Java local hostname ip resolution

2019-08-30 22:56发布

问题:

I am running into a weird issue on my macbook pro where hostname to ip resolution. Here is the code,

import java.net.InetAddress;

public class IpRes {
  public static void main(String[] args) throws Exception {
    String host = args[0];
    InetAddress address = InetAddress.getByName(host);
    System.out.println(address.getHostAddress());
  }
}

My host name is "a-b-vik". I have entries in /etc/hosts for

127.0.0.1 localhost
127.0.0.1 a-b-vik 

Here is output when I run the above program,

java IpRes "localhost"
127.0.0.1

java IpRes "a-b-vik"
10.0.0.4

Why is the hostname not resolving to '127.0.0.1'? I tried with -Djava.net.preferIPv4Stack=true and get the same result. Also I tried writing a C program and there it seems to give 127.0.0.1. So this seems to be a jvm specific issue.

What is weird is that I able to get it to work if I use a '\' anywhere in my hostname. For example,

java IpRes "a-\b-vik'
127.0.0.1

The same program with same /etc/hosts file works from my friend's mac. Not sure why I am facing this issue. Any ideas?

回答1:

Your hosts table is invalid. Hosts table is a sort of map mapping ipaddresses to one or more names. Try the following:

127.0.0.1 localhost a-b-vik

Your last conclusion is wrong. In asking for java IpRes 'a-\b-vik' (or whatever quotes you used) you simply request the resolution of a non existing name.



回答2:

I think the JVM caches resolved names. You might be able to turn this off by setting the networkaddress.cache.ttl and networkaddress.cache.negative.ttl system properties to 0.

Credit to the author of this article:

http://www.myhowto.org/java/42-understanding-host-name-resolution-and-dns-behavior-in-java/