How do I get the Mac Address for and Android Device using 6.0 or higher in c#?

醉酒当歌 提交于 2019-12-05 13:45:51

Unfortunately, you're out of luck. Starting from version 6.0, Android restricts the access to the MAC address. If you try to query the MAC address of your current device, you'll get a constant value of 02:00:00:00:00:00

You can still access MAC addresses of the nearby devices, as is stated in the official Android documentation:

To access the hardware identifiers of nearby external devices via Bluetooth and Wi-Fi scans, your app must now have the ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION permissions:

Edit: While the official way of getting the MAC address is not supported, it sure seems to be possible by taking a little detour. I post here a minimal example that just goes through all network interfaces and outputs the MAC addresses to the console if there's one:

// NetworkInterface is from Java.Net namespace, not System.Net
var all = Collections.List(NetworkInterface.NetworkInterfaces);

foreach (var interface in all)
{
    var macBytes = (interface as NetworkInterface).GetHardwareAddress();

    if (macBytes == null) continue;

    var sb = new StringBuilder();
    foreach (var b in macBytes)
    {
        sb.Append((b & 0xFF).ToString("X2") + ":");
    }

    Console.WriteLine(sb.ToString().Remove(sb.Length - 1));
}

To use this in a real world scenario requires some null reference checking and other modifications, but it works.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!