java - InetAddress : getHostAddress() returns 127. x.x.x 而不是外部 IP 地址

标签 java

以前,当我使用 openJDK 10 时,下面的代码给出了我的本地 IP 地址,但是现在它 (inetAddress.getHostAddress()) 总是返回 127.0.1.1

import java.net.*;

class main {
    public static void main(String[] args) throws Exception {
        InetAddress inetAddress = InetAddress.getLocalHost();
        System.out.println("IP Address:- " + inetAddress.getHostAddress());

    }
}

附加信息:

openjdk version "11.0.3" 2019-04-16
OpenJDK Runtime Environment (build 11.0.3+7-Ubuntu-1ubuntu219.04.1)
OpenJDK 64-Bit Server VM (build 11.0.3+7-Ubuntu-1ubuntu219.04.1, mixed mode, sharing)

我最近从(具有 openJDK 10 的 18.04 LTS)[不是虚拟机] 迁移到 ubuntu 19.04,这是由于防火墙吗?在那种情况下,我如何允许 java 通过防火墙。

最佳答案

该函数的结果取决于您的系统配置(您的操作系统将哪个主机视为“规范”主机),这可能取决于系统和配置。

要找到您系统的互联网地址,请使用 NetworkInterface::getNetworkInterfaces(),如所述。这里:https://docs.oracle.com/javase/tutorial/networking/nifs/listing.html

在你的情况下,你想要做的可能是这样的:

InetAddress theOneAddress = null;
Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netint : Collections.list(nets)) {
    if (!netint.isLoopback()) {
        theOneAddress = Collections.list(netint.getInetAddresses()).stream().findFirst().orElse(null);
        if (theOneAddress != null) {
            break;
        }
    }
}

关于java - InetAddress : getHostAddress() returns 127. x.x.x 而不是外部 IP 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56292941/

相关文章:

java - 我可以向 Combobox 的模型添加与 String 不同的值吗?

Java - 检查字符串是否只包含某些字符(即 DNA/RNA)

java - Spring数据 Elasticsearch : remove low disk watermark warning

java - MongoDb 如何获取缺少属性的行

java - java中存储信息

Java字节码到机器码

java - 抽屉导航无法点击页面(Android Studio)

java - 如何修改数组列表中的元素

java - 无法读取上传到 Azure Blob 的文件

java - Spring 入站 channel 适配器的最大数量是多少?