IP 地址的使用在本地网络中不起作用。我使用了其他一些方法来获取 MAC 地址 - sysout 解析有用的命令。
public String getMacAddress() throws Exception {
String macAddress = null;
String command = "ifconfig";
String osName = System.getProperty("os.name");
System.out.println("Operating System is " + osName);
if (osName.startsWith("Windows")) {
command = "ipconfig /all";
} else if (osName.startsWith("Linux") || osName.startsWith("Mac") || osName.startsWith("HP-UX")
|| osName.startsWith("NeXTStep") || osName.startsWith("Solaris") || osName.startsWith("SunOS")
|| osName.startsWith("FreeBSD") || osName.startsWith("NetBSD")) {
command = "ifconfig -a";
} else if (osName.startsWith("OpenBSD")) {
command = "netstat -in";
} else if (osName.startsWith("IRIX") || osName.startsWith("AIX") || osName.startsWith("Tru64")) {
command = "netstat -ia";
} else if (osName.startsWith("Caldera") || osName.startsWith("UnixWare") || osName.startsWith("OpenUNIX")) {
command = "ndstat";
} else {// Note: Unsupported system.
throw new Exception("The current operating system '" + osName + "' is not supported.");
}
Process pid = Runtime.getRuntime().exec(command);
BufferedReader in = new BufferedReader(new InputStreamReader(pid.getInputStream()));
Pattern p = Pattern.compile("([\\w]{1,2}(-|:)){5}[\\w]{1,2}");
while (true) {
String line = in.readLine();
System.out.println("line " + line);
if (line == null)
break;
Matcher m = p.matcher(line);
if (m.find()) {
macAddress = m.group();
break;
}
}
in.close();
return macAddress;
}
这应该在任何地方都有效。至少,在 Ubuntu 机器上使用这种方法会得到以下结果:
Operating System is Linux
line eth0 Link encap:Ethernet HWaddr f4:6d:04:63:8e:21
mac: f4:6d:04:63:8e:21