Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

sockets

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)
like image 506
Bilal B Avatar asked Jan 01 '26 04:01

Bilal B


1 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.

like image 96
Steffen Ullrich Avatar answered Jan 02 '26 19:01

Steffen Ullrich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!