
top.bluesword.util.network.LocalIpAddressUtil Maven / Gradle / Ivy
The newest version!
package top.bluesword.util.network;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
/**
* 获取本地ip4的工具
* @author 李林峰
*/
public class LocalIpAddressUtil {
private LocalIpAddressUtil() {
}
/**
* 获取本地ip地址列表,兼容多网卡情景
* @return 本地ip地址列表
* @throws SocketException if an I/O error occurs,
* or if the platform does not have at least one configured
* network interface.
*/
public static Set resolveLocalAddresses() throws SocketException {
Set addresses = new HashSet<>();
Enumeration ns = NetworkInterface.getNetworkInterfaces();
while (ns.hasMoreElements()) {
NetworkInterface n = ns.nextElement();
Enumeration is = n.getInetAddresses();
while (is.hasMoreElements()) {
InetAddress i = is.nextElement();
if (!i.isLoopbackAddress() && !i.isLinkLocalAddress() && !i.isMulticastAddress()
&& !isSpecialIp(i.getHostAddress())) addresses.add(i);
}
}
return addresses;
}
/**
* 获取字符串ip4地址
* @return 字符串ip4地址
* @throws SocketException if an I/O error occurs,
* or if the platform does not have at least one configured
* network interface.
*/
public static Set resolveLocalIps() throws SocketException {
Set ret = new HashSet<>();
for (InetAddress addr : resolveLocalAddresses()) ret.add(addr.getHostAddress());
return ret;
}
/**
* 判断是否是特殊专用地址
*/
private static boolean isSpecialIp(String ip) {
return ip.contains(":") || ip.startsWith("169.254.") || ip.startsWith("127.");
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy