Python cannot bind my external/public IP address using socket, gives error But when using local IP address the error doesn't show up

Question:

Here is the code where the main error shows up

A bind with my local IP will work:

s.bind(("192.168.1.4", port))

A bind with my public IP fails with the error below

s.bind(("99.99.99.99", port))

[WinError 10049] The requested address is not valid in its context

Here is more context about my code:


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

port = 6767

try:
    s.bind(("192.168.1.4", port))  # will work fine as local ip is used but 
                                   # when used public ip the error is thrown
except socket.error as e:
    print(str(e)+"aa")

s.listen(2)
Asked By: Bilal B

||

Answers:

You can only bind to an IP address which is local to your system. The “public IP” you see is likely not the IP address of your local machine but the IP address of your router which provides you with internet connectivity.

That means you would need to run a program on this router in order to bind to this IP address. Since this is usually impossible the common way to make some internal service accessible from outside is to bind to the address in your local network and then add a forward rule to your router which forwards external connections to your internal IP and port where the service is bound to and listening.

Answered By: Steffen Ullrich

I had a similar problem, I was using ubuntu and binding to my wan ip with no problems. I moved to windows and it did not work so had set up ports on my router to allow all my client data to access the internal ip of my server. Also have to allow ports in your firewall

Answered By: Foton
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.