Tuesday, June 01, 2010

How to bind to all local addresses

Whenever we bind to an address, typically we bind to an address and port.
InetSocketAddress local = new InetSocketAddress("localhost", port);
socket.bind(local);
This binds your socket only to "localhost". What if your host has multiple names, such as "localhost" and "myhost.mydomain"? You can still bind to all local addresses by doing the following:
InetSocketAddress local = new InetSocketAddress(port);
socket.bind(local);
Internally, this binds to all localhost addresses by using InetAddress.anyLocalAddress() (which is package private).
Post a Comment