当前位置:  开发笔记 > 运维 > 正文

理解set/getsockopt SO_SNDBUF

如何解决《理解set/getsockoptSO_SNDBUF》经验,为你挑选了1个好方法。

嗨,我有以下程序来检查UDP套接字的发送缓冲区大小.但是,我的返回值对我来说有点混乱.我使用以下简单的应用程序:

#include 
#include 

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;
}

我机器上的输出是:

发送缓冲区大小= 129024

将发送缓冲区设置为98304

发送缓冲区大小= 196608

任何人都可以澄清我在这里做错了什么或如何解释输出?



1> Matthew Slat..:

你没有做错任何事.Linux在设置时将值加倍(在内核中),并在查询时返回doubled值. 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.
[...]


神圣网络蝙蝠侠 这就是所有skbuf的东西:)
推荐阅读
360691894_8a5c48
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有