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.....

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<stdio.h>
#include<fcntl.h>
#include<stdlib.h>
#include <sys/sendfile.h>


int
main()
{
int in_fd, out_fd=0;
in_fd=open("foo",O_RDWR);
if(in_fd < 0)
{
perror("open failed");
exit(EXIT_FAILURE);
}


out_fd=open("bar",O_RDWR);
if(out_fd < 0)
{
perror("open failed");
exit(EXIT_FAILURE);
}


sendfile(out_fd,in_fd,NULL,22);


return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.