ehehhh
ehehhh

Reputation: 1074

Sending a file through a socket in C

I got a task at school to write an FTP program in C language (for Linux). I got all the basic functionality working in no time (ls, cd), but I'm having troubles with the file transfer part. I use sendfile to send the file over the socket like this:

int fd = open(temp, O_RDONLY);  
int rc = sendfile (client_fd, fd, &offset, statbuf.st_size);

I can't seem to figure out how to receive this file on the client end. I tried it like this for debugging:

while( (i = read(sock, message, MSG_LEN - 1)) > 0 ) {

    message[i] = '\0';
    printf("%s", message);
}

This does a good job at printing out text files, but if I try to send binary files, for example, it just prints out the beginning of the binary file and hangs at the read() part (since there's nothing coming from server, I think).

I appreciate any suggestions!

Upvotes: 0

Views: 3099

Answers (1)

caf
caf

Reputation: 239011

You need to shutdown the writing side of the socket after sending the file, so that the receiver knows the end of the file has been reached:

shutdown(client_fd, SHUT_WR);

(shutdown() is used instead of close(), so that you can find out if the other side successfully received the whole file or not).

Your reading side then will see end-of-file (read() returning 0), at which point it should close() its end of the socket. The server will then see end-of-file, and it can close its socket too (and record a successful transfer).

Upvotes: 2

Related Questions