QTcpServer can only be accessed through localhost
Asked Answered
S

2

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?

Scandinavian answered 4/11, 2013 at 16:8 Comment(0)
B
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.

Bootblack answered 4/11, 2013 at 16:11 Comment(4)
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.Scandinavian
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.Bootblack
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.Scandinavian
I feel like it might be add value to describe the difference between listening on a specific interface vs all interfaces.Cardew
S
3

localhost is on a separate network interface

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

Swahili answered 4/11, 2013 at 16:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.