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.
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.
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