mirror of
https://github.com/TheAlgorithms/C
synced 2024-11-25 23:09:36 +03:00
Added UDP server Algo
This commit is contained in:
parent
564ef7ad6d
commit
3dc4aaee33
55
Simple Client Server/UDPServer.c
Normal file
55
Simple Client Server/UDPServer.c
Normal file
@ -0,0 +1,55 @@
|
||||
// Server side implementation of UDP client-server model
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
#include <string.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/socket.h>
|
||||
#include <arpa/inet.h>
|
||||
#include <netinet/in.h>
|
||||
|
||||
#define PORT 8080
|
||||
#define MAXLINE 1024
|
||||
|
||||
// Driver code
|
||||
int main() {
|
||||
int sockfd;
|
||||
char buffer[MAXLINE];
|
||||
char *hello = "Hello from server";
|
||||
struct sockaddr_in servaddr, cliaddr;
|
||||
|
||||
// Creating socket file descriptor
|
||||
if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) {
|
||||
perror("socket creation failed");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
memset(&servaddr, 0, sizeof(servaddr));
|
||||
memset(&cliaddr, 0, sizeof(cliaddr));
|
||||
|
||||
// Filling server information
|
||||
servaddr.sin_family = AF_INET; // IPv4
|
||||
servaddr.sin_addr.s_addr = INADDR_ANY;
|
||||
servaddr.sin_port = htons(PORT);
|
||||
|
||||
// Bind the socket with the server address
|
||||
if ( bind(sockfd, (const struct sockaddr *)&servaddr,
|
||||
sizeof(servaddr)) < 0 )
|
||||
{
|
||||
perror("bind failed");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
int len, n;
|
||||
n = recvfrom(sockfd, (char *)buffer, MAXLINE,
|
||||
MSG_WAITALL, ( struct sockaddr *) &cliaddr,
|
||||
&len);
|
||||
buffer[n] = '\0';
|
||||
printf("Client : %s\n", buffer);
|
||||
sendto(sockfd, (const char *)hello, strlen(hello),
|
||||
MSG_CONFIRM, (const struct sockaddr *) &cliaddr,
|
||||
len);
|
||||
printf("Hello message sent.\n");
|
||||
|
||||
return 0;
|
||||
}
|
Loading…
Reference in New Issue
Block a user