如何在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#时遇到了麻烦.任何人都可以发布一个简单的C#示例来获取我设备的Mac地址FOR Marshmallow(6.0).我知道还有其他获取唯一ID的方法,我现在对导入组件并不十分感兴趣.我在Visual Studio 2015中使用Xamarin.
I have found a few examples using Java, however I am having trouble constructing the method to c#. Can anyone please post a straightforward c# example that gets the Mac Address of my device, FOR Marshmallow (6.0). I understand that there are other methods of obtaining a unique Id, I am not really interested in having to import components at this time. I am using Xamarin with Visual Studio 2015.
我已激活以下权限:
ACCESS_WIFI_STATE 互联网 READ_PHONE_STATE
ACCESS_WIFI_STATE INTERNET READ_PHONE_STATE
我尝试过的唯一代码是用于android 6.0以下版本的简单方法.任何帮助表示赞赏.
The only codes I have tried are the simple methods used for below android version 6.0. Any help is appreciated.
我不认为这是重复的,因为我特别要求C#版本的代码
推荐答案
不幸的是,您不走运.从6.0版开始,Android限制对MAC地址的访问.如果您尝试查询当前设备的MAC地址,则会得到一个常量值02:00:00:00:00:00
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:
要通过蓝牙和Wi-Fi扫描访问附近的外部设备的硬件标识符,您的应用现在必须具有ACCESS_FINE_LOCATION或ACCESS_COARSE_LOCATION权限:
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地址的官方方法,但似乎可以绕开一点弯路.我在这里发布了一个最小的示例,该示例仅遍历所有网络接口,如果有,则将MAC地址输出到控制台:
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.
这篇关于如何在c#中使用6.0或更高版本获取Mac地址和Android设备?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!