From b433c8480e49d3553a6f019b8496825ea9128020 Mon Sep 17 00:00:00 2001 From: qiminbao Date: Fri, 31 Oct 2025 16:07:26 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A4=9A=E7=BD=91IP=E6=8E=A2=E6=B5=8B-?= =?UTF-8?q?=E8=BF=87=E6=BB=A4=E6=97=A0=E7=BD=91=E5=85=B3=E7=BD=91=E5=8D=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../tongran/agent/client/utils/AgentUtil.java | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/src/main/java/com/tongran/agent/client/utils/AgentUtil.java b/src/main/java/com/tongran/agent/client/utils/AgentUtil.java index 14aaaf9..868ce40 100644 --- a/src/main/java/com/tongran/agent/client/utils/AgentUtil.java +++ b/src/main/java/com/tongran/agent/client/utils/AgentUtil.java @@ -251,6 +251,9 @@ public class AgentUtil { return swapped; } + // 存储网关信息:接口名 -> 网关IP + private static Map gatewayMap = new HashMap<>(); + // 正则表达式匹配:当前 IP:xxx.xxx.xxx.xxx 来自于:中国 江苏省 南京市 电信 private static final String REGEX = "来自于:(\\S+)\\s+(\\S+)\\s+(\\S+)\\s+(\\S+)"; /** @@ -280,6 +283,12 @@ public class AgentUtil { String name = ni.getName(); if (!isEthernetInterface(name)) continue; + // 检查是否“已连接”(物理链路状态) + if (!isInterfaceConnected(name)) continue; + + // 检查IP4信息 + if (getIPv4Address(ni).equals("N/A")) continue; + NetworkInterfaceInfo info = NetworkInterfaceInfo.builder() .name(name) .type("Ethernet") @@ -390,6 +399,42 @@ public class AgentUtil { return "N/A"; } + // 检查接口是否“已连接”(物理链路状态) + private static boolean isInterfaceConnected(String interfaceName) { + try { + String os = System.getProperty("os.name").toLowerCase(); + Process process; + + if (os.contains("win")) { + // Windows: 使用 wmic 检查网卡是否启用 + process = Runtime.getRuntime().exec( + "wmic nic where \"NetEnabled=true\" get Name"); + } else { + // Linux: 检查 operstate + process = Runtime.getRuntime().exec( + "cat /sys/class/net/" + interfaceName + "/operstate"); + } + + BufferedReader reader = new BufferedReader( + new InputStreamReader(process.getInputStream())); + String line; + while ((line = reader.readLine()) != null) { + if (os.contains("win")) { + if (line.trim().equalsIgnoreCase(interfaceName)) { + return true; + } + } else { + return "up".equals(line.trim()); + } + } + reader.close(); + return false; + } catch (Exception e) { + System.err.println("无法检查接口状态: " + interfaceName); + return false; // 保守处理 + } + } + /** * 获取公网 IP */