Android 6.0 – You CAN NO longer access the Mac-Address? You can !

Okay that’s new to us android developers: You can no longer get the hardware MAC address of a android device. WifiInfo.getMacAddress() and BluetoothAdapter.getAddress() methods will return 02:00:00:00:00:00. This restriction was introduced in Android 6.0.

I wanted to know if this is true. So I tested this on my OnePlus One (Android 6.0.1 Cyanogen).
 

private String getMacAddress() {
        try {
            Context cntxt = getApplicationContext();
            WifiManager wifi = (WifiManager) cntxt.getSystemService(Context.WIFI_SERVICE);
            if(wifi == null) return "Failed: WiFiManager is null";
 
            WifiInfo info = wifi.getConnectionInfo();
            if(info == null) return "Failed: WifiInfo is null";
 
            return info.getMacAddress();
        } catch (Exception e) {
            e.printStackTrace();
        }
    return "Nothing";
    }

Result:
I/System.out: My android 6.0 mac address: 02:00:00:00:00:00

This proves that you can not access the mac addess with the Android API.

 
BUT I found an alternative way to get the MAC addr on a Android 6.0 device and it still works:
 
First add Internet User-Permission to your AndroidManifest.xml:
<uses-permission android:name=“android.permission.INTERNET“ />
 
With this code I was able to figure out my mac on a android 6.0 device:
 
    public static String getMacAddr() {
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (!nif.getName().equalsIgnoreCase("wlan0")) continue;
 
                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null) {
                    return "";
                }
 
                StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    res1.append(Integer.toHexString(b & 0xFF) + ":");
                }
 
                if (res1.length() > 0) {
                    res1.deleteCharAt(res1.length() - 1);
                }
                return res1.toString();
            }
        } catch (Exception ex) {
        }
        return "02:00:00:00:00:00";
    }

Feel free to use this in all your projects. If you use this in a commercial project don’t forget to donate! 😉

One thing that you have to keep in mind: On some devices the interface is not called „wlan0“. You need to adjust that.

1 Kommentar zu “Android 6.0 – You CAN NO longer access the Mac-Address? You can !

  1. The code didn’t get mac address but generate mac randomly. If you have 2 device you will see different mac address on app connected in same wifi

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.