private String getMACAddress() throws UnknownHostException, SocketException {
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 str = Integer.toHexString(mac[i] & 0xFF);
sb.append(str.length() == 1 ? 0 + str : str);
}
return sb.toString().toUpperCase();
}
上述代码用的是localhost的方法来获取MAC地址,在某些情况下会返回null,如果是获取MAC地址作为设备的唯一标识,建议使用以下方法:
public static List<String> getMACAddress() throws SocketException {
Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
List<String> list = new ArrayList<>();
while (nis.hasMoreElements()) {
NetworkInterface ni = nis.nextElement();
if (ni != null && ni.isUp()) {
byte[] bytes = ni.getHardwareAddress();
if (bytes != null && bytes.length == 6) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
//与11110000作按位与运算以便读取当前字节高4位
sb.append(Integer.toHexString((b & 240) >> 4));
//与00001111作按位与运算以便读取当前字节低4位
sb.append(Integer.toHexString(b & 15));
sb.append("-");
}
sb.deleteCharAt(sb.length() - 1);
list.add(sb.toString().toUpperCase());
}
}
}
return list;
}