0

我有一个程序要求它知道它的 IP 地址。但是,当我使用

InetAddress current_addr = addresses.nextElement();

它返回

127.0.1.1

这不是很有帮助。如何从 java 获取我的非本地 IP 地址?

4

1 回答 1

1

使用时会得到什么:

InetAddress IP = InetAddress.getLocalHost();
String ipAddress  = IP.getHostAddress();

如果您没有多个网络接口,理想情况下它应该为您提供 IP 地址。

我在本地对其进行了测试,它为我提供了我机器的正确 IP 地址,即

192.168.2.10

如果您有多个网络接口,则可以尝试使用 NetworkInterface 类,示例如下:

  Enumeration<NetworkInterface> n = NetworkInterface.getNetworkInterfaces();
            for (; n.hasMoreElements();)
            {
                    NetworkInterface e = n.nextElement();
                    System.out.println("Interface: " + e.getName());
                    Enumeration<InetAddress> a = e.getInetAddresses();
                    for (; a.hasMoreElements();)
                    {
                            InetAddress addr = a.nextElement();
                            System.out.println("  " + addr.getHostAddress());
                    }
            }

来源取自相关帖子:java InetAddress.getLocalHost(); 返回 127.0.0.1 ...如何获得真实 IP?

于 2013-08-16T17:03:29.993 回答