首页 文章

在Android 6.0中获取MAC地址

提问于
浏览
41

我正在开发一个获取设备MAC地址的应用程序,但是因为Android 6.0我的代码不起作用,给我一个不正确的值 .

这是我的代码......

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

    return(info.getMacAddress().toUpperCase());
}

它返回一个奇怪的代码:“02:00:00:00:00:00”,而不是真正的MAC地址 .

有人可以帮我解决吗?

9 回答

  • 1

    答案大多是正确的,但请注意,android 7中有一个变化 . 你需要使用

    DevicePolicyManager 和方法 getWifiMacAddress . 官方文档有拼写错误,这意味着你不应该从那里复制/粘贴它 .

    DevicePolicyManager.getWifiMacAddress()
    

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

    Get Device mac adress in Android Nougat and O programmatically

  • 13

    请参阅Android 6.0 Changes .

    为了向用户提供更好的数据保护,从此版本开始,Android会删除使用Wi-Fi和蓝牙API对应用程序的设备本地硬件标识符的编程访问 . WifiInfo.getMacAddress()和BluetoothAdapter.getAddress()方法现在返回一个常量值02:00:00:00:00:00 . 要通过蓝牙和Wi-Fi扫描访问附近外部设备的硬件标识符,您的应用现在必须具有ACCESS_FINE_LOCATION或ACCESS_COARSE_LOCATION权限 .

  • 9

    使用以下代码在Android 6.0中获取Mac地址

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

    我没有得到上述工作的答案,但偶然发现了另一个答案 .

    这是获取IPv6地址然后从中获取mac地址的完整而简单的方法 .

    How to get Wi-Fi Mac address in 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";
    }
    

    已经测试过,它可以工作 . 非常感谢Rob Anderson!

  • 26

    这是在Marshmallow上成功获得它的完整2路代码,只需复制过去就可以了!

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

    清单:

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
        <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    
    • Summary : this code will try to get the MAC address first by Interface and if its failed it get it by file system.

    • Note:for file System way, you need to enable WIFI to access the file.

    thnx对Sam的回答https://stackoverflow.com/a/39288868/3818437

  • 6

    您可以从IPv6本地地址获取MAC地址 . 例如,IPv6地址“fe80 :: 1034:56ff:fe78:9abc”对应于MAC地址“12-34-56-78-9a-bc” . 请参阅下面的代码 . 获取WiFi IPv6地址只需要android.permission.INTERNET .

    请参阅维基百科页面IPv6 address,特别是关于"local addresses" fe80 :: / 64的注释和关于"Modified EUI-64"的部分 .

    /**
     * Gets an EUI-48 MAC address from an IPv6 link-local address.
     * E.g., 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;
    }
    
  • 33

    我尝试使用2种方法获取mac地址,首先是通过接口,如果失败,我通过文件系统得到它,但你需要启用wifi来访问该文件 .

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

    将此行添加到清单中 .

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

    我建议你像这里一样在你的偏好中保留你的mac地址

    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();
                        }
                    }
    
  • 0

    首先,您需要添加Internet用户权限 .

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

    然后,您可以通过NetworkInterfaces API找到mac .

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

    Its Perfectly Fine

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

相关问题