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