C. UDP Socket Programming in Unix Using C Programming

ECHO SERVER USING

/*ECHO SERVER USING UDP IN C*/

#include<netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include<stdio.h>
#include <arpa/inet.h>
#include <string.h>
#include<fcntl.h>

main() {
 int sfd, l;
 char buf[1024] = "", buf1[1024] = "";
 struct sockaddr_in ser;
 sfd = socket(AF_INET, SOCK_DGRAM, 0);
 bzero(&ser, sizeof (ser));
 ser.sin_family = AF_INET;
 ser.sin_port = htons(1300);
 inet_aton("localhost", &ser.sin_addr);
 printf("Enter the message:");
 scanf("%s", buf);
 sendto(sfd, buf, strlen(buf), 0, (struct sockaddr *) &ser, sizeof (ser));
 recvfrom(sfd, buf1, 1024, 0, NULL, NULL);
 close(sfd);
}

ECHO CLIENT USING UDP

/*ECHO CLIENT USING UDP IN C*/
#include<netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include<stdio.h>
#include <arpa/inet.h>
#include <string.h>
#include<fcntl.h>

main() {
 int sfd, l;
 char buf[1024] = "";
 struct sockaddr_in server, client;
 sfd = socket(AF_INET, SOCK_DGRAM, 0);
 bzero(&server, sizeof (server));
 server.sin_family = AF_INET;
 server.sin_port = htons(1300);
 inet_aton("localhost", &server.sin_addr);
 printf("bind=%d\n", bind(sfd, (struct sockaddr *) &server, sizeof (server)));
 l = sizeof (client);
 for (;;) {
   recvfrom(sfd, buf, 1024, 0, (struct sockaddr *) &client, &l);
   sendto(sfd, buf, strlen(buf), 0, (struct sockaddr *) &client, l);
   printf("MESSAGE FROM CLIENT:%s\n", buf);
 }
}


Server Sample Output

cc udpechoserver.c -o echo
./echo
bind=0
MESSAGE FROM CLIENT:hello

Client Sample Output: 

cc udpechoclient.c -o udpecho
./udpecho
Enter the message:
hello