Get SO_RCVBUF socket option value from Qt

241 views Asked by At

I want to get the value of the SO_RCVBUF socket option used by Qt to be sure that it uses by default the system value (that I changed).

But the following piece of code returns an "Invalid" QVariant:

QUdpSocket socket;
qDebug() << socket.socketOption(QAbstractSocket::ReceiveBufferSizeSocketOption);

Does it mean that the socketOption() Qt method only get the value if it has been set with setSocketOption()?

Or did I make a mistake?

1

There are 1 answers

4
eyllanesc On BEST ANSWER

In order to obtain the socket information, then the native socket must have been created, that is, obtain a socketDescriptor() other than -1, but in your case it is not connected causing that value not to be read, returning a invalid QVariant.

The solution is to connect the socket and analyze that the socket is valid to obtain the desired information:

#include <QCoreApplication>
#include <QTimer>
#include <QUdpSocket>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QUdpSocket socket;
    QObject::connect(&socket, &QAbstractSocket::stateChanged, [&socket](){
        if(socket.socketDescriptor() != -1){
            qDebug() << socket.socketOption(QAbstractSocket::ReceiveBufferSizeSocketOption);
            // kill application
            QTimer::singleShot(1000, &QCoreApplication::quit);
        }
    });
    socket.bind(QHostAddress::LocalHost, 1234);
    return a.exec();
}

Output:

QVariant(int, 212992)