From 91dd6fad8ee8888344b59fc8610d850feb453ab5 Mon Sep 17 00:00:00 2001 From: TsMask <340112800@qq.com> Date: Fri, 6 Dec 2024 21:48:40 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20IP=E5=9C=B0=E5=9D=80=E5=8F=96MAC?= =?UTF-8?q?=E5=9C=B0=E5=9D=80=E5=B7=A5=E5=85=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../wfc/common/core/utils/ip/MacUtils.java | 82 +++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 wfc-common/wfc-common-core/src/main/java/org/wfc/common/core/utils/ip/MacUtils.java diff --git a/wfc-common/wfc-common-core/src/main/java/org/wfc/common/core/utils/ip/MacUtils.java b/wfc-common/wfc-common-core/src/main/java/org/wfc/common/core/utils/ip/MacUtils.java new file mode 100644 index 0000000..c85cdac --- /dev/null +++ b/wfc-common/wfc-common-core/src/main/java/org/wfc/common/core/utils/ip/MacUtils.java @@ -0,0 +1,82 @@ +package org.wfc.common.core.utils.ip; + +import org.wfc.common.core.utils.StringUtils; + +import java.io.BufferedReader; +import java.io.InputStreamReader; + +/** + * 获取MAC地址方法 + * + * @author wfc + */ +public class MacUtils { + + /** + * 获取客户端MAC 00:50:56:b4:09:c0 + * + * @return MAC地址 + */ + public static String getMacAddress(String ipAddress) { + String macAddress = null; + try { + String os = System.getProperty("os.name").toLowerCase(); + String command = null; + + if (os.contains("win")) { + command = "arp -a " + ipAddress; // Windows + } else if (os.contains("nix") || os.contains("nux") || os.contains("mac")) { + command = "arp -n " + ipAddress; // Linux/macOS + } + + // 执行命令并获取输出 + Process process = Runtime.getRuntime().exec(command); + BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); + String line; + + while ((line = reader.readLine()) != null) { + // 输出每一行,查找包含 MAC 地址的行 + if (line.contains(ipAddress)) { + String[] tokens = line.trim().split("\\s+"); + if (os.contains("win")) { + macAddress = tokens[1]; // MAC 地址通常在第二个位置 + } else if (os.contains("nix") || os.contains("nux") || os.contains("mac")) { + macAddress = tokens[2]; // MAC 地址通常在第三个位置 + } + break; + } + } + reader.close(); + } catch (Exception e) { + e.printStackTrace(); + } + return macAddress; + } + + /** + * 转换MAC格式为 00-50-56-B4-44-4E + * + * @return MAC地址 + */ + public static String toUpperCaseMacAddress(String macAddress) { + if (StringUtils.isBlank(macAddress)) { + return null; + } + // 分割原始 MAC 地址字符串 + String[] parts = macAddress.split("-"); + + // 创建一个 StringBuilder 来存储转换后的地址 + StringBuilder convertedMac = new StringBuilder(); + + // 遍历所有部分并转换为大写 + for (int i = 0; i < parts.length; i++) { + if (i > 0) { + convertedMac.append("-"); // 在每部分之间添加分隔符 + } + // 将每个字节转换为大写 + convertedMac.append(parts[i].toUpperCase()); + } + + return convertedMac.toString(); + } +} \ No newline at end of file