我在获取机器的mac地址时遇到问题,使用下面的代码在this question中解决了该问题:
Process p = Runtime.getRuntime().exec("getmac /fo csv /nh");
java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(p.getInputStream()));
String line;
line = in.readLine();
String[] result = line.split(",");
System.out.println(result[0].replace('"', ' ').trim());
但是,我想知道为什么此代码无法正常工作。每次读取MAC地址时,它都会返回一个不同的值。首先,我认为这是因为getHash,也许使用了一个我不知道的时间戳……但是即使删除它,结果也会改变。
代码
public static byte[] getMacAddress() {
try {
Enumeration<NetworkInterface> nwInterface = NetworkInterface.getNetworkInterfaces();
while (nwInterface.hasMoreElements()) {
NetworkInterface nis = nwInterface.nextElement();
if (nis != null) {
byte[] mac = nis.getHardwareAddress();
if (mac != null) {
/*
* Extract each array of mac address and generate a
* hashCode for it
*/
return mac;//.hashCode();
} else {
Logger.getLogger(Utils.class.getName()).log(Level.WARNING, "Address doesn't exist or is not accessible");
}
} else {
Logger.getLogger(Utils.class.getName()).log(Level.WARNING, "Network Interface for the specified address is not found.");
}
return null;
}
} catch (SocketException ex) {
Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
}
输出示例(我直接从字节数组打印,但是足以看到我认为的不同)
[B@91cee
[B@95c083
[B@99681b
[B@a61164
[B@af8358
[B@b61fd1
[B@bb7465
[B@bfc8e0
[B@c2ff5
[B@c8f6f8
[B@d251a3
[B@d6c16c
[B@e2dae9
[B@ef5502
[B@f7f540
[B@f99ff5
[B@fec107
提前致谢
最佳答案
B@91cee
实际上是toString()
数组的结果byte[]
方法。
我建议您改为使用new String(mac)
打印该值。byte[].toString()
实现为:
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
由于默认的
Object.hashCode()
是作为内存中的地址实现的,因此每次创建新的Object
时,它是不一致的。编辑:
由于返回的字节为十六进制,因此应将其转换为十进制字符串。该代码可以从here中看到