我正在编写客户端服务器应用程序。简单地说,服务器可以为每个客户端使用UDP或TCP。
我希望TCP客户端和UDP客户端都打印默认值
SO_SNDBUF
和SO_RCVBUF
,但是当我在连接建立之前打印sndbuf和rcvbuf的默认值时,我感到很惊讶。
注意:我使用的是Ubuntu 12.10
这是我的代码:
//assume all variables initialized correctly.
/* SO_RCVBUF options */
len = sizeof(rcvbuf);
getsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, &rcvbuf, &len);
len = sizeof(mss);
getsockopt(sockfd, IPPROTO_TCP, TCP_MAXSEG, &mss, &len);
printf("defaults: SO_RCVBUF = %d, MSS = %d\n", rcvbuf, mss);
rcvbuf = 9973; /* a prime number */
setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof(rcvbuf));
len = sizeof(rcvbuf);
getsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, &rcvbuf, &len);
printf("SO_RCVBUF = %d (after setting it to 9973)\n\n\n\n", rcvbuf);
/* SO_RCVBUF options */
/* SO_SNDBUF options */
len2 = sizeof(sndbuf);
getsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, &sndbuf, &len2);
//len2 = sizeof(mss2);
getsockopt(sockfd, IPPROTO_TCP, TCP_MAXSEG, &mss2, &len2);
printf("defaults: SO_SNDBUF = %d, MSS = %d\n", sndbuf, mss2);
sndbuf = 9979; /* a prime number */
setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, &sndbuf, sizeof(sndbuf));
len2 = sizeof(sndbuf);
getsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, &sndbuf, &len2);
printf("SO_SNDBUF = %d (after setting it to 9979)\n", sndbuf);
/* SO_SNDBUF options */
示例输出:
默认值:SO_RCVBUF = 0,MSS = 0
SO_RCVBUF = 9973(将其设置为9973后)
默认值:SO_SNDBUF = 0,MSS = 0
SO_SNDBUF = 9979(将其设置为9979后)
tcp_time nes411_server
当前时间是(TCP):Mon Apr 22 23:40:46 2013
连接后:
SO_SNDBUF = 170840,MSS = 16384
答案 0 :(得分:3)
显然,在您之前调用connect(),
时会分配发送缓冲区和接收缓冲区。您可能正要使用套接字进行侦听,在这种情况下,两个缓冲区都会完全浪费空间。或者没有,同上。
NB为什么使用素数?习惯上使用2的幂来表示缓冲区大小。
答案 1 :(得分:0)
您可以从下面的代码中检查默认套接字缓冲区。
int rcvBufferSize;
int sockOptSize = sizeof(rcvBufferSize);
getsockopt(udp_fd, SOL_SOCKET, SO_RCVBUF, &rcvBufferSize, &sockOptSize);
printf("initial socket receive buf %d\n", rcvBufferSize);