Thursday 4 December 2014

UDP Programming for client Full Duplex Communication
#include<stdio.h>
#include<sys/ipc.h>
#include<sys/socket.h>
#include<sys/stat.h>
#include<stdlib.h>
#include<netinet/in.h>
#include<string.h>
main(int argc,char **argv)
{
int sd,newsd,ret,i,j;
socklen_t len;
char buf[20],temp;
struct sockaddr_in cAddr,sAddr;
sd=socket(PF_INET,SOCK_DGRAM,0);
if(sd==-1)
{
perror("socket");
return;
}
sAddr.sin_family=PF_INET;
sAddr.sin_port=htons(atoi(argv[2]));
sAddr.sin_addr.s_addr=inet_addr(argv[1]);
if(fork()==0)
{
while(1)
{
printf("enter msg:");
scanf("%s",buf);
sendto(sd,buf,strlen(buf),0,(struct sockaddr*)&sAddr,sizeof(sAddr));
//printf("connect successful\n");
}
}
else
{
while(1)
{
printf("waiting for message....\n");
bzero(buf,20);
socklen_t y=sizeof(cAddr);
recvfrom(sd,buf,20,0,(struct sockaddr *)&sAddr,&y);
for(i=0,j=strlen(buf)-1;i<j;i++,j--)
{
temp=buf[i];
buf[i]=buf[j];
buf[j]=temp;
}

printf("received msg:%s\n",buf);

//if(strcmp(buf,"QUIT")==0)
//break;
//printf("%s %s\n",inet_ntoa(cAddr.sin_addr.s_addr),buf);
}
}
close(sd);
}

UDP Programming for Server Full Duplex Communication
#include<stdio.h>
#include<sys/ipc.h>
#include<sys/socket.h>
#include<sys/stat.h>
#include<stdlib.h>
#include<netinet/in.h>
#include<string.h>
main(int argc,char **argv)
{
int sd,newsd,ret,i,j;
socklen_t len;
char buf[20],temp;
struct sockaddr_in cAddr,sAddr;
sd=socket(PF_INET,SOCK_DGRAM,0);
if(sd==-1)
{
perror("socket");
return;
}
sAddr.sin_family=PF_INET;
sAddr.sin_port=htons(atoi(argv[1]));
sAddr.sin_addr.s_addr=inet_addr("0.0.0.0");
if(bind(sd,(struct sockaddr*)&sAddr,sizeof(sAddr))==-1)
perror("bind");
else
printf("bind sucess\n");
socklen_t y=sizeof(cAddr);
//printf("connect successful\n");
recvfrom(sd,buf,20,0,(struct sockaddr *)&cAddr,&y);
if(fork()==0)
{
while(1)
{
printf("waiting for message....\n");
bzero(buf,20);
recvfrom(sd,buf,20,0,(struct sockaddr *)&cAddr,&y);
for(i=0,j=strlen(buf)-1;i<j;i++,j--)
{
temp=buf[i];
buf[i]=buf[j];
buf[j]=temp;
}
printf("recv=%s\n",buf);
printf("%s %s\n",inet_ntoa(cAddr.sin_addr.s_addr),buf);
}
}
else
{
while(1)
{
printf("enter msg:");
scanf("%s",buf);
sendto(sd,buf,strlen(buf),0,(struct sockaddr*)&cAddr,sizeof(cAddr));
}
}

close(sd);
}