Reputation: 63
I am trying to implement a simple TCP instant messaging program in Python using the socket module. When I use the value returned by socket.gethostname()
in connect()
, the client works perfectly fine when connecting to the IM server running on localhost. However, the client returns errno 111 (Connection refused) when I use the value returned by socket.gethostbyname("localhost")
. Is there any way to fix this issue?
Upvotes: 0
Views: 2555
Reputation: 365925
If you get a 111 when trying to connect
, that generally means nothing is listening at that host and port.
It's usually easier to check this with a one-liner using netcat
(which you probably have built-in on any platform but Windows, and can get easily if you don't), or telnet
if you must:
abarnert$ nc -v localhost 111
nc: connect to localhost port 111 (tcp) failed: Connection refused
nc: connect to localhost port 111 (tcp) failed: Connection refused
nc: connect to localhost port 111 (tcp) failed: Connection refused
Since netcat couldn't connect, the problem isn't your Python client, it really is that there's nothing to connect to.
This means your server isn't listening on localhost:111.
Without knowing anything about your server beyond a brief mention, it's impossible to diagnose, but my first guess would be that you're doing a bind((gethostname(), 111))
, which means it ends up listening only on, say, 10.0.0.3:111
.
If you want to listen on all hosts and interfaces, there are fancy ways to specify that, but the easiest way is:
serversocket.bind(('', 111))
Upvotes: 1