Important: Please read the Qt Code of Conduct -

Static port for QTcpSocket

  • Hi

    I'm using a QTcpSocket to send data to stunnel.
    However in my stunnel config I need to setup a specific port for the localhost connection.

    In Qt I use:
    socket->connectToHost(ipBox->text(), portBox->text().toInt());

    It works, however when I print the port used:
    qDebug() << QString::number(socket_->localPort());

    it is not the value I have inputted. Actually the port changes everytime and even seems to be incremented.
    Do you know how to setup my QTcpSocket so it always uses the same port?


  • To make it clear: when I say it works, I mean there's no other problem with the socket: the data is sent. But it never reaches the server since I can't configure the port I want to send the data through.

  • A TCP/IP connection utilizes two ports, the one you connect to on the remote end and a local port that is used for incoming data. The local port is an ephemeral port assigned by the operating system from the pool of free ephemeral port numbers. This is normal operation, you do not need to have a fixed local port because the the ephemeral port is sent to the remote end so that it knows how to reply to you the client.

    QAbstractSocket::peerPort() returns the remote port number.

Log in to reply