public static String getMac() {
try {
List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface nif : all) {
if (!"wlan0".equalsIgnoreCase(nif.getName())) {
continue;
}
byte[] macBytes = nif.getHardwareAddress();
if (macBytes == null || macBytes.length == 0) {
continue;
}
StringBuilder result = new StringBuilder();
for (byte b : macBytes) {
result.append(String.format("%02X", b));
}
return result.toString().toUpperCase();
}
} catch (Exception x) {
x.printStackTrace();
}
return "";
}
注:
1.如果是手机系统的话,上述方式可以取到正确的mac地址,亦即无线网卡的mac地址。
2.如果是TV系统的话,上述方式有时则获取不到mac地址。原因是TV系统有两块网卡:有线网卡、无线网卡,因此TV系统同时存在2个mac地址。而无线mac地址,只有开启了无线网络开关时,才能获取到。而有线mac地址则在任何情况下都可以获取到,因此TV系统推荐使用有线网卡的mac地址作为设备的mac地址。而要获取到有线mac地址,则需要将上述算法中的"wlan0"参数改为:"eth0"。