Can the recv() function receive more bytes than its internal buffer?

755 Views Asked by At

I am new to sockets in Linux and trying to understand how the recv() works. Tried a scenario where I couldn't find an explanation clearly. I hope somebody out there can enlighten me. Here is the scenario:

Using TCP Sockets to send data of 5 MiB between two process (Sender and Receiver). I execute these process on i.MX6 Sabrelite board which is running Linux.

Sender.cpp:

char buffer[5MB];
send(sendSocket, (void*) buffer, 5 MiB, 0);

Receiver.cpp:

char buffer[5 MiB];
int count = 0;
do {
    rbytes = recv(receiveSocket, (void*) buffer, 5MB, 0);
    printf("Recv'd %d. %d\n",count,rbytes);
    count++;
} while (rbytes!=0);

I used the getsockopt() function call before receiving to get the internal buffer SO_RCVBUF size. It was around 86 KiB.

I wanted to see how many recv() calls did it take to get 5 MiB and how many bytes for each recv() call.

After receiving 5 MiB I check the output. It nearly takes 48 recv() calls to get 5 MiB of data. For the first 40 calls it received less than 86 KiB which makes sense as bytes received is less than the internal buffer. If I had received double of 86 KiB then some explanation I had come across was that the kernel usually allocates twice of what is shown in SO_RCVBUF.

But I am receiving more bytes than the double of 86 KiB.

Can I trust the SO_RCVBUF size using getsockopt()?

Does it dynamically change its values?

Just tried another iteration of the same scenario. The number of recv() call varies. But the bytes I receive is sometimes more than allocated.

1

There are 1 best solutions below

2
On

According to this thread, the kernel allocates twice as much buffer space as you request with SO_RCVBUF.