我正在使用下面的代码测试功能 setsockopt(),但出现了我不理解的行为:
下面是我正在运行的代码片段(在Ubuntu 12.04 64bit,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();
}

基本上,我为套接字设置了recv缓冲区的大小,然后将其读回以验证操作是否成功。
将缓冲区大小设置为一个在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:

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

10-11 22:57