Networking – How and Why Connecting to IP 0.0.0.0 Succeeds

networkingstracetcp

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?

Best Answer

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.

Related Question