shishira
shishira

Reputation: 59

how can we send a text file from client to the server?

I am trying to send a file from client to the server using C socket programming. but in the server side I am not able to receive the file which I had sent from the client. I am attaching the codes below.

server:

/*  Create a connection queue and wait for clients.  */

listen(server_sockfd, 5);
while(1) {
    char ch;

    printf("server waiting\n");

/*  Accept a connection.  */

    client_len = sizeof(client_address);
client_sockfd = accept(server_sockfd,(struct sockaddr*)&client_address,cli);
    if(client_sockfd > 0)
    printf("client is connected\n");
/*  We can now read/write to client on client_sockfd.  */
  char *fh;
    recv(client_sockfd,fh,1024+1,0);
    printf("server recieved %s",fh);

/*        read(client_sockfd, &ch, 1);
    ch++;
    write(client_sockfd, &ch, 1); */
   return close(client_sockfd);
}
}

Upvotes: 0

Views: 500

Answers (1)

David Ranieri
David Ranieri

Reputation: 41017

You need to check the return of recv

if ((nbytes = recv(client_sockfd,fh,1024+1,0)) > 0)

and end your buffer with '\0'

fh[nbytes] = '\0';
printf("server recieved %s",fh);

Also, is not a good idea to use magic numbers like 1024+1

Upvotes: 3

Related Questions