在Linux中的运行时指定UDP接收缓冲区大小 [英] Specifying UDP receive buffer size at runtime in Linux
问题描述
在Linux中,可以使用以下命令为网络数据包(例如UDP)指定系统的默认接收缓冲区大小:
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>
但是我想知道,应用程序(例如,在c
中)是否可以通过在运行时指定每个UDP套接字的接收缓冲区大小来覆盖系统的默认值?
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?
推荐答案
您可以从默认值增加该值,但不能将其增加到最大值以外.使用 setsockopt
更改SO_RCVBUF
选项:
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
}
请注意,这是便携式解决方案.它可以在任何POSIX平台上工作,以增加接收缓冲区的大小. Linux已有自动调整一段时间了(从2.6.7开始,并且合理的最大缓冲区大小(自2.6.17开始),它会根据负载自动调整接收缓冲区的大小.在具有自动调整功能的内核上,建议您不要使用setsockopt
设置接收缓冲区的大小,因为这将禁用内核的自动调整功能.在其他平台上,仍然可能需要使用setsockopt
来调整缓冲区大小.
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.
这篇关于在Linux中的运行时指定UDP接收缓冲区大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!