2010-01-08 36 views
36

嗨,我有以下程序來檢查UDP套接字的發送緩衝區大小。但是,我的返回值對我來說有點混亂。我用下面簡單的應用程序:瞭解設置/ getsockopt SO_SNDBUF

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

我的機器上輸出是:

發送緩衝區的大小= 129024

設置發送緩衝區98304

發送緩衝區的大小= 196608

任何人都可以澄清我在這裏做錯了什麼或如何解釋輸出?

回答

45

你沒有做錯什麼。 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. 
[...] 
+9

神聖的網絡蝙蝠俠!那就是所有那些skbuf的東西去:) – 2010-01-09 02:40:47

+0

我不知道爲什麼內核加倍的價值? – csyangchen 2015-10-08 13:18:24

+0

@csyangchen:我只能猜測,但我會假設有人有這樣的想法,即通過將緩衝區設置爲n,緩衝區應該能夠保存n個字節的PAYLOAD。因此需要額外的緩衝區大小來保存消息頭(至少在無連接的底層協議的情況下,如UDP)。 – Aconcagua 2016-02-01 10:22:10