Why “[Errno 61] Connection refused” when program is listening on correct port, socket is bound to all interfaces?

Tags: , , ,

I’ll try be concise, but please let me know if I can provide any more helpful pieces of information.

I have client and server Python programs, and they work fine when ran on the same machine, and when the client connects to my machine’s local IP (not, but the IP assigned to my machine). I have not been able to get this to work with my public IP.

I get a [Errno 61] Connection refused error when I try to get the client to connect to my router’s public IP address. My server binds to all interfaces using bind(("", 50000)), and I already set up port forwarding for my router. I verified that the program is listening on that port by running netstat -an | grep LISTEN and finding the following line:

tcp4 0 0 *.50000 *.* LISTEN

I can also seemingly reach the port through an online port checking tool, which shows that the port is open when I am running my program, and closed when I close that program. My program also registers the connection from this tool.

The fact that my program accepts the connection from the port checking tool gives me the impression that my client code is missing something, but I can’t find any answers. It might be worth noting that I am still running my server and client code on the same machine, but I’m not sure why that would derail things. Here’s the code I use to connect on the client side:

tcp_client = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
tcp_client.connect(('my_public_ip', 50000))

Are there any diagnostic steps that I can follow to narrow down my issue?


Before you spend any more time on this, try connecting to your public ip from a computer outside your home network. Spend a couple of dollars on an AWS instance for an hour if you have to, or try connecting from a friend’s machine, whatever. It will probably work just fine.

I suspect the problem is simply that you cannot, from inside your home network, connect to your router’s public ip address. I tried the same thing with my local network and ran into the same behavior.

If you really need to your public ip during development, you can just assign that as an alias to one of your local interfaces (ip addr add dev eth0)…but it’s probably easier just to use your an address on your local network, or just arrange for regular access to a remote system for testing.

Source: stackoverflow