Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is binding to 0.0.0.0 in Java guaranteed to bind to all network interfaces?

I've found empirically that

Endpoint endpoint1 = Endpoint.create(new Ping());
endpoint1.publish("http://0.0.0.0:8080/ws/ping");

binds to all network interfaces on the current computer (instead of just localhost - 127.0.0.1 or the hostname), but I have not been able to locate the documentation which says that this is guaranteed.

Question: Where is it defined that binding to 0.0.0.0 in Java will always bind to all network interfaces?

like image 631
Thorbjørn Ravn Andersen Avatar asked Jun 19 '12 08:06

Thorbjørn Ravn Andersen


People also ask

What happens when you bind to 0. 0 0. 0?

If you have interfaces bound to 0.0. 0.0 (that is all known interfaces), then this will include both 127.0. 0.1 (localhost) and any IP address that the server node has. This means that the client will receive at least two interfaces that it will use to reconnect to the realm.

What does it mean to bind to an interface?

When a socket has both an IP address and a port number it is said to be 'bound to a port', or 'bound to an address'. A bound socket can receive data because it has a complete address. The process of allocating a port number to a socket is called 'binding'.

What does socket binding DO?

Binding of a socket is done to address and port in order to receive data on this socket (most cases) or to use this address/port as the source of the data when sending data (for example used with data connections in FTP server).


2 Answers

Using 0.0.0.0 will only bind to IPv4-enabled interfaces. However, if you bind to ::, that should cover all IPv4 and IPv6 interfaces, assuming your TCP/IP stack (and Java) have IPv4-compatible IPv6 sockets enabled.

You'll need to look to the kernel (or socket libraries, if you're on Windows) for an explanation of "why". On my OS X system, the man pages explain it.

From man 4 inet`:

Sockets may be created with the local address INADDR_ANY to effect 'wildcard' matching on incoming messages. The address in a connect(2) or sendto(2) call may be given as INADDR_ANY to mean 'this host'. The distinguished address INADDR_BROADCAST is allowed as a shorthand for the broadcast address on the primary network if the first network configured supports broadcast.

From man 4 inet6:

Sockets may be created with the local address :: (which is equal to IPv6 address 0:0:0:0:0:0:0:0) to affect 'wildcard' matching on incoming messages.

like image 145
mpontillo Avatar answered Nov 15 '22 17:11

mpontillo


It has nothing to do with Java. 0.0.0.0 is INADDR_ANY, which is is a special address that is guaranteed to receive from any network interface by the C sockets API, which is called by Java.

like image 21
user207421 Avatar answered Nov 15 '22 15:11

user207421