Send part of a file over a socket with sendfile and an offset
Send a byte range of a file to a socket with sendfile(2) and an in/out offset pointer, which leaves the file's own position alone. Linux 5.x.
To serve a range request you want bytes 4096 to 8191 of a file on a socket, with no copy through user space. sendfile(out_fd, in_fd, &offset, count) reads from in_fd starting at *offset and advances *offset by the amount sent. When you pass an offset pointer, the file descriptor's own position is not used or changed, so concurrent senders sharing one descriptor do not disturb each other.
#include <sys/sendfile.h>
#include <sys/types.h>
#include <errno.h>
ssize_t send_range(int sock, int filefd, off_t start, size_t count)
{
off_t off = start;
size_t left = count;
while (left > 0) {
ssize_t n = sendfile(sock, filefd, &off, left);
if (n < 0) {
if (errno == EINTR)
continue;
return -1;
}
if (n == 0)
break; /* file ended early */
left -= (size_t)n;
}
return (ssize_t)(count - left);
}sendfile may send less than asked: the socket buffer fills, or a signal arrives. That is why the loop exists, and on a non-blocking socket you wait for writability when it returns EAGAIN. A single call also moves at most 2,147,479,552 bytes on Linux, so large files always need the loop. The input must be a file that supports mmap-like reads, so not another socket. If the connection later switches to kTLS, the same call keeps working, since encryption happens in the kernel. See sendfile(2).