What is the difference between binding a socket like this:
sock.bind((socket.gethostname(), 9999))
versus this:
sock.bind(('', 9999))
According to the HOWTO, binding to socket.gethostname() makes the socket visible to the outside world. However, it also says that binding to '' makes the socket reachable by any address the machine happens to have. Does this mean that it also makes it reachable by the outside world? My guess is binding to '' allows the socket to be reached both from within the same machine (through loopback) as well as from other machines, while binding to socket.gethostname() will only allow connections from other machines (including the same machine, but just not through the loopback interface). Please let me know if this is wrong. Also, if I am behind a router, will I still need to set up some sort of port forwarding in order to listen for connections from the internet with both of these binding methods? Or will binding to '' allow me to directly listen for connections to my public ip? Thanks.
Binding to 0.0.0.0 or '' (aka "Wildcard Address" or INADDR_ANY) will bind to all interfaces, including public ones.
Binding to 127.0.0.1 ('localhost') will only bind to the loopback interface.
Binding to the specific IP address, as resolved from the result of gethostname, will only accept connections to the associated interface. (A connection made from the same machine must be made to the resolved IP, not the loopback.)
Routing / firewalls / forwarding is a separate issue as the listening socket is local to the machine, which must be exposed through network to the outside world: once the connection gets to machine the socket binding rules become relevant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With