Thursday, 4 December 2014

Half Duplex Communication Using TCP IP Protocol

TCPIP Client Half Duplex Communication Method-2 Program
#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,n,newsd1;
socklen_t len;
char buf[20],buf1[20];
struct sockaddr_in cAddr,sAddr;
sd=socket(PF_INET,SOCK_STREAM,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(connect(sd,(struct sockaddr *)&sAddr,sizeof(sAddr))==-1)
{
perror("connect");
return;
}
printf("connect successful\n");
while(1)
{
printf("enter msg to send...\n");
gets(buf);
n=send(sd,buf,strlen(buf),0);
if(n<0)
{
perror("send");
return;
}
printf("send successful\n");
//if(strcmp(buf,"exit")==0)
//exit(0);
n=recv(newsd,buf1,20,0);
if(n<0)
{
perror("EBADF");
return;
}
printf("%s",buf1);
if(strcmp(buf,"exit")==0)
exit(0);
}
close(sd);
}

TCPIP Server Half Duplex Communication Method-2 Program
#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,n;
socklen_t len;
char buf[20],buf1[20];
struct sockaddr_in cAddr,sAddr;
sd=socket(PF_INET,SOCK_STREAM,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");
return;
}
printf("bind successful....\n");
listen(sd,5);
len=sizeof(cAddr);
printf("waiting for client request...\n");
newsd=accept(sd,(struct sockaddr *)&cAddr,&len);
if(newsd==-1)
{
perror("accept");
return;
}
printf("connection accepted\n");
while(1)
{
printf("waiting for data...\n");
bzero(buf,20);
n=recv(newsd,buf,20,0);
if(n<0)
{
perror("recv");
return;
}
bzero(buf1,20);
printf("received: %s\n",buf);
printf("enter data to send...\n");
gets(buf1);
n=send(sd,buf1,strlen(buf),0);
if(n<0)
{
perror("send");
return;
}
//printf("%s",buf1);
if(strcmp(buf1,"exit")==0)
exit(0);
//if(strcmp(buf,"exit")==0)
//exit(0);
}
close(sd);
close(newsd);
}