Saturday, October 2, 2021

Code to get WiFi MAC Address of Device in Android

 In Android we can get the MAC Address of a Device

Code to get WiFi MAC Address of Device in Android

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// only for gingerbread and newer versions
macAddressOfDevice = getMacAddr();
Log.i("KAMLESH", "MAC Address : " + macAddressOfDevice);
}
else {
WifiManager wifiMan = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInf = wifiMan.getConnectionInfo();
macAddressOfDevice = wifiInf.getMacAddress();
Log.i("KAMLESH", "MAC Address : " + macAddressOfDevice);
}


public  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(String.format("%02X:",b));
}

if (res1.length() > 0) {
res1.deleteCharAt(res1.length() - 1);
}
return res1.toString();
}
} catch (Exception ex) {
}
return "02:00:00:00:00:00";
}

No comments:

Post a Comment