在不连接到互联网的情况下获取本地IP地址

9 浏览
0 Comments

在不连接到互联网的情况下获取本地IP地址

我试图获取本地网络中我的机器的IP地址(应该是192.168.178.41)。

我最初的想法是使用以下代码:

InetAddress.getLocalHost().getHostAddress();

但它只返回127.0.0.1,这是正确的,但对我来说没有太大帮助。

我搜索并找到了这个答案https://stackoverflow.com/a/2381398/717341,它简单地创建一个Socket连接到某个网页(如"google.com"),并从Socket获取本地主机地址:

Socket s = new Socket("google.com", 80);

System.out.println(s.getLocalAddress().getHostAddress());

s.close();

这对我的机器有效(返回192.168.178.41),但它需要连接到互联网才能工作。由于我的应用程序不需要互联网连接,并且每次启动应用程序尝试连接到Google可能会显得"可疑",因此我不喜欢使用它。

因此,在进一步研究后,我偶然发现了NetworkInterface类,它(通过一些工作)也返回了所需的IP地址:

Enumeration interfaces = NetworkInterface.getNetworkInterfaces();

while (interfaces.hasMoreElements()){

NetworkInterface current = interfaces.nextElement();

System.out.println(current);

if (!current.isUp() || current.isLoopback() || current.isVirtual()) continue;

Enumeration addresses = current.getInetAddresses();

while (addresses.hasMoreElements()){

InetAddress current_addr = addresses.nextElement();

if (current_addr.isLoopbackAddress()) continue;

System.out.println(current_addr.getHostAddress());

}

}

在我的机器上,这返回以下内容:

name:eth1 (eth1)

fe80:0:0:0:226:4aff:fe0d:592e%3

192.168.178.41

name:lo (lo)

它找到我的两个网络接口并返回所需的IP,但我不确定另一个地址(fe80:0:0:0:226:4aff:fe0d:592e%3)的含义。

此外,我还没有找到除了使用正则表达式之外的过滤返回的地址的方法(使用InetAddress对象的isXX()方法),我认为这样做非常"不干净"。

有没有其他想法,而不是使用正则表达式或互联网?

0