1

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?

Alexandre D.
  • 711
  • 1
  • 9
  • 28

1 Answers1

1

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)
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • Thanks for the answer @eyllanesc. Are we sure that the value returned by the `socketOption()` is took into account by the socket? For exemple, if we set a value which is not a mulitple of 4096, I guess the value is not used by the socket because invalid – Alexandre D. Apr 03 '20 at 15:11
  • @AlexandreD. mmm I do not understand you. QXSocket is a wrapper of native sockets so method like socketOption will internally use the native socket, so since there is no connection then the native socket will not exist and therefore setSocketOption and socketOption cannot be used. – eyllanesc Apr 03 '20 at 15:18
  • Yes totally. My question is now different from the one above. I understood that I need to have a socket descriptor to be able to set socket options. But are we sure that the value received from socketOption is actually used by our native socket? – Alexandre D. Apr 03 '20 at 15:29
  • @AlexandreD. Yes, I am sure. I recommend you check the Qt source code so that you can analyze depending on your OS. For linux you can check https://github.com/qt/qtbase/blob/5.14.2/src/network/socket/qnativesocketengine_unix.cpp#L453 – eyllanesc Apr 03 '20 at 15:35