feat: IP地址取MAC地址工具
This commit is contained in:
@@ -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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user