Question: send an integer from client to server and Reverse that number in Server after that Send result to client
TCPIP Client number reverse Program
TCPIP Client number reverse 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,i,j,num,res; socklen_t len; char buf[20],ch; 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"); printf("enter msg to send...\n"); scanf("%d",&num); send(sd,&num,4,0); recv(sd,&res,4,0); printf("number after reverse is:%d\n",res); close(sd); }TCPIP Server Number reverse 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,i,j,rev=0,res=0,num=0; socklen_t len; char buf[20],ch; 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(sAddr); printf("waiting for client request...\n"); newsd=accept(sd,(struct sockaddr *)&cAddr,&len); if(newsd==-1) { perror("accept"); return; } printf("connection accepted\n"); printf("waiting for data...\n"); //bzero(num,20); recv(newsd,&num,4,0); printf("num:%d\n",num); while(num>0) { //rev=rev*10; rev=(rev*10)+(num%10); num=(num/10); } printf("reversed num is %d\n",rev); ret=send(newsd,&rev,4,0); if(ret==-1) perror("send"); else printf("send successful...\n"); close(sd); close(newsd); }