28

In Linux, one can specify the system's default receive buffer size for network packets, say UDP, using the following commands:

sysctl -w net.core.rmem_max=<value>
sysctl -w net.core.rmem_default=<value>

But I wonder, is it possible for an application (say, in c) to override system's defaults by specifying the receive buffer size per UDP socket in runtime?

Brian Campbell
  • 322,767
  • 57
  • 360
  • 340
Mαzen
  • 535
  • 2
  • 7
  • 14

1 Answers1

34

You can increase the value from the default, but you can't increase it beyond the maximum value. Use setsockopt to change the SO_RCVBUF option:

int n = 1024 * 1024;
if (setsockopt(socket, SOL_SOCKET, SO_RCVBUF, &n, sizeof(n)) == -1) {
  // deal with failure, or ignore if you can live with the default size
}

Note that this is the portable solution; it should work on any POSIX platform for increasing the receive buffer size. Linux has had autotuning for a while now (since 2.6.7, and with reasonable maximum buffer sizes since 2.6.17), which automatically adjusts the receive buffer size based on load. On kernels with autotuning, it is recommended that you not set the receive buffer size using setsockopt, as that will disable the kernel's autotuning. Using setsockopt to adjust the buffer size may still be necessary on other platforms, however.

Brian Campbell
  • 322,767
  • 57
  • 360
  • 340
  • just what I was looking for :) I also wonder, if I specified the buffer size to a small value, will it be static? Or will the system dynamically resize the buffer to handle traffic pressure, if any? – Mαzen Jan 19 '10 at 04:12
  • I've expanded my answer a bit to mention Linux TCP autotuning; on Linux, if autotuning is enabled, you probably shouldn't adjust the buffer size using `setsockopt`; but on other systems, you may still want to. – Brian Campbell Jan 19 '10 at 15:52
  • 4
    autotuning applies to TCP only or it applies to both TCP and UDP? – kumar Jun 29 '10 at 14:27
  • Is it possible to do so from Java app? I'd also like to know if autotuning applies both for UPD and TCP... – omnomnom May 22 '11 at 10:43
  • 1
    @PiotrekDe Yes, see `Socket.setReceiveBufferSize()`, `Socket.setSendBufferSize()`, `DatagramSocket.setReceiveBufferSize()`, and `DatagramSocket.setSendBufferSize()`. – user207421 Aug 01 '12 at 08:49
  • 2
    @kumar, it looks like it only applies to TCP per the link mentioned in the answer [autotuning](http://www.psc.edu/networking/projects/tcptune/#Linux) – Anne Sep 19 '12 at 19:25
  • @BrianCampbell is there any way that we could check the buffer size and if its full clear it, i am trying it out in android. – George Thomas Sep 02 '16 at 04:59