String hostAddress = InetAddress.getLocalHost().getHostAddress();
上述代码在 Java 1.7 和 1.6 上的工作方式有所不同。在 1.6 中,它返回分配给系统的正确 IP (10.4...)。在 1.7 中,它返回 127.0.0.1。
要解决此问题,我必须使用 NetworkInterface.getNetworkInterfaces()
并从中获取 InetAddress
。我将尝试连接到每个可用的 InetAddress
直到一次成功。这很有效,但我想知道为什么 Java 1.7 的行为不同?
任何帮助都会很棒。
最佳答案
很难确切地说,但有一些想法:
来自docs :
Returns the address of the local host. This is achieved by retrieving the name of the host from the system, then resolving that name into an InetAddress.
表明 @Jayamohan 提到的对 gethostname
的更改将是相关的。
同样来自文档
If the operation is not allowed, an InetAddress representing the loopback address is returned.
这就是您所得到的。
<小时/>127.0.0.1 确实是您计算机的有效地址(很可能)。在多地址系统中,JVM 如何确定您想要哪个 IP?
关于java - 为什么 InetAddress.getLocalHost() 在 Java 1.7 中表现不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15566350/