Java does not handle multi network systems well. You cannot control which network interface will be returned by InetAddress.getLocalHost()
. The only solution I have so far to control which interface is returned by InetAddress.getLocalHost()
is to use the security manager and not grant SocketPermission to the addresses that I don't want used.
InetAddress.getAllByName("localhost");
Will get you the loop back addresses.
IntetAddress ia = InetAddress.getLocalHost();
Will get you one of your IP's;
IntetAddress[] iaa = InetAddress.getAllByName(ia.getHostName());
will get you all of the addresses on your host.
The sun InetAddress implements getLocalHost() like this:
public static InetAddress getLocalHost() throws UnknownHostException {
SecurityManager security = System.getSecurityManager();
try {
String local = impl.getLocalHostName();
if (security != null) {
security.checkConnect(local, -1);
}
// we are calling getAddressFromNameService directly
// to avoid getting localHost from cache
InetAddress[] localAddrs;
try {
localAddrs =
(InetAddress[]) InetAddress.getAddressFromNameService(local);
} catch (UnknownHostException uhe) {
throw new UnknownHostException(local + ": " + uhe.getMessage());
}
return localAddrs[0];
} catch (java.lang.SecurityException e) {
return impl.loopbackAddress();
}
}