1.获取局域网IP地址
String hostAddress = InetAddress.getLocalHost().getHostAddress();
System.out.println("获取局域网IP地址:" + hostAddress);
2.获取全部 IPV4/IPV6 IP地址
private static List<String> getIpAddress() throws SocketException {
List<String> list = new LinkedList<>();
Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
while (enumeration.hasMoreElements()) {
NetworkInterface network = enumeration.nextElement();
if (!(network.isVirtual() || !network.isUp())) {
Enumeration<InetAddress> addresses = network.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress address = addresses.nextElement();
if ((address instanceof Inet4Address || address instanceof Inet6Address)) {
list.add(address.getHostAddress());
}
}
}
}
return list;
}
3.获取全部存放本机IP地址
private static List<String> getAllIpAddress() throws SocketException {
List<String> list = new LinkedList<>();
Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
while (enumeration.hasMoreElements()) {
NetworkInterface network = enumeration.nextElement();
Enumeration<InetAddress> addresses = network.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress address = addresses.nextElement();
if ((address instanceof Inet4Address || address instanceof Inet6Address)) {
list.add(address.getHostAddress());
}
}
}
return list;
}