0%

Java如何获取到本地的ip地址

在 Java 程序中,我们可以通过如下代码获取本地的 ip 地址:

1
InetAddress.getLocalHost().getHostAddress()

但由于安装了虚拟机,或者由于本地回环网的问题,获取的 ip 地址可能不是想要的那个。可以采用如下方法获取到所有的 ip 地址列表,再做筛选。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package gy.finolo.ipdemo;

import java.net.*;
import java.util.Enumeration;

public class IPDemo {

public static void main(String[] args) throws UnknownHostException, SocketException {

System.out.println(InetAddress.getLocalHost().getHostAddress());

Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();

while (inetAddresses.hasMoreElements()) {
InetAddress inetAddress = inetAddresses.nextElement();

if (inetAddress instanceof Inet4Address) {

System.out.println(inetAddress.getHostAddress() + " loopback: " + inetAddress.isLoopbackAddress() +
" linklocal: " + inetAddress.isLinkLocalAddress() +
" sitelocal: " + inetAddress.isSiteLocalAddress());
}

if (inetAddress instanceof Inet6Address) {
System.out.println(((Inet6Address) inetAddress).getScopedInterface());
}
}
}
}
}

如果还不能区分,那就可能需要通过网卡名字来过滤了,这个是需要用到 Inet6Address 了。