InetAddress:getHostAddress()返回127.x.x.x而不是外部IP地址

时间:2019-05-24 12:42:13

标签: 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通过防火墙。

1 个答案:

答案 0 :(得分:3)

该功能的结果取决于系统的配置(操作系统将其主机视为“规范”主机),该配置可能取决于系统和配置。

要查找系统的Internet地址,请使用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;
        }
    }
}
相关问题