i am trying to send a file between a client and a server using sockets in C....well i see that there is a function sendfile(), but i donno its usage, can someone guide me with an example how to send a file and receive it.....

6 Years
Discussion Span
Last Post by aShu5tosh

sendfile() is used to transfer data between file descriptors. The prototype of sendfile() is as follows,

#include <sys/sendfile.h>
ssize_t sendfile(int out_fd, int in_fd, off_t *offset, size_t count);

It basically copies file data from one file descriptor to another in local machine.
So, not sure if sendfile can be used to transfer file data across network using Socket APIs, but in man page of sendfile a note is mentioned as below,
If you plan to use sendfile() for sending files to a TCP socket, but need to send some header data in front of the file contents, you will find it useful
to employ the TCP_CORK option, described in tcp(7), to minimize the number of packets and to tune performance.

In Linux 2.4 and earlier, out_fd could refer to a regular file, and sendfile() changed the current offset of that file.
So, need to explore these options and try it out....

I wrote a simple prog. to just copy file data from one file to another on same machine.... this shows the usage of sendfile, but you need to modify it further to use it on socket file descriptor. Below is my sample code:

#include <sys/sendfile.h>

int in_fd, out_fd=0;
if(in_fd < 0)
perror("open failed");

if(out_fd < 0)
perror("open failed");


return 0;

Edited by Nick Evan: Fixed formatting

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.