如何在 c# 中使用 6.0 或更高版本获取 Mac 地址和 Android 设备?

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

我找到了一些使用 Java 的示例,但是我在构建 c# 方法时遇到了问题。任何人都可以 post 一个简单的 c# 示例,它获取我的设备的 Mac 地址,FOR Marshmallow (6.0)。我知道还有其他获取唯一 Id 的方法,此时我对必须导入组件并不感兴趣。我在 Visual Studio 2015 中使用 Xamarin。

我激活了这些权限:

ACCESS_WIFI_STATE 互联网 READ_PHONE_STATE

我尝试过的唯一代码是用于 android 6.0 版以下的简单方法。任何帮助表示赞赏。

编辑:我不认为这是重复的,因为我特别要求代码的 c# 版本

不幸的是,你运气不好。从 6.0 版本开始,Android 限制对 MAC 地址的访问。如果您尝试查询当前设备的 MAC 地址,您将得到一个常量值 02:00:00:00:00:00

您仍然可以访问附近设备的 MAC 个地址,如 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:

编辑: 虽然不支持获取 MAC 地址的官方方式,但似乎确实可以通过绕一些弯路。我 post 这里是一个最小的例子,它只遍历所有网络接口并将 MAC 地址输出到控制台,如果有的话:

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

要在现实世界中使用它需要进行一些空引用检查和其他修改,但它确实有效。