41

We are serving a port on localhost and want to check in another process if the port is available. Due to a bug in our code, it is actually trying to connect to the IP 0.0.0.0:<port>, and for some reason it succeeds -- as strace proves:

[...]
connect(3, {sa_family=AF_INET, sin_port=htons(10002), sin_addr=inet_addr("0.0.0.0")}, 16) = 0
[...]

What does it mean? Why does it work?

68

0.0.0.0 as a target address refers variously to a non-routable host or to “this host”. In practice connecting to 0.0.0.0 is equivalent to connecting to localhost. (Strictly speaking it isn’t valid as a destination address, only as a source address, but practice doesn’t match theory.)

When binding, “this host” expands to “any address on this host” — so applications commonly accept connections by binding to 0.0.0.0, which means they’ll receive packets addressed to any IPv4 address on the system.

  • 7
    To extend this answer a little - it means "any IP address on this system, including IPs that have been added after the listening process started" – Criggie Jan 27 '18 at 9:23
  • 5
    localhost is a single address, mostly 127.0.0.1, while 0.0.0.0 means all addresses on this host. – rexkogitans Jan 27 '18 at 11:21
  • @rexkogitans localhost is not a single address, but any address in the range 127.0.0.0/8 - i.e. any address from 127.0.0.0 to 127.255.255.255 – Dezza Jan 27 '18 at 15:05
  • 6
    @Dezza No, localhost is 127.0.0.1. 127.0.0.0/8 (as you say, a.k.a. 127.0.0.0 through 127.255.255.255) is loopback with most equipment, e.g. documented by RFC 5735 page 4. (Interestingly, some Cisco equipment can assign loopback to any address, but defaults to not supporting loopback at all. Not that this is likely to affect other equipment on the network.) However, localhost is a name, typically pointing to just to a single address which is 127.0.0.1, and commonly implemented by using a "hosts" file. So I disagree with your attempted correction. – TOOGAM Jan 27 '18 at 19:11
  • Could you clarify what you mean by "it isn’t valid as a destination address, only as a source address"? When mysql server listens at 0.0.0.0, is the address destination or source? Is it not the destination of a request sent from a mysql client? – Tim Mar 22 at 20:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.