public static String getLocalMac() throws Exception {
InetAddress ia = InetAddress.getLocalHost();
byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
if (i != 0) sb.append("-");
String s = Integer.toHexString(mac[i] & 0xFF);
sb.append(s.length() == 1 ? "0" + s : s);
}
return sb.toString().toUpperCase();
}
原理:透過 NetworkInterface 獲取硬體地址,位運算 & 0xFF 確保正數十六進制。
public static String getRemoteMac(String ip) {
try {
Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);
try (BufferedReader br = new BufferedReader(
new InputStreamReader(p.getInputStream(), "GBK"))) {
String line;
while ((line = br.readLine()) != null) {
if (line.contains("MAC 地址") || line.contains("MAC Address")) {
return line.substring(line.indexOf("=") + 1).trim();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
關鍵點:
GBK 編碼避免亂碼arp -a 或其他指令| 維度 | 本機法 | 遠端法 |
|---|---|---|
| 適用範圍 | 本機 | 局域網 Windows 主機 |
| 效能 | 極快 | 較慢(進程開銷) |
| 跨平台 | 是 | 否 |
推薦:本機優先用方法一;遠端 Windows 環境可用方法二,注意編碼與權限。