38

I have a small one sided message sender that works while I specify the IP to connect to in code, however, I am having trouble allowing the socket to accept connections from any IP. Here is the line that is the problem.

mySocket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
mySocket.bind ( ( '', 2727 ) )

The '' is for localhost, and it works if I manually enter IP, eg '192.168.1.106', however, how can I leave it open to all? Or am I using the wrong connection type for this?

phoenix
  • 7,988
  • 6
  • 39
  • 45
Trent
  • 1,275
  • 7
  • 17
  • 22

3 Answers3

49

If you want to bind to all available IPv4 addresses, specify 0.0.0.0 as your IP address. If you're behind a router and wish to have your socket internet-accessible, rather than just available on your LAN, you'll need to set up a port forwarding rule so that users outside your LAN can access the service.

See the following ServerFault question for more info on 0.0.0.0: https://serverfault.com/questions/78048/whats-the-difference-between-ip-address-0-0-0-0-and-127-0-0-1

Community
  • 1
  • 1
Polynomial
  • 27,674
  • 12
  • 80
  • 107
16

Binding to '' has the same effect as to '0.0.0.0' makes the transition to IPv6 easier.

Depending on the OS, opening a socket.AF_INET6 socket listens to IPv4 and IPv6.

glglgl
  • 89,107
  • 13
  • 149
  • 217
  • Python bug report to make the docs more explicit about this: https://bugs.python.org/issue33921 – phoenix Jun 21 '18 at 11:17
  • 1
    According to the [docs](https://docs.python.org/3/library/socket.html#socket-families), `''` is **not** compatible with IPv6: *This behavior is not compatible with IPv6, therefore, you may want to avoid these if you intend to support IPv6 with your Python programs.* – phoenix Jun 23 '18 at 14:44
6

Binding to 0.0.0.0 will allow it to accept connections from any IPv4 address that can route to it.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358