Question: client needs to send request to server, then server respond to the client request. Implement this method using TCP IP Protocol
TCPIP Client Upload and download data Program
TCPIP Client Upload and download data 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; socklen_t len; char buf[80],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 name of file to download...\n"); gets(buf); ret=send(sd,buf,strlen(buf),0); if(ret==-1) { perror("send"); return; } printf("file name send successfully...\n"); while(recv(sd,buf,80,0)) { if(strcmp(buf,"complete")==0) break; else{ printf("received: %s\n",buf); } } printf("message downloaded successfully...\n"); close(sd); }TCPIP Server Upload Download data 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,j,pos; socklen_t len; char buf[20],ch,str[80]; 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"); printf("waiting for file name from client...\n"); bzero(buf,20); recv(newsd,buf,20,0); FILE *fp; fp=fopen(buf,"r"); if(fp==NULL) { printf("file cannot be opened..\n"); return; } fseek(fp,0,2); pos=ftell(fp); printf("size=%d\n",pos); rewind(fp); int i=0; /*while((ch=fgetc(fp))!=EOF) { str[i]=ch; i++; }*/ while((fgets(str,80,fp))!=NULL) ret=send(newsd,str,strlen(str),0); //ret=send(newsd,str,strlen(str),0); if(ret==-1) { perror("send"); return; } strcpy(str,"complete"); ret=send(newsd,str,strlen(str),0); printf("send successfull...\n"); //printf("received: %s\n",buf); close(sd); close(newsd); }