I want to ask, why I cannot transfer file from server to client?
When I start to send the file from server, the client side program will have problem.
So, I spend some times to check the code,
But I still cannot find out the problem
Can anyone point out the problem for me?
CLIENTFILE.C
#include stdio.h
#include stdlib.h
#include time.h
#include netinet/in.h
#include fcntl.h
#include sys/types.h
#include string.h
#include stdarg.h
#define PORT 5678
#define MLEN 1000
int main(int argc, char *argv [])
{
int sockfd;
int number,message;
char outbuff[MLEN],inbuff[MLEN];
//char PWD_buffer[_MAX_PATH];
struct sockaddr_in servaddr;
FILE *fp;
int numbytes;
char buf[2048];
if (argc != 2)
fprintf(stderr, "error");
if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
fprintf(stderr, "socket error");
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(PORT);
if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0)
fprintf(stderr, "connect error");
if ( (fp = fopen("/home/na/nall9047/write.txt", "w")) == NULL){
perror("fopen");
exit(1);
}
printf("Still NO PROBLEM!\n");
//Receive file from server
while(1){
numbytes = read(sockfd, buf, sizeof(buf));
printf("read %d bytes, ", numbytes);
if(numbytes == 0){
printf("\n");
break;
}
numbytes = fwrite(buf, sizeof(char), numbytes, fp);
printf("fwrite %d bytes\n", numbytes);
}
fclose(fp);
close(sockfd);
return 0;
}
SERVERFILE.C
#include stdio.h
#include fcntl.h
#include stdlib.h
#include time.h
#include string.h
#include netinet/in.h
#include errno.h
#include sys/types.h
#include sys/socket.h
#includ estdarg.h
#define PORT 5678
#define MLEN 1000
int main(int argc, char *argv [])
{
int listenfd, connfd;
int number, message, numbytes;
int h, i, j, alen;
int nread;
struct sockaddr_in servaddr;
struct sockaddr_in cliaddr;
FILE *in_file, *out_file, *fp;
char buf[4096];
listenfd = socket(AF_INET, SOCK_STREAM, 0);
if (listenfd < 0)
fprintf(stderr,"listen error") ;
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);
if (bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0)
fprintf(stderr,"bind error") ;
alen = sizeof(struct sockaddr);
connfd = accept(listenfd, (struct sockaddr *) &cliaddr, &alen);
if (connfd < 0)
fprintf(stderr,"error connecting") ;
printf("accept one client from %s!\n", inet_ntoa(cliaddr.sin_addr));
fp = fopen ("/home/na/nall9047/read.txt", "r"); // open file stored in server
if (fp == NULL) {
printf("\nfile NOT exist");
}
//Sending file
while(!feof(fp)){
numbytes = fread(buf, sizeof(char), sizeof(buf), fp);
printf("fread %d bytes, ", numbytes);
numbytes = write(connfd, buf, numbytes);
printf("Sending %d bytes\n",numbytes);
}
fclose (fp);
close(listenfd);
close(connfd);
return 0;
}