Java local hostname ip resolution

我与影子孤独终老i 提交于 2019-12-12 02:59:06

问题


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/



来源:https://stackoverflow.com/questions/36089518/java-local-hostname-ip-resolution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!