我使用的是Windows 8和JDK1.7。我的IP地址是192.168.1.108,当我运行时:
System.out.println(InetAddress.getLocalHost().equals(InetAddress.getByName("localhost"))); 或
System.out.println(InetAddress.getLocalHost().equals(InetAddress.getByName("127.0.0.1")));输出-都是假的。
InetAddress.getLocalHost() - Output: 192.168.1.108
InetAddress.getByName("localhost") - Output: 127.0.0.1此外,我的UDP服务器绑定在InetAddress.getLocalHost()上,如果客户端向InetAddress.getByName("localhost")发送数据包,它将无法从客户端接收任何信息。但是,如果客户端发送到InetAddress.getLocalHost().端口是合情合理的,那么它工作得很好。
有谁知道区别吗?提前谢谢。
发布于 2013-12-02 15:27:59
来自getLocalHost()的JDK文档:
返回本地主机的地址。这是通过从系统中检索主机名来实现的,然后将该名称解析为InetAddress。
在我的GNU/Linux框中,我的主机名为“膝上型计算机”,它映射到与/etc/ host中的127.0.0.1不同的地址。Windows中的C:\Windows\System32 32\drivers\etc\host上有一个等效的文件。
默认情况下,在DNS查找之前会搜索此主机文件。
发布于 2013-12-02 15:25:06
ad1为您提供局域网/广域网中的地址(我指的是本地/专用网络IP地址,例如192.168.0.108或10.3.6.55)。
另请参阅:
spaces
http://download.java.net/jdk7/archive/b123/docs/api/java/net/InetAddress.html#getLocalHost%28%29
但请注意,在我的示例中,ad2和ad3是相等的。
import java.net.InetAddress;
public class Test014 {
public static void main(String[] args) throws Exception {
InetAddress ad1 = InetAddress.getLocalHost();
InetAddress ad2 = InetAddress.getByName("localhost");
InetAddress ad3 = InetAddress.getByName("127.0.0.1");
printArr(ad1.getAddress());
printArr(ad2.getAddress());
printArr(ad3.getAddress());
System.out.println(ad1.equals(ad2));
System.out.println(ad1.equals(ad3));
System.out.println(ad2.equals(ad3));
}
static void printArr(byte[] arr){
for (int i=0; i<arr.length; i++){
System.out.print("[" + i + "] = " + arr[i] + "; ");
}
System.out.println();
System.out.println("---------");
}
}此外,请检查API文档中关于equals方法何时返回true和何时返回false的问题。
http://download.java.net/jdk7/archive/b123/docs/api/java/net/InetAddress.html#equals%28java.lang.Object%29
https://stackoverflow.com/questions/20331603
复制相似问题