gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:30:50 31 4
gpt4 key购买 nike

以前,当我使用 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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com