Connecting to IP 0.0.0.0 succeeds. How? Why?

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments