server.c
client.c
#include "stdio.h" #include "string.h" #include "sys/types.h" #include "sys/socket.h" #include "arpa/inet.h" #include "netinet/in.h" #define SA struct sockaddr int main(int argc,char** argv) { int sockfd; int n=0,clilen; char fname[20],content[2000],ch; FILE *fp; struct sockaddr_in servaddr,cliaddr; if(argc!=2) { printf("usage ./server PORT\n"); return 0; } //create socket sockfd = socket(AF_INET,SOCK_DGRAM,0); //fill structure servaddr.sin_family = AF_INET; servaddr.sin_port = htons(atoi(argv[1])); servaddr.sin_addr.s_addr = INADDR_ANY; //bind bind(sockfd,(SA*)&servaddr,sizeof(servaddr)); //getting filename from client clilen=sizeof(cliaddr); recvfrom(sockfd,fname,sizeof(fname),0,(SA*)&cliaddr,&clilen); //open the file for reading fp = fopen(fname,"r"); while(1) { ch = fgetc(fp); if(ch!=EOF) { content[n++]=ch; } else break; } fputs(content,stdout); //send the file content to client sendto(sockfd,content,sizeof(content),0,(SA*)&cliaddr,sizeof(cliaddr)); return 0; }
client.c
#include "stdio.h" #include "sys/types.h" #include "sys/socket.h" #include "arpa/inet.h" #include "netinet/in.h" #include "string.h" #define SA struct sockaddr int main(int argc,char** argv) { int sockfd,len; struct sockaddr_in servaddr; char fname[20],content[2000]; if(argc!=3) { printf("usage ./client PORT FILENAME\n"); return 0; } strcpy(fname,argv[2]); //create socket sockfd = socket(AF_INET,SOCK_DGRAM,0); //fill structure servaddr.sin_family = AF_INET; servaddr.sin_port = htons(atoi(argv[1])); servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); //send filename sendto(sockfd,fname,sizeof(fname),0,(SA*)&servaddr,sizeof(servaddr)); //receive the file content from server len=sizeof(servaddr); bzero(content,sizeof(content)); recvfrom(sockfd,content,sizeof(content),0,NULL,NULL); //print the file contents printf("contents of the %s:\n\n",fname); fputs(content,stdout); return 0; }
Comments
Post a Comment