This commit is contained in:
2025-11-30 00:14:48 +08:00
parent c881640667
commit fcb335726d
19 changed files with 73 additions and 281 deletions

View File

@@ -17,23 +17,47 @@ public class IpUtils {
* @return 本地IP地址获取失败返回null
*/
public static String getLocalIp() {
// 1. 优先读取宿主机注入的环境变量
String hostIp = System.getenv("HOST_MACHINE_IP");
if (isValidIp(hostIp)) {
return hostIp;
}
// 2. 尝试解析Docker网关宿主机IP
try {
InetAddress gatewayAddr = InetAddress.getByName("gateway");
if (gatewayAddr.isReachable(1000)) {
String gatewayIp = gatewayAddr.getHostAddress();
if (isValidIp(gatewayIp)) {
return gatewayIp;
}
}
} catch (Exception e) {
System.out.print(e.getMessage());
}
// 3. 过滤容器网卡获取宿主机IP
try {
// 遍历所有网络接口
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface ni = interfaces.nextElement();
// 跳过虚拟网卡、未启用的网卡
if (ni.isLoopback() || ni.isVirtual() || !ni.isUp()) {
if (ni.isLoopback() || ni.isVirtual() || !ni.isUp()
|| ni.getName().startsWith("docker")
|| ni.getName().startsWith("veth")
|| ni.getName().startsWith("cni0")) {
continue;
}
// 遍历该网卡下的所有IP地址
Enumeration<InetAddress> addresses = ni.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress addr = addresses.nextElement();
// 仅保留IPv4地址且排除回环地址
if (addr instanceof Inet4Address && !addr.isLoopbackAddress()) {
String ip = addr.getHostAddress();
if (!ip.startsWith("172.") && !ip.startsWith("192.168.31.")) {
// 过滤容器内网段
if (!ip.startsWith("172.")
&& !ip.startsWith("192.168.99.")
&& !ip.startsWith("10.0.")
&& isValidIp(ip)) {
return ip;
}
}
@@ -42,9 +66,36 @@ public class IpUtils {
} catch (SocketException e) {
e.printStackTrace();
}
// 4. 兜底返回回环地址
return getLoopbackIp();
}
/**
* 验证是否为合法IPv4地址
*/
private static boolean isValidIp(String ip) {
if (ip == null || ip.isEmpty()) {
return false;
}
String[] parts = ip.split("\\.");
if (parts.length != 4) {
return false;
}
for (String part : parts) {
try {
int num = Integer.parseInt(part);
if (num < 0 || num > 255) {
return false;
}
} catch (NumberFormatException e) {
return false;
}
}
return true;
}
/**
* 获取回环地址127.0.0.1
*