标签 tcp 下的文章

“”

linux socket 设置缓冲区大小时内核会翻倍
示例代码:

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

运行结果:

send buffer size = 129024
sets the send buffer to 98304
new send buffer size = 196608

官方手册说明

SO_SNDBUFSets 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.