java - 为什么 InetAddress.getLocalHost() 在 Java 1.7 中表现不同?

标签 java networking java-7

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?

More reading, similar question

关于java - 为什么 InetAddress.getLocalHost() 在 Java 1.7 中表现不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15566350/

相关文章:

linux - Linux 中的 Java7 安装

java - 字符串列表上的 @Pattern 注释

java - 使用自定义适配器更新 SQL 数据库和 ArrayList<>。

ios - 通过蓝牙或无线在 iPad/iPhone 上建立局域网的简单方法

performance - 模拟慢速互联网连接

java - 如何获取带有源代码的 Windows JDK 安装程序?

java - 错误 : You have an error with your sql syntax, 检查与您的 MariaDB 对应的手册以获取正确的语法

java - 如何更新启用 NETCONF 的设备上的配置?

iphone - 为什么我在一个网络上获得 HTTP 代码 414 而在另一个网络上却没有?

java - Java 中菱形运算符 (<>) 的作用是什么?