Java本地主机名IP解析 [英] Java local hostname ip resolution
问题描述
我在Macbook Pro上遇到了一个奇怪的问题,其中主机名为IP解析.这是代码,
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());
}
}
我的主机名是"a-b-vik".我在/etc/hosts中有条目
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
为什么主机名不能解析为"127.0.0.1"?我尝试使用-Djava.net.preferIPv4Stack = true并获得相同的结果.我也尝试编写一个C程序,它似乎给出了127.0.0.1.因此,这似乎是特定于jvm的问题.
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
具有相同/etc/hosts文件的相同程序可从我朋友的mac上运行.不知道为什么我要面对这个问题.有什么想法吗?
The same program with same /etc/hosts file works from my friend's mac. Not sure why I am facing this issue. Any ideas?
推荐答案
我认为JVM缓存了已解析的名称.您可以通过将networkaddress.cache.ttl和networkaddress.cache.negative.ttl系统属性设置为0来关闭此功能.
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.
本文作者的致谢:
http://www.myhowto.org/java/42-understanding-host-name-resolution-and-dns-behavior-in-java/
这篇关于Java本地主机名IP解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!