Bind a QTcpSocket to a specific port

≡放荡痞女 提交于 2020-06-23 08:25:42

问题


I am connecting through a QTcpSocket to a QTcpServer. I can specify the listening port on the Server side, but the client chooses a random port for its connection. I have tried to use the method QAbstractSocket::bind but that made no difference.

Here is my code:

void ConnectionHandler::connectToServer() {
     this->socket->bind(QHostAddress::LocalHost, 2001);
     this->socket->connectToHost(this->ip, this->port);

     if (!this->socket->waitForConnected()) {
           this->socket->close();
           this->errorMsg = this->socket->errorString();
      }

     qDebug() << this->socket->localPort();
}

Does anyone know what I'm missing?


回答1:


I reformulated your code into a MCVE:

#include <QDebug>
#include <QHostAddress>
#include <QTcpSocket>

#include <memory>

int main()
{
    std::unique_ptr<QTcpSocket> socket(new QTcpSocket);

    socket->bind(QHostAddress::LocalHost, 2001);
    qDebug() << socket->localPort(); // prints 2001

    socket->connectToHost(QHostAddress::LocalHost, 25);
    qDebug() << socket->localPort(); // prints 0
}

Why does connectToHost reset the local port to 0?

This appears to be a bug in Qt. In version 5.2.1, QAbstractSocket::connectToHost contains

d->state = UnconnectedState;
/* ... */
d->localPort = 0;
d->peerPort = 0;

In version 5.5, this has changed to

if (d->state != BoundState) {
    d->state = UnconnectedState;
    d->localPort = 0;
    d->localAddress.clear();
}

So it's likely that upgrading your Qt will fix the issue.



来源:https://stackoverflow.com/questions/33202353/bind-a-qtcpsocket-to-a-specific-port

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!