Wednesday, July 14, 2010

UDP Echo Server Client Program

UDP - User Datagram Protocol

(To know more Click the below link)

http://en.wikipedia.org/wiki/User_Datagram_Protocol

TCP Vs UDP

TCP -
Reliable, Ordered, Heavyweight, Streaming.

UDP - Unreliable, Not Ordered, Lightweight, Datagrams.

Screenshot of the Output




Program


Server.c

#include "stdio.h"
#include "sys/types.h"
#include "sys/socket.h"
#include "netinet/in.h"
#include "string.h"
#include "stdlib.h"
int main()
{
int len,sfd,connfd,i=0,r,b,l,port;
char buff[1024],str[1024],c;
struct sockaddr_in servaddr,cliaddr;
socklen_t clilen;
sfd=socket(AF_INET,SOCK_DGRAM,0);
if(sfd==-1)
{
perror("Socket");
exit(-1);
}
memset(servaddr.sin_zero,'\0',sizeof(servaddr.sin_zero));
printf("\n Enter the port no:");
scanf("%d",&port);
printf("\n Port No is %d",port);
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=INADDR_ANY;
servaddr.sin_port=htons(port);
b=bind(sfd,(struct sockaddr*)&servaddr, sizeof(servaddr));
if(b==-1)
{
perror("bind");
exit(-1);
}
clilen=sizeof(cliaddr);
r=recvfrom(sfd,buff,sizeof(buff),0,(struct sockaddr*)&cliaddr, &clilen);
buff[r]=0;
printf("\n Client:%s",buff);
printf("\n Server:%s",buff);
sendto(sfd,buff,sizeof(buff),0,(struct sockaddr*)&cliaddr,sizeof(cliaddr));
exit(0);
return 0;
}


Client.c

#include "stdio.h"
#include "sys/types.h"
#include "sys/socket.h"
#include "netinet/in.h"
#include "string.h"
#include "stdlib.h"
int main()
{
int len,listenfd,connfd,i=0,r,co,port;
char buff[1024],c;
struct sockaddr_in servaddr,cliaddr;
socklen_t servlen;
listenfd=socket(AF_INET,SOCK_DGRAM,0);
if(listenfd==-1)
{
perror("socket");
exit(-1);
}
memset(servaddr.sin_zero,'\0',sizeof(servaddr.sin_zero));
printf("\n Enter the port no:");
scanf("%d",&port);
printf("\n Port No is : %d",port);
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=INADDR_ANY;
servaddr.sin_port=htons(port);
printf("\n Client:");
scanf("%s",buff);
sendto(listenfd,buff,sizeof(buff),0,(struct sockaddr*)&servaddr,sizeof(servaddr));
r=recvfrom(listenfd,buff,sizeof(buff),0,(struct sockaddr*)&servaddr, &servlen);
buff[r]=0;
printf("\n Server:%s\n",buff);
exit(0);
return 0;
}


Download The Source Code

UDP_Server.c

UDP_Client.c

No comments: