A UDP Client Server program

Submitted on Sat, 06/12/2021 - 10:39
UDP Server

#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char* argv[]) {
//structure to store server socket details
struct sockaddr_in srv;
//server socket details 
srv.sin_family=AF_INET;
srv.sin_port=htons(atoi(argv[2]));
inet_aton(argv[1],&srv.sin_addr);
//structure to store client socket details
struct sockaddr_in cli;
//character array to store udp datagarm
char buff[1024];
//creating the udp socket
int fd=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
if(fd==-1) {perror("Something is wrong.");}
else {printf("%s","\nUDP socket created by the server.");}
//binding the socket to a local ip address
int ibind=bind(fd,(struct sockaddr*)&srv,sizeof(srv));
if(ibind==-1) {perror("something is wrong.");}
else {printf("%s","\nUDP Socket binding successful.");}
int clilen=sizeof(cli);
while(1) {
memset(&buff,0,sizeof(buff));
recvfrom(fd,buff,1024,0,(struct sockaddr*)&cli,&clilen);
printf("\nClient: %s",buff);
memset(&buff,0,sizeof(buff));
printf("\nServer: ");
fgets(buff,1024,stdin);
sendto(fd,buff,1024,0,(struct sockaddr*)&cli,clilen);
}
close(fd);
return 0;
}

 

 

UDP Client:

#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char* argv[]){
//creating a socket
int fd=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
if(fd==-1) {perror("Something is wrong.");}
else {
printf("%s","\nUDP socket created by the client.");
}
//structure to store client socket details
struct sockaddr_in cli;
//socket details
cli.sin_family=AF_INET;
cli.sin_port=htons(atoi(argv[2]));
inet_aton(argv[1],&cli.sin_addr);
//udp data buffer
char buff[1024];
int clilen=sizeof(cli);
while(1) {
memset(&buff,0,sizeof(buff));
printf("\nClient: ");
fgets(buff,1024,stdin);
sendto(fd,buff,1024,0,(struct sockaddr*)&cli,sizeof(cli));
memset(&buff,0,sizeof(buff));
recvfrom(fd,buff,1024,0,(struct sockaddr*)&cli,&clilen);
printf("\nServer: %s",buff);
}
}