java getLocalHost()显示错误的IP地址
我正在尝试执行以下代码。我是Java新手,所以这是我第一次使用Java。网程序中没有错误,但我得到的本地主机地址是192.168.56.1,而我的IP是192.168.2.10
import java.net.*;
class InetAddressDemo
{
public static void main(String[] args)
{
try
{
InetAddress address = InetAddress.getLocalHost();
System.out.println("\nLocalhost Address : " + address + "\n");
}
catch (Exception e)
{
System.out.println(e);
}
}
}
# 1 楼答案
一个简短的回答是,要获得您在问题中已经提到的IP地址,您必须使用:
你可以在这里找到一个很好的解释:Getting the IP address of the current machine using Java
# 2 楼答案
您应该枚举网络接口,因为您可能有多个接口。
getLocalHost()
只返回机器的环回地址