且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SO_SNDBUF和SO_RCVBUF Linux上的插座

更新时间:2023-11-12 09:59:22

显然,发送缓冲区和接收缓冲区,当你调用连接(分配),而不是之前。你可能是即将用于监听的插座,在这种情况下,这两个缓冲区将是空间完全是浪费。或者什么,同上。

NB你为什么要使用一个素数?这是习惯使用的两个大国的缓冲区大小。

I am programming a client server application. Simply, the server can use either UDP or TCP for each client.

I want both the TCP client and UDP client to print the default value for SO_SNDBUF and SO_RCVBUF, but I am surprised when I print the default value for sndbuf and rcvbuf before the connection establishment the value is 0.

Note: I am using Ubuntu 12.10

Here is my code:

//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 */

Sample output:

defaults: SO_RCVBUF = 0, MSS = 0

SO_RCVBUF = 9973 (after setting it to 9973)

defaults: SO_SNDBUF = 0, MSS = 0

SO_SNDBUF = 9979 (after setting it to 9979)

tcp_time nes411_server

Current time is (TCP): Mon Apr 22 23:40:46 2013

After connection:

SO_SNDBUF = 170840, MSS = 16384

Obviously the send buffer and receive buffer are allocated when you call connect(), not before. You could be about to use the socket for listening, in which case both buffers would be a complete waste of space. Or for nothing, ditto.

NB Why are you using a prime number? It's customary to use powers of two for buffer sizes.