1

If I write a few times in a quick succession on a socket (with the POSIX function write), usually all the data I wrote gets sent in a single TCP packets. Unless I write too much or unless I wait too long between the writes.

Is the kernel buffering the data I write on a socket and sending packets out at regular intervals? Or does the libc handle this? How long does the kernel wait before sending a packet? Can I request to send a mostly empty packet immediately? Is UDP or other protocols handled differently?

I'm curious to understand how all of this work, but I struggled at finding information on the topic.

1 Answer 1

1

Your OS likely does some short term buffering before sending. E.g. the Linux man page tcp(7) mentions the TCP_NODELAY option to disable that (see also setsockopt(2)):

TCP_NODELAY
If set, disable the Nagle algorithm. This means that segments are always sent as soon as possible, even if there is only a small amount of data. When not set, data is buffered until there is a sufficient amount to send out, thereby avoiding the frequent sending of small packets, which results in poor utilization of the network. This option is overridden by TCP_CORK; however, setting this option forces an explicit flush of pending output, even if TCP_CORK is currently set.

Nagle's algorithm being the actual buffering algorithm. If I followed the breadcrumbs correctly, RFC 1122 appears to be the currently-valid definition for it.

It's the kernel, not libc. The C library does buffering for stdio streams (FILE *), but write() and send() go directly to the kernel.

With UDP, the sizes of the datagrams are significant and visible to the upper layers, so similar mangling is not possible there.

1
  • Thanks, this answers all my questions. Apr 14, 2021 at 17:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .