本文介绍了在Xamarin中的棉花糖上获取Mac地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在尝试几种方法来在Android 6.0上获得MAC,但没有成功):
I've been trying several things to get the MAC on Android 6.0 with no success ):
我已经拥有此权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
这是我的代码:
public string GetMacAdress(Context context)
{
string mac = GetMacAddressLegacy(context);
if (mac == "02:00:00:00:00:00")
{
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface nif in interfaces)
{
if (!nif.Name.ToLower().Contains("wlan")) continue;
var physicalAddress = nif.GetPhysicalAddress();
byte[] macBytes = physicalAddress.GetAddressBytes();
if (macBytes == null) continue;
string macString = BitConverter.ToString(macBytes);
if (!string.IsNullOrWhiteSpace(macString)) mac = macString.Trim().ToUpper().Replace("-", ":");
}
}
return mac;
}
[Obsolete]
public string GetMacAddressLegacy(Context context)
{
string toReturn = "02:00:00:00:00:00";
if (DetectWifiNetwork())
{
isConected = true;
var telephonyMgr = (WifiManager)context.GetSystemService(Context.WifiService);
toReturn = telephonyMgr.ConnectionInfo.MacAddress;
if (!string.IsNullOrWhiteSpace(toReturn)) toReturn = toReturn.Trim().ToUpper();
}
else
{
isConected = false;
}
return toReturn;
}
但是这一行: byte [] macBytes = physicalAddress.GetAddressBytes();
返回一个空数组.
But this line: byte[] macBytes = physicalAddress.GetAddressBytes();
returns an empty array.
任何人都可以解决这个问题吗?
Anyone could solve this?
推荐答案
尝试使用此代码:
public string GetMacAdress(Context context)
{
string mac = GetMacAddressLegacy(context);
if (mac == "02:00:00:00:00:00")
{
var interfaces = Java.Net.NetworkInterface.NetworkInterfaces;
foreach (var nif in interfaces)
{
if (!nif.Name.ToLower().Contains("wlan")) continue;
byte[] macBytes = nif.GetHardwareAddress();
string macString = BitConverter.ToString(macBytes);
if (!string.IsNullOrWhiteSpace(macString))
mac = macString.Trim().ToUpper().Replace("-", ":");
}
}
return mac;
}
这篇关于在Xamarin中的棉花糖上获取Mac地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!