PDA

View Full Version : Problem when excluding clients from connecting to QTcpServer



Raistlin
22nd May 2008, 16:13
I wanted to exclude certain clients from connecting to a QTcpServer. In my server, I use the following code:



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;
}
}

On the client side:



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;
}
}

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?

wysota
22nd May 2008, 16:17
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.

Raistlin
22nd May 2008, 16:23
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 :).

wysota
22nd May 2008, 16:34
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).

Raistlin
23rd May 2008, 09:42
Ok, good to know :).