Utils-Linux环境下获取 IP v4 地址

获取 Linux 环境下当前的 IP v4 的 IP 地址。在不修改 Linux 系统的 host 映射的情况下,InetAddress.getLocalHost().getHostAddress()获取的 IP 地址很可能是 127.0.0.1,而真正想要的是对外 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
34
35
public ArrayList<String> getIPv4List() throws SocketException {
ArrayList<String> ipv4List = new ArrayList<>();
//返回所有网卡
Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) interfaces.nextElement();
Enumeration ipAddrEnum = ni.getInetAddresses();
while (ipAddrEnum.hasMoreElements()) {
InetAddress addr = (InetAddress) ipAddrEnum.nextElement();
if (addr.isLoopbackAddress()) {
continue;
}
String ip = addr.getHostAddress();
if (ip.contains(":")) {
//IPV6跳出本次循环
continue;
}
ipv4List.add(ip);
}
}
Collections.sort(ipv4List);

/*String ip = null;
ArrayList<String> iPv4List = this.getIPv4List();
for (String ipv4 : iPv4List) {
if (ipv4.equals("127.0.0.1")) {
continue;
}
ip = ipv4;
break;
}
return ip;*/

return ipv4List;
}

Utils-Linux环境下获取 IP v4 地址

http://blog.gxitsky.com/2020/04/22/Utils-getAllIPv4/

作者

光星

发布于

2020-04-22

更新于

2022-06-17

许可协议

评论