0
votes

I am creating a Linux C++/Qt5 app which opens a TCP socket for an outbound connection (to a remote server). I create a QTcpSocket and then try to set sockopt options as follows:

m_tcpSocket = new QTcpSocket(this);
int fd = m_tcpSocket->socketDescriptor();
int enableKeepAlive = 1;  // Enable
if ( setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &enableKeepAlive, sizeof(enableKeepAlive)) != 0)
    reportsockoptError("SOL_SOCKET","SO_KEEPALIVE");

Unfortunately my setsockopt is failing with 'Bad file descriptor' error, because m_tcpSocket->socketDescriptor() is returning -1. How do I get the socket descriptor for an outbound socket before it connects? Or do I have to do this AFTER connect? (which seems to contract what I understand from the Qt docs)

The above works fine for a listening socket (QTcpServer)....just not QTcpSocket.

1
Why don't you use qt function setSocketOption for this?Геннадий Казачёк

1 Answers

2
votes

From the QAbstractSocket documentation

The socket descriptor is not available when QAbstractSocket is in UnconnectedState.

So, before calling socketDescriptor, you should change the TCP socket internal state. In the case of a client socket, you probably need to connect it to a server, thus passing it to ConnectedState.