QTcpSocket 这不是坑爹吗,我电脑上分配了多个IP,采用QTcpSocket编写的客户端,先绑定了指定IP地址,然后连接。绑定之后,我还打印了localAddress和localPort,结果他连接的时候就变成了另外一个地址,而且不管我怎么绑定,到服务器之后地址永远都不变,然后我用原生的socket操作,socket -- bind -- connect,到服务器那边获取的IP地址就是我客户端绑定的地址,屡试不爽,难道这是一个bug。
最后我很想知道为什么,查看qt的源代码,在connectToHost函数中发现,在连接之前qt把localAddress给clear了,难道客户端就不能绑定IP吗。这是哪门子的事啊,然后我在connectToHost之后再打印localAddress,确实为空。整了好久,以为是我的电脑IP没有分配好,原来是QT在里面干坏事。
void QAbstractSocket::connectToHost(const QString &hostName, quint16 port,
OpenMode openMode,
NetworkLayerProtocol protocol)
{
Q_D(QAbstractSocket);
#if defined(QABSTRACTSOCKET_DEBUG)
qDebug("QAbstractSocket::connectToHost(\"%s\", %i, %i)...", qPrintable(hostName), port,
(int) openMode);
#endif
if (d->state == ConnectedState || d->state == ConnectingState
|| d->state == ClosingState || d->state == HostLookupState) {
qWarning("QAbstractSocket::connectToHost() called when already looking up or connecting/connected to \"%s\"", qPrintable(hostName));
d->socketError = QAbstractSocket::OperationError;
setErrorString(QAbstractSocket::tr("Trying to connect while connection is in progress"));
emit error(d->socketError);
return;
}
d->preferredNetworkLayerProtocol = protocol;
d->hostName = hostName;
d->port = port;
d->state = UnconnectedState;
d->buffer.clear();
d->writeBuffer.clear();
d->abortCalled = false;
d->closeCalled = false;
d->pendingClose = false;
d->localPort = 0;
d->peerPort = 0;
d->localAddress.clear();
d->peerAddress.clear();
d->peerName = hostName;
if (d->hostLookupId != -1) {
QHostInfo::abortHostLookup(d->hostLookupId);
d->hostLookupId = -1;
}
......
......
}