Cómo obtener la dirección MAC en Android 6.0

Estoy desarrollando una aplicación que recibe la dirección MAC del dispositivo, pero desde Android 6.0 mi código no funciona, dándome un valor incorrecto.

Aquí está mi código …

public String ObtenMAC() { WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE); WifiInfo info = manager.getConnectionInfo(); return(info.getMacAddress().toUpperCase()); } 

En lugar de la dirección MAC real, devuelve un código extraño: "02: 00: 00: 00: 00: 00".

¿Puede alguien ayudarme a resolverlo ?.

Gracias por adelantado.

Consulte los cambios de Android 6.0 .

Para ofrecer a los usuarios una mayor protección de datos, a partir de esta versión, Android elimina el acceso programático al identificador de hardware local del dispositivo para las aplicaciones que utilizan las APIs Wi-Fi y Bluetooth. Los métodos WifiInfo.getMacAddress () y BluetoothAdapter.getAddress () ahora devuelven un valor constante de 02: 00: 00: 00: 00: 00.

Para acceder a los identificadores de hardware de los dispositivos externos cercanos mediante exploraciones Bluetooth y Wi-Fi, su aplicación debe tener ahora los permisos ACCESS_FINE_LOCATION o ACCESS_COARSE_LOCATION.

Usa código debajo para obtener la dirección de Mac en Android 6.0

 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) { //handle exception } return ""; } 

No obtuve la respuesta anterior para trabajar, pero tropezó con otra respuesta.

Aquí está un método completo y simple en conseguir la dirección IPv6 y después conseguir la dirección del mac de ella.

Cómo obtener la dirección Wi-Fi de Mac en Android Marshmallow

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

Probado ya y funciona. Muchas gracias a Rob Anderson!

Puede obtener la dirección MAC de la dirección IPv6 local. Por ejemplo, la dirección IPv6 "fe80 :: 1034: 56ff: fe78: 9abc" corresponde a la dirección MAC "12-34-56-78-9a-bc". Vea el código abajo. Obtener la dirección WiFi IPv6 sólo requiere android.permission.INTERNET.

Consulte la dirección IPv6 de la página Wikipedia, en particular la nota sobre "direcciones locales" fe80 :: / 64 y la sección sobre "EUI-64 modificado".

 /** * Gets an EUI-48 MAC address from an IPv6 link-local address. * Eg, the IPv6 address "fe80::1034:56ff:fe78:9abc" * corresponds to the MAC address "12-34-56-78-9a-bc". * <p/> * See the note about "local addresses" fe80::/64 and the section about "Modified EUI-64" in * the Wikipedia article "IPv6 address" at https://en.wikipedia.org/wiki/IPv6_address * * @param ipv6 An Inet6Address object. * @return The EUI-48 MAC address as a byte array, null on error. */ private static byte[] getMacAddressFromIpv6(final Inet6Address ipv6) { byte[] eui48mac = null; if (ipv6 != null) { /* * Make sure that this is an fe80::/64 link-local address. */ final byte[] ipv6Bytes = ipv6.getAddress(); if ((ipv6Bytes != null) && (ipv6Bytes.length == 16) && (ipv6Bytes[0] == (byte) 0xfe) && (ipv6Bytes[1] == (byte) 0x80) && (ipv6Bytes[11] == (byte) 0xff) && (ipv6Bytes[12] == (byte) 0xfe)) { /* * Allocate a byte array for storing the EUI-48 MAC address, then fill it * from the appropriate bytes of the IPv6 address. Invert the 7th bit * of the first byte and discard the "ff:fe" portion of the modified * EUI-64 MAC address. */ eui48mac = new byte[6]; eui48mac[0] = (byte) (ipv6Bytes[8] ^ 0x2); eui48mac[1] = ipv6Bytes[9]; eui48mac[2] = ipv6Bytes[10]; eui48mac[3] = ipv6Bytes[13]; eui48mac[4] = ipv6Bytes[14]; eui48mac[5] = ipv6Bytes[15]; } } return eui48mac; } 

Éste es el código completo de 2 maneras de conseguirlo con éxito en la melcocha, apenas copia pasado esto y trabajará!

 //Android 6.0 : Access to mac address from WifiManager forbidden private static final String marshmallowMacAddress = "02:00:00:00:00:00"; private static final String fileAddressMac = "/sys/class/net/wlan0/address"; public static String recupAdresseMAC(WifiManager wifiMan) { WifiInfo wifiInf = wifiMan.getConnectionInfo(); if(wifiInf.getMacAddress().equals(marshmallowMacAddress)){ String ret = null; try { ret= getAdressMacByInterface(); if (ret != null){ return ret; } else { ret = getAddressMacByFile(wifiMan); return ret; } } catch (IOException e) { Log.e("MobileAccess", "Erreur lecture propriete Adresse MAC"); } catch (Exception e) { Log.e("MobileAcces", "Erreur lecture propriete Adresse MAC "); } } else{ return wifiInf.getMacAddress(); } return marshmallowMacAddress; } private static String getAdressMacByInterface(){ try { List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface nif : all) { if (nif.getName().equalsIgnoreCase("wlan0")) { 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 e) { Log.e("MobileAcces", "Erreur lecture propriete Adresse MAC "); } return null; } private static String getAddressMacByFile(WifiManager wifiMan) throws Exception { String ret; int wifiState = wifiMan.getWifiState(); wifiMan.setWifiEnabled(true); File fl = new File(fileAddressMac); FileInputStream fin = new FileInputStream(fl); StringBuilder builder = new StringBuilder(); int ch; while((ch = fin.read()) != -1){ builder.append((char)ch); } ret = builder.toString(); fin.close(); boolean enabled = WifiManager.WIFI_STATE_ENABLED == wifiState; wifiMan.setWifiEnabled(enabled); return ret; } 

Manifiesto

 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> 
  • Resumen: este código tratará de obtener la dirección MAC primero por Interfaz y si su error lo consigue por sistema de archivos.

  • Nota: para el sistema de archivos, es necesario habilitar WIFI para acceder al archivo.

Thnx a la respuesta de Sam aquí https://stackoverflow.com/a/39288868/3818437

Intento conseguir la dirección del mac con 2 métodos, primero por interfaz y si su no, lo consigo por el sistema de ficheros, pero usted necesita permitir wifi para tener acceso al archivo.

 //Android 6.0 : Access to mac address from WifiManager forbidden private static final String marshmallowMacAddress = "02:00:00:00:00:00"; private static final String fileAddressMac = "/sys/class/net/wlan0/address"; public static String recupAdresseMAC(WifiManager wifiMan) { WifiInfo wifiInf = wifiMan.getConnectionInfo(); if(wifiInf.getMacAddress().equals(marshmallowMacAddress)){ String ret = null; try { ret= getAdressMacByInterface(); if (ret != null){ return ret; } else { ret = getAddressMacByFile(wifiMan); return ret; } } catch (IOException e) { Log.e("MobileAccess", "Erreur lecture propriete Adresse MAC"); } catch (Exception e) { Log.e("MobileAcces", "Erreur lecture propriete Adresse MAC "); } } else{ return wifiInf.getMacAddress(); } return marshmallowMacAddress; } private static String getAdressMacByInterface(){ try { List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface nif : all) { if (nif.getName().equalsIgnoreCase("wlan0")) { 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 e) { Log.e("MobileAcces", "Erreur lecture propriete Adresse MAC "); } return null; } private static String getAddressMacByFile(WifiManager wifiMan) throws Exception { String ret; int wifiState = wifiMan.getWifiState(); wifiMan.setWifiEnabled(true); File fl = new File(fileAddressMac); FileInputStream fin = new FileInputStream(fl); ret = convertStreamToString(fin); fin.close(); boolean enabled = WifiManager.WIFI_STATE_ENABLED == wifiState; wifiMan.setWifiEnabled(enabled); return ret; } 

Agregue esta línea a su manifiesto.

 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /> 

Te recomiendo que persistas tu dirección MAC en tus preferencias como aquí

 mac = activity.getSharedPreferences("MAC_ADDRESS", Context.MODE_PRIVATE).getString("MAC_ADDRESS", ""); if(mac == null || mac.equals("")){ WifiManager wifiMan = (WifiManager) activity.getSystemService(Context.WIFI_SERVICE); mac = MobileAccess.recupAdresseMAC(wifiMan); if(mac != null && !mac.equals("")){ SharedPreferences.Editor editor = activity.getSharedPreferences("MAC_ADDRESS", Context.MODE_PRIVATE).edit(); editor.putString("MAC_ADDRESS", mac).commit(); } } 

Primero debe agregar permiso de usuario de Internet.

 <uses-permission android:name="android.permission.INTERNET" /> 

A continuación, puede encontrar el mac a través de la API NetworkInterfaces.

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

Las respuestas son en su mayoría correctas, pero mantener el cuidado, que hay un cambio en android 7. Usted tendrá que utilizar el

DevicePolicyManager y el método getWifiMacAddress . Los documentos oficiales tienen un error tipográfico, lo que significa que no deberías copiarlo / pegarlo desde allí.

 DevicePolicyManager.getWifiMacAddress() 

Refs: https://developer.android.com/about/versions/nougat/android-7.0-changes.html

Obtener la dirección del dispositivo MAC en Android Nougat y O programáticamente

Está perfectamente bien

 package com.keshav.fetchmacaddress; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Collections; import java.util.List; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.e("keshav","getMacAddr -> " +getMacAddr()); } 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) { //handle exception } return ""; } } 
  • Obtener estadísticas de tráfico wifi android
  • Android wifi permiso
  • Android: Escaneado de redes Wifi + Lista seleccionable
  • ANDROID: si WiFi está habilitado Y activo, inicia una intención
  • Android / Java cómo saber el tipo de radio de wifi conectado
  • Enviar notificación a todos los dispositivos conectados a una red Wi-Fi
  • Retraso / retraso enorme de UDP con Android
  • Android activar / desactivar WiFi HotSpot mediante programación
  • Reiniciar en modo TCP puerto 5555 se bloquea adb
  • ¿Cómo compartir programaticamente la pantalla del dispositivo Android con otra vía wifi? (No captura de pantalla)
  • ¿Hay una manera de forzar una conexión de red sobre 4G, incluso cuando WiFi está habilitado y conectado?
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.