Linux 了解 set/getsockopt SO_SNDBUF 大小加倍
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2031109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Understanding set/getsockopt SO_SNDBUF size doubles
提问by mortenvp
Hi I have the following program to check the send buffer size for a UDP socket. However, I the return value is a bit confusing to me. I use the following simple app:
嗨,我有以下程序来检查 UDP 套接字的发送缓冲区大小。但是,我的返回值让我有点困惑。我使用以下简单的应用程序:
#include <sys/socket.h>
#include <stdio.h>
int main(int argc, char **argv)
{
int sockfd, sendbuff;
socklen_t optlen;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if(sockfd == -1)
printf("Error");
int res = 0;
// Get buffer size
optlen = sizeof(sendbuff);
res = getsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, &sendbuff, &optlen);
if(res == -1)
printf("Error getsockopt one");
else
printf("send buffer size = %d\n", sendbuff);
// Set buffer size
sendbuff = 98304;
printf("sets the send buffer to %d\n", sendbuff);
res = setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, &sendbuff, sizeof(sendbuff));
if(res == -1)
printf("Error setsockopt");
// Get buffer size
optlen = sizeof(sendbuff);
res = getsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, &sendbuff, &optlen);
if(res == -1)
printf("Error getsockopt two");
else
printf("send buffer size = %d\n", sendbuff);
return 0;
}
The output on my machine is:
我机器上的输出是:
send buffer size = 129024
发送缓冲区大小 = 129024
sets the send buffer to 98304
将发送缓冲区设置为 98304
new send buffer size = 196608
新的发送缓冲区大小 = 196608
Can anybody clarify what I'm doing wrong here or how to interpret the output?
任何人都可以澄清我在这里做错了什么或如何解释输出?
采纳答案by Matthew Slattery
You're not doing anything wrong. Linux doubles the value (within the kernel) when you set it, and returns the doubled value when you query it. man 7 socket
says:
你没有做错任何事。Linux 在您设置时将该值(在内核内)加倍,并在您查询时返回加倍后的值。 man 7 socket
说:
[...] SO_SNDBUF Sets or gets the maximum socket send buffer in bytes. The ker- nel doubles this value (to allow space for bookkeeping overhead) when it is set using setsockopt(), and this doubled value is returned by getsockopt(). The default value is set by the wmem_default sysctl and the maximum allowed value is set by the wmem_max sysctl. The minimum (doubled) value for this option is 2048. [...] NOTES Linux assumes that half of the send/receive buffer is used for internal kernel structures; thus the sysctls are twice what can be observed on the wire. [...]