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

Client 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_client.c:

Macros

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

Functions

int main ()
 Driver code.
 

Detailed Description

Client side implementation of UDP client-server model.

Author
TheShubham99
Krishna Vedala
See also
client_server/udp_server.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 client";
52 struct sockaddr_in servaddr;
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
63 // Filling server information
64 servaddr.sin_family = AF_INET;
65 servaddr.sin_port = htons(PORT);
66 servaddr.sin_addr.s_addr = INADDR_ANY;
67
68 int n;
69 unsigned int len;
70
71 sendto(sockfd, (const char *)hello, strlen(hello), 0,
72 (const struct sockaddr *)&servaddr, sizeof(servaddr));
73 printf("Hello message sent.\n");
74
75 n = recvfrom(sockfd, (char *)buffer, MAXLINE, MSG_WAITALL,
76 (struct sockaddr *)&servaddr, &len);
77 buffer[n] = '\0';
78 printf("Server : %s\n", buffer);
79
80 close(sockfd);
81 return 0;
82}
struct used to store character in certain times
Definition min_printf.h:35
#define MAXLINE
maximum characters per line
Definition udp_client.c:27
#define PORT
port number to connect to
Definition udp_client.c:26