问题
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