在 Linux 中在运行时指定 UDP 接收缓冲区大小 [英] Specifying UDP receive buffer size at runtime in Linux

查看:27
本文介绍了在 Linux 中在运行时指定 UDP 接收缓冲区大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆