getLocalHost()显示错误的IP地址

时间:2017-03-18 13:56:36

标签: java ip inetaddress

我正在尝试执行以下代码。我是Java的新手,所以这是我第一次使用java.net。程序中没有错误,但我得到的本地主机地址为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);
        }
    }
}

2 个答案:

答案 0 :(得分:2)

您应该枚举网络接口,因为您可能有多个接口。 getLocalHost()仅返回您计算机的环回地址。

Enumeration Interfaces = NetworkInterface.getNetworkInterfaces();
while(Interfaces.hasMoreElements())
{
    NetworkInterface Interface = (NetworkInterface)Interfaces.nextElement();
    Enumeration Addresses = Interface.getInetAddresses();
    while(Addresses.hasMoreElements())
    {
        InetAddress Address = (InetAddress)Addresses.nextElement();
        System.out.println(Address.getHostAddress());
    }
 }

答案 1 :(得分:0)

简短的回答,要获得您在问题中已经提到的IP地址,您必须使用:

String address = InetAddress.getLocalHost().getHostAddress();

你可以在这里找到一个很好的解释:Getting the IP address of the current machine using Java

相关问题