TCPIP Client Half Duplex Communication 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,ret; socklen_t len; char buf[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); ret=send(sd,buf,strlen(buf),0); if(strcmp(buf,"QUIT")==0) //exit(0); break; if(ret==-1) { perror("send"); return; } printf("waiting for data...\n"); bzero(buf,20); recv(sd,buf,20,0); if(strcmp(buf,"QUIT")==0) break; printf("received: %s\n",buf); } close(sd); }TCPIP Server half Duplex Communication 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,ret; socklen_t len; char buf[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); recv(newsd,buf,20,0); if(strcmp(buf,"QUIT")==0) break; printf("received: %s\n",buf); printf("enter msg to send...\n"); gets(buf); ret=send(newsd,buf,strlen(buf),0); if(strcmp(buf,"QUIT")==0) //exit(0); break; if(ret==-1) { perror("send"); return; } } close(sd); close(newsd); }