I wanted to exclude certain clients from connecting to a QTcpServer. In my server, I use the following code:
void Server::incomingConnection(int socketDescriptor)
{
//Only perform a host look-up, do NOT establish a connection
if (!socket_
->setSocketDescriptor
(socketDescriptor,
QAbstractSocket::HostLookupState)) {
emit error(socket_->error());
return;
}
QString name
= socket_
->peerName
();
if (socket_
->peerName
() == QString("A certain hostname")) {
emit finished();
socket_->close();
return;
}
//Close socket anyway to be able to establish a connection
socket_->close();
if (!socket_->setSocketDescriptor(socketDescriptor))
{
emit error(socket_->error());
return;
}
}
void Server::incomingConnection(int socketDescriptor)
{
socket_ = new QTcpSocket(this);
//Only perform a host look-up, do NOT establish a connection
if (!socket_->setSocketDescriptor(socketDescriptor, QAbstractSocket::HostLookupState))
{
emit error(socket_->error());
return;
}
QString name = socket_->peerName();
if (socket_->peerName() == QString("A certain hostname"))
{
emit finished();
socket_->close();
return;
}
//Close socket anyway to be able to establish a connection
socket_->close();
if (!socket_->setSocketDescriptor(socketDescriptor))
{
emit error(socket_->error());
return;
}
}
To copy to clipboard, switch view to plain text mode
On the client side:
void Client::establishConnection()
{
{
socket_->connectToHost(server, port_);
if (socket_->waitForConnected(100))
{
connect(socket_, SIGNAL(readyRead()), this, SLOT(readyRead()));
emit connectionEstablished(server);
break;
}
}
void Client::establishConnection()
{
foreach(QString server, servers_)
{
socket_->connectToHost(server, port_);
if (socket_->waitForConnected(100))
{
connect(socket_, SIGNAL(readyRead()), this, SLOT(readyRead()));
emit connectionEstablished(server);
break;
}
}
To copy to clipboard, switch view to plain text mode
Now it seems that waitForConnected returns true when only performing the host look-up. I do not want a connection to be established at the client side, if there is no real connection. This does not seem to be the behavior one would expect.
I can off course check of the socket is open afterwards, but shouldn't waitForConnected() only return true when a complete connection has been established?
Bookmarks