Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java InetAddress:getHostAddress()返回127.x.x.x,而不是外部IP地址_Java - Fatal编程技术网

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

Java InetAddress:getHostAddress()返回127.x.x.x,而不是外部IP地址,java,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();

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

我最近从(18.04 LTS,有OpenJDK10)[不是虚拟机]转到ubuntu 19.04,这是因为防火墙吗?在这种情况下,我如何允许java通过防火墙。

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

要查找系统的internet地址,请使用
NetworkInterface::getNetworkInterfaces()
,如下所述:

在您的情况下,您想要做的可能是:

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;
        }
    }
}
InetAddress theOneAddress=null;
枚举网络=NetworkInterface.getNetworkInterfaces();
用于(网络接口netint:Collections.list(nets)){
如果(!netint.isLoopback()){
theOneAddress=Collections.list(netint.getInetAddresses()).stream().findFirst().orElse(null);
if(theOneAddress!=null){
打破
}
}
}

您以前在哪里启动应用程序?你在什么操作系统中工作?你在虚拟机上使用ubuntu吗?请添加有关设置的详细信息
127.0.1.1
127.0.0.1
?我正在尝试复制DC++(通过intranet的文件共享辅助工具)。我需要服务器计算机的IP地址,以便客户端可以连接,发送和接收文件。在@MladenSavić行中,所有127.x.x.x地址都指向本地环回,127.0.0.1正是最常用的地址。@markrottveel谢谢。至于将其固定在操作系统级别,应该避免。更好地使用
NetworkInterface
类。是的,但根据文档:“返回本地主机的地址。这是通过从系统中检索主机名,然后将该名称解析为InetAddress来实现的。”这取决于Linux系统中/etc/hostname中的内容,可能已更改。您不应该依赖未记录的、特定于系统的解决方案在不同的操作系统和/或Java版本上工作。谢谢!还有其他选择吗?[获取我的本地ip]我确实看到了@steve smith的答案,但我需要一种本地方式来实现。基本上,您希望使用上述方法获取所有接口,然后过滤掉
isLoopback()
上返回的所有
true
。如果您有一个网络接口,那就是您应该使用的,如果没有,您可能应该考虑如何选择一个(如果您有多个网络接口,Java无法知道哪个网络接口是您的主要网络接口)。谢谢,我将尝试这一个,我不知道有一个名为
isLoopbackAddress()