Important: Please read the Qt Code of Conduct -

QTcpSocket accepts localhost but not

  • Hello

    I have a Qt server app running on my computer, and a Qt client app which connects with:
    @socket.connectToHost("localhost", 9998);@
    @socket.connectToHost("my-pc-name", 9998);@

    The above works perfectly. But the following:
    @socket.connectToHost("", 9998);@
    @socket.connectToHost(QHostAddress("localhost"), 9998);@

    These two lines don't work.

    My Apache server on the other hand responds to these IPs well when I enter them on my browser:

    I downloaded the latest Qt SDK from for my Ubuntu 12.04 installation. The about page says:
    @Qt Creator 2.4.1
    Based on Qt 4.7.4 (64 bit)
    Built on Jan 25 2012 at 11:24:18
    From revision 8cd370e163@

    What could be the problem? The biggest problem is that on my N9 I even the face problem when trying these lines:
    @socket.connectToHost("my-pc-name", 9998);@

    @socket.connectToHost("", 9998);@

    Thank you!

  • QHostAddress() when constructed with a string expects an IP address not a name and it does not do a name lookup. So, QHostAddress("localhost") is not valid. You can get the loopback interface using QHostAddress(QHostAddress::LocalHost) or QHostAddress("").

    QAbstractSocket::connectToHost(), when given a QString, does a name lookup if needed, i.e. it takes a name or an IP address in the string. Both variants work correctly here. If you have no name resolution service then this might fail (I don't know about the N9).

Log in to reply