File Transfer Using TCP/IP

FILE TRANSFER USING TCP / IP
SERVER:
#include <unistd.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/socket.h>
#include <stdio.h>
int main()
{
int sd,nsd,i,port=6200;
char c[30]="\0",fname[30];
struct sockaddr_in ser;
struct sockaddr_in cli;
FILE *fp;
if ((sd=socket(AF_INET,SOCK_STREAM,0))<0)
{
printf("\nError:Socket Creation");
return 0;
}
bzero((char*)&ser,sizeof(ser));
printf("\nPort Address is %d",port);
ser.sin_family=AF_INET;
ser.sin_port=htons(port);
ser.sin_addr.s_addr=htonl(INADDR_ANY);
if (bind(sd,(struct sockaddr*)&ser,sizeof(ser))<0)
{
printf("\nError:Binding");
return 0;
}
i=sizeof(cli);
listen(sd,1);
printf("\nServer Module\n");
nsd=accept(sd,(sd,(struct sockaddr*)&cli),&i);
if (nsd==-1)
{
printf("\nError:Client accepts the problem");
return 0;
}
printf("\nClient Accepted\n");
i=recv(nsd,fname,30,0);
fname[i]='\0';
fp=fopen(fname,"rb");
printf("File Reading....\n");
while(1)
{
i=fread(&c,1,30,fp);
c[i]='\0';
send(nsd,c,30,0);
printf("%s",c);
strcpy(c,"\0");
if(i<30) break;
}
send(nsd,"EOF",4,0);
printf("\nFile has been Transfered");
fclose(fp);
close(sd);
close(nsd);
return 0;
}
CLIENT:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
int main()
{
int sd,nsd,i,port=6200;
char c[30]="\0",fname[30],file[30];
FILE *fp;
struct sockaddr_in ser;
if ((sd=socket(AF_INET,SOCK_STREAM,0))<0)
{
printf("\nError:Socket Creation");
return 0;
}
bzero((char *)&ser,sizeof(ser));
printf("\nPort Address is %d",port);
ser.sin_family=AF_INET;
ser.sin_port=htons(port);
ser.sin_addr.s_addr=htonl(INADDR_ANY);
if (connect(sd,(struct sockaddr*)&ser,sizeof(ser))==-1)
{
printf("\nError:Binding");
return 0;
}
printf("Client Module\n");
printf("Enter the source Filename:");
scanf("%s",fname);
printf("\nEnter the Destination file name:");
scanf("%s",file);
send(sd,fname,30,0);
fp=fopen(file,"w");
printf("Receiving....\n");
while(1)
{
i=recv(sd,c,30,0);
c[i]='\0';
printf("%s",c);
if(!strcmp(c,"EOF"))
break;
fwrite(&c,strlen(c),1,fp);
strcpy(c,"\0");
}
printf("\n File Transfered");
fclose(fp);
close(sd);
return 0;
}
Output:
Port Address is 6200
Server Module
Client Accepted
File Reading....
hello hai
----------------------------------------------------
Port Address is 6200
Client Module
Enter the source Filename:a2.txt
Enter the Destination file name:aa.txt
Receiving....
hello hai