简体   繁体   English

Java本地主机名IP解析

[英]Java local hostname ip resolution

I am running into a weird issue on my macbook pro where hostname to ip resolution. 我在Macbook Pro上遇到了一个奇怪的问题,其中主机名到IP解析。 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 "ab-vik". 我的主机名是“ ab-vik”。 I have entries in /etc/hosts for 我在/ etc / hosts中有条目

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'? 为什么主机名不能解析为“ 127.0.0.1”? I tried with -Djava.net.preferIPv4Stack=true and get the same result. 我尝试使用-Djava.net.preferIPv4Stack = true并获得相同的结果。 Also I tried writing a C program and there it seems to give 127.0.0.1. 我也尝试编写一个C程序,它似乎给出了127.0.0.1。 So this seems to be a jvm specific issue. 因此,这似乎是特定于jvm的问题。

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. 具有相同/ etc / hosts文件的相同程序可从我朋友的mac上运行。 Not sure why I am facing this issue. 不知道为什么我要面对这个问题。 Any ideas? 有任何想法吗?

Your hosts table is invalid. 您的主机表无效。 Hosts table is a sort of map mapping ipaddresses to one or more names. 主机表是一种将ipaddress映射到一个或多个名称的映射。 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. 要求提供java IpRes 'a-\\b-vik' (或您使用的任何引号)时,您只需请求不存在名称的解析即可。

I think the JVM caches resolved names. 我认为JVM缓存已解析的名称。 You might be able to turn this off by setting the networkaddress.cache.ttl and networkaddress.cache.negative.ttl system properties to 0. 您可以通过将networkaddress.cache.ttl和networkaddress.cache.negative.ttl系统属性设置为0来关闭此功能。

Credit to the author of this article: 归功于本文的作者:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM