InetAddress.getAllByName() does not work as advertised?
The following snippet returns only a single InetAddress with my hostname and the loopback address 127.0.1.1:
InetAddress[] allAddresses = InetAddress.getAllByName(host);
assert allAddresses.length == 1;
assert allAddresses[0].isLoopbackAddress();
However, I can find my non-loopback IP like so:
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
for (Enumeration<NetworkInterface> e = networkInterfaces; e.hasMoreElements();) {
NetworkInterface networkInterface = e.nextElement();
Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
for (Enumeration<InetAddress> eAddresses = inetAddresses; eAddresses.hasMoreElements();) {
InetAddress address = eAddresses.nextElement();
if (!address.isLoopbackAddress()) {
return address;
}
}
}
In addition, I'm able to resolve my host name to the non-loopback IP using nslookup.
InetAddress.getAllByName() claims "given the name of a host, returns an array of its IP addresses, based on the configur开发者_JAVA百科ed name service on the system." Am I missing a configuration step?
For this method, on Linux at least,OS will read values from /etc/hosts and if it finds anything it will return it. And /etc/hosts probably only has
127.0.0.1 yourhostname
on your system.
Looks like the only way to get the desired behavior in this instance is to use something like dnsjava: http://www.dnsjava.org/dnsjava-current/examples.html
The following solves the problem.
InetAddress[] allAddresses = org.xbill.DNS.Address.getAllByName(host);
精彩评论