获取 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(":")) { continue; } ipv4List.add(ip); } } Collections.sort(ipv4List);
return ipv4List; }
|