gpt4 book ai didi

c++ - 设置大套接字接收缓冲区时setsockopt()不返回错误

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:39:10 24 4
gpt4 key购买 nike

我正在使用以下代码测试函数 setsockopt(),但出现了我无法理解的行为:下面是我正在运行的代码片段(在 Ubuntu 12.04 64 位、Qt 4.8.x 上编译):

#include <QCoreApplication>

#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <QDebug>

#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);

int sock = ::socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
int res;
int bufferSizeByte = QString(argv[1]).toInt();

qDebug() << "Setting socket buffer size to" << bufferSizeByte << "bytes";
res = setsockopt( sock, SOL_SOCKET, SO_RCVBUF, (void*)&bufferSizeByte, sizeof(bufferSizeByte) );
if ( -1 == res )
{
qDebug() << "ERROR setting socket buffer size to" << bufferSizeByte << "bytes";
}

/*
* !! WARNING !!
* If we try setting the buff size over the kernel max: we do not get an error
*/

int readValue = 0;
unsigned int readLen = sizeof(readValue);
res = getsockopt( sock, SOL_SOCKET, SO_RCVBUF, (void*)&readValue, &readLen );
if ( -1 == res )
{
qDebug() << "ERROR reading socket buffer size";
}
else
{
qDebug() << "Read socket buffer size:" << readValue << "bytes";
Q_ASSERT ( readValue == bufferSizeByte*2 );
}


return a.exec();
}

基本上我正在为套接字设置接收缓冲区大小,然后读回它以验证操作是否真的成功。将缓冲区大小设置为在 Linux 内核 (/proc/sys/net/core/rmem_max) 中配置的值会触发 Q_ASSERT() 作为预期,但我没有收到 setsockopt 错误消息.

例如:

sergio@netbeast: sudo ./setsockopt 300000 
Setting socket buffer size to 300000 bytes
Read socket buffer size: 262142 bytes
ASSERT: "readValue == bufferSizeByte*2" in file ../setsockopt/main.cpp, line 43

我不明白为什么 setsockopt() 不返回错误

有什么线索吗?

最佳答案

sock_setsockopt()的实现(这是系统调用 setsockopt() 最终在内核中调用的内容)关于为什么设置太大的值不会导致错误的评论。评论表明原因是为了与原始 BSD 实现兼容(因此,为 BSD 系统编写的软件更容易移植到 Linux):

            /* Don't error on this BSD doesn't and if you think
* about it this is right. Otherwise apps have to
* play 'guess the biggest size' games. RCVBUF/SNDBUF
* are treated in BSD as hints
*/

请注意,如果这样做时没有超过最大大小(并且满足最小值),则实际存储的值是传递给 SO_RCVBUF 的值的两倍。来自man page :

SO_RCVBUF Sets or gets the maximum socket receive buffer in bytes. The kernel doubles this value (to allow space for bookkeeping overhead) when it is set using setsockopt(2), and this doubled value is returned by getsockopt(2). The default value is set by the /proc/sys/net/core/rmem_default file, and the maximum allowed value is set by the /proc/sys/net/core/rmem_max file. The minimum (doubled) value for this option is 256.

关于c++ - 设置大套接字接收缓冲区时setsockopt()不返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18685775/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com