gpt4 book ai didi

android - 在 Xamarin 中获取 Marshmallow 上的 Mac 地址

转载 作者:搜寻专家 更新时间:2023-11-01 08:36:09 32 4
gpt4 key购买 nike

我已经尝试了几种方法来在 Android 6.0 上获取 MAC 但没有成功 ):

我已经拥有此权限:

<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(); 返回一个空数组。

谁能解决这个问题?

最佳答案

尝试使用这种方法

public static string getMacAddress()
{
string macAddress = string.Empty;

var all = Collections.List(Java.Net.NetworkInterface.NetworkInterfaces);

foreach (var interfaces in all)
{
if (!(interfaces as Java.Net.NetworkInterface).Name.Contains("wlan0")) continue;

var macBytes = (interfaces as
Java.Net.NetworkInterface).GetHardwareAddress();
if (macBytes == null) continue;

var sb = new System.Text.StringBuilder();
foreach (var b in macBytes)
{
string convertedByte = string.Empty;
convertedByte = (b & 0xFF).ToString("X2") + ":";

if(convertedByte.Length == 1)
{
convertedByte.Insert(0, "0");
}
sb.Append(convertedByte);
}

macAddress = sb.ToString().Remove(sb.Length - 1);

return macAddress;
}
return "02:00:00:00:00:00";
}

关于android - 在 Xamarin 中获取 Marshmallow 上的 Mac 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36504424/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com