Get the mac address of the device in Android

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 "";
}

Note:
1. If it is a mobile phone system, the above method can get the correct mac address, that is, the mac address of the wireless network card.
2. If it is a TV system, sometimes the mac address cannot be obtained by the above method. The reason is that the TV system has two network cards: a wired network card and a wireless network card, so there are two mac addresses in the TV system at the same time. The wireless mac address can only be obtained when the wireless network switch is turned on. The wired mac address can be obtained under any circumstances, so the TV system recommends using the mac address of the wired network card as the mac address of the device. To get the wired mac address, you need to change the "wlan0" parameter in the above algorithm to: "eth0".

 

Guess you like

Origin blog.csdn.net/chenzhengfeng/article/details/107706992