Effect SO_SNDBUF

I can’t understand how and why the following code segments work:

/* Now lets try to set the send buffer size to 5000 bytes */ size = 5000; err = setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, &size, sizeof(int)); if (err != 0) { printf("Unable to set send buffer size, continuing with default size\n"); } 

If we check the value of the send buffer, it is really correctly set to 5000 * 2 = 10000. However, if we try to send more than the size of the send buffer, it will send it all. For example:

  n = send(sockfd, buf, 30000, 0); /* Lets check how much us actually sent */ printf("No. of bytes sent is %d\n", n); 

Prints 30,000.

How exactly did it work? Did the fact that the size of the send buffer be equal to 10,000? If so, what exactly happened? Some kind of fragmentation?

UPDATE: What happens if the socket is in non-blocking mode? I tried the following:

  • Changing the buffer size to 10,000 (5,000 * 2) sends 16,384 bytes
  • Changing the buffer size to 20,000 (10,000 * 2) causes the sending of 30,000 bytes

Once again, why?

+7
source share
2 answers

The effect of setting the SO_SNDBUF parameter SO_SNDBUF different for TCP and UDP.

  • For UDP, this sets a limit on the size of the datagram, that is, something more will be discarded.
  • For TCP, this simply sets the size of the built-in buffer for this socket (with some rounding to the page border and with an upper limit).

Since it looks like you're talking about TCP, the effect you are observing is because the socket is in blocking mode, so send(2) blocks until the kernel can receive all your data and / or the network stack asynchronously data and clicking on the network card, freeing up space in the buffer.

In addition, TCP is a streaming protocol, it does not preserve the structure of "messages". One send(2) can correspond to several recv(2) on the other hand, and vice versa. Think of it as a byte stream.

+11
source

SO_SNDBUF sets up a buffer that uses the socket implementation internally. If your socket is not blocked, you can send only the configured size, if your socket is blocked, there are no restrictions for your call.

+4
source

All Articles