0
点赞
收藏
分享

微信扫一扫

Java 获取本机IP地址

德州spark 2022-04-17 阅读 75
java

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;
}
举报

相关推荐

0 条评论