Problem when excluding clients from connecting to QTcpServer
I wanted to exclude certain clients from connecting to a QTcpServer. In my server, I use the following code:
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;
}
}
On the client side:
Code:
void Client::establishConnection()
{
{
socket_->connectToHost(server, port_);
if (socket_->waitForConnected(100))
{
connect(socket_, SIGNAL(readyRead()), this, SLOT(readyRead()));
emit connectionEstablished(server);
break;
}
}
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?
Re: Problem when excluding clients from connecting to QTcpServer
You should establish a connection and close it immediately. The connection is already established when incomingConnection() is called. The way you are trying to validate the client is... weird :) You can't create and close sockets as you want and expect the connection not to suffer on that.
Re: Problem when excluding clients from connecting to QTcpServer
If so, then why is it possible to set the descriptor with the state QAbstractSocket::HostLookupState? I thought that was the perfect way to prevent a connection from being established :).
Re: Problem when excluding clients from connecting to QTcpServer
Because you might set an arbitrary descriptor on a socket, so Qt doesn't know what state it is in. But this exact descriptor is in the connecting state when you get it (so you can't make a step back).
Re: Problem when excluding clients from connecting to QTcpServer