Choose Category
chatappserver.c #include<sys/socket.h> #include<sys/types.h> #include<stdio.h> #include<arpa/inet.h> #include<netinet/in.h> #include<string.h> #include<unistd.h> #define SER_PORT 1200 int main() { int a,sersock,newsock,n; char str[25],str2[25]; struct sockaddr_in seraddr; struct sockaddr_in cliinfo; socklen_t csize=sizeof(cliinfo); seraddr.sin_family=AF_INET; seraddr.sin_port=htons(SER_PORT); seraddr.sin_addr.s_addr=htonl(INADDR_ANY); if((sersock=socket(AF_INET,SOCK_STREAM,0))<0) { error("\n socket"); exit(0); } if(bind(sersock,(struct sockaddr *)&seraddr,sizeof(seraddr))<0) { error("\nBIND"); exit(0); } if(listen(sersock,1)<0) { error("\n LISTEN"); } if((newsock=accept(sersock,(struct sockaddr *)&cliinfo,&csize))<0) { error("\n ACCEPT"); exit(0); } else printf("\n now connected to %s\n",inet_ntoa(cliinfo.sin_addr)); read(newsock,str,sizeof(str)); do { printf("\n client msg:%s",str); printf("\n server msg:"); scanf("%s",str2); write(newsock,str2,sizeof(str2)); listen(newsock,1); read(newsock,str,sizeof(str)); n=strcmp(str,"BYE"); a=strcmp(str2,"BYE"); } while(n!=0||a!=0); close(newsock); close(sersock); return 0; }
chatappclient.c #include<stdio.h> #include<sys/socket.h> #include<sys/types.h> #include<arpa/inet.h> #include<netinet/in.h> #include<unistd.h> #define SER_PORT 1200 int main(int count,char*arg[]) { int a,clisock; char str[20],str2[20]; struct sockaddr_in cliaddr; cliaddr.sin_port=htons(SER_PORT); cliaddr.sin_family=AF_INET; cliaddr.sin_addr.s_addr=inet_addr(arg[1]); clisock=socket(AF_INET,SOCK_STREAM,0); if(clisock<0) { perror("\n SOCKET"); exit(0); } if(connect(clisock,(struct sockaddr*)&cliaddr,sizeof(cliaddr))<0) { perror("\n CONNECT"); exit(0); } printf("\nclient connected to %s",arg[1]); printf("\nCLIENT"); scanf("%s",&str); if(write(clisock,str,sizeof(str))<0) { printf("\n data could not be sent"); } do { listen(clisock,1); read(clisock,str2,sizeof(str2)); printf("\nserver msg:%s",str2); printf("\nclient msg:"); scanf("%s",&str); a=strcmp(str2,"BYE"); write(clisock,str2,sizeof(str2)); } while(a!=0); close(clisock); return 0; }