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