我正在尝试编写一种方法来获取计算机的mac地址。在几台计算机上测试过:
public String mac() throws UnknownHostException, SocketException {
InetAddress ip = InetAddress.getLocalHost();
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
byte[] mac = network.getHardwareAddress();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" :""));
}
System.out.println("MAC: " + sb.toString());
return(sb.toString());
}
它在运行JDK 7的计算机上执行它的操作。但是,在JDK 6上, byte [] mac 返回null,从而导致nullPointerException。任何人都知道为什么?