QTcpSocket accepts localhost but not 127.0.0.1



  • Hello

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

    The above works perfectly. But the following:
    @socket.connectToHost("127.0.0.1", 9998);@
    or
    @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:
    @127.0.0.1
    192.168.0.2
    my-pc-name
    localhost@

    I downloaded the latest Qt SDK from qt.nokia.com 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);@

    and
    @socket.connectToHost("192.168.0.2", 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("127.0.0.1").

    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
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.