10

My computer's IP on the local network is 192.168.0.100, I start my QTcpServer with

if (!tcpServer->listen(QHostAddress::LocalHost, 1234)) {

When I try to connect to it with netcat 192.168.0.100 1234, the connection is refused, but netcat localhost 1234 succeeds.

At the same time, if I listen with netcat -l -p 1234, I can connect on both 192.168.0.100 and localhost without any problem.

This has me scratching my head, why is it happening?

sashoalm
  • 75,001
  • 122
  • 434
  • 781

2 Answers2

10

In order to accept connections from the outside, you have to listen on 0.0.0.0, not on 127.0.0.1 or localhost. The latter will only allow connections coming from the same machine. It's also the value of QHostAddress::LocalHost.

So change the first argument to QHostAddress::Any and it should work.

lethal-guitar
  • 4,438
  • 1
  • 20
  • 40
  • Up till now I always thought that listening on localhost meant that you get all connections that reach the local machine, so I kind of thought that `QHostAddress::LocalHost` is the same as `QHostAddress::Any`. Thanks for clearing it up. – sashoalm Nov 04 '13 at 16:15
  • 1
    Yeah this is a frequent cause of confusion. Listening on `127.0.0.1` is intended for cases where you do *not* want to allow a connection from the outside, like when you're running a DB server on the same machine as your web server and don't want to expose it etc. – lethal-guitar Nov 04 '13 at 16:17
  • It seems it goes the other way around, too. I tried with `tcpServer->listen(QHostAddress("192.168.56.1"), 1234))` and now it won't accept `netcat localhost 1234`, only `netcat 192.168.56.1`. – sashoalm Nov 04 '13 at 16:20
  • 1
    I feel like it might be add value to describe the difference between listening on a specific interface vs all interfaces. – Son-Huy Pham Nov 04 '13 at 17:42
3

localhost is on a separate network interface

you can use QHostAddress::Any to listen for external connections

ratchet freak
  • 47,288
  • 5
  • 68
  • 106