Algorithms_in_C 1.0.0
Set of algorithms implemented in C.
Loading...
Searching...
No Matches
udp_server.c File Reference

Server side implementation of UDP client-server model. More...

#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Include dependency graph for udp_server.c:

Macros

#define PORT   8080
 port number to connect to
 
#define MAXLINE   1024
 maximum characters per line
 

Functions

int main ()
 Driver code.
 

Detailed Description

Server side implementation of UDP client-server model.

Author
TheShubham99
Krishna Vedala
See also
client_server/udp_client.c

Function Documentation

◆ main()

int main ( void  )

Driver code.

36{
37#ifdef _WIN32
38 // when using winsock2.h, startup required
39 WSADATA wsData;
40 if (WSAStartup(MAKEWORD(2, 2), &wsData) != 0)
41 {
42 perror("WSA Startup error: \n");
43 return 0;
44 }
45
46 atexit(cleanup); // register at-exit function
47#endif
48
49 int sockfd;
50 char buffer[MAXLINE];
51 char *hello = "Hello from server";
52 struct sockaddr_in servaddr, cliaddr;
53
54 // Creating socket file descriptor
55 if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
56 {
57 perror("socket creation failed");
58 exit(EXIT_FAILURE);
59 }
60
61 memset(&servaddr, 0, sizeof(servaddr));
62 memset(&cliaddr, 0, sizeof(cliaddr));
63
64 // Filling server information
65 servaddr.sin_family = AF_INET; // IPv4
66 servaddr.sin_addr.s_addr = INADDR_ANY;
67 servaddr.sin_port = htons(PORT);
68
69 // Bind the socket with the server address
70 if (bind(sockfd, (const struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
71 {
72 perror("bind failed");
73 exit(EXIT_FAILURE);
74 }
75
76 unsigned int len;
77 int n;
78 n = recvfrom(sockfd, (char *)buffer, MAXLINE, MSG_WAITALL,
79 (struct sockaddr *)&cliaddr, &len);
80 buffer[n] = '\0';
81 printf("Client : %s\n", buffer);
82 sendto(sockfd, (const char *)hello, strlen(hello), 0,
83 (const struct sockaddr *)&cliaddr, len);
84 printf("Hello message sent.\n");
85
86 close(sockfd);
87
88 return 0;
89}
struct used to store character in certain times
Definition min_printf.h:35
#define MAXLINE
maximum characters per line
Definition udp_server.c:27
#define PORT
port number to connect to
Definition udp_server.c:26