参考文档:https://zhidao.baidu.com/question/1302917822901810779.html
场景:正常使用的一段程序,最近出现有获取不到mac地址的机器,导致登录不了我们的系统
问题寻找:找到注册表下的mac address,发现在以太网的适配器下并不能找到mac address。如:计算机型号:HUAWEI MACH-WX9
分析及解决方案:一般计算机存在两个mac地址,一个是无线网卡的mac地址,一个是有线网卡的mac地址
此类型的计算机没有以太网适配器,只存在无线网卡,所以返回值总是空值,添加判定条件为找不到有线mac地址时去获取无线mac地址
原程序代码:
public string GetMacAddressByNetworkInformation()
{
string key = "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\";
string macAddress = string.Empty;
try
{
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in nics)
{
if (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet
&& adapter.GetPhysicalAddress().ToString().Length != 0)
{
string fRegistryKey = key + adapter.Id + "\\Connection";
RegistryKey rk = Registry.LocalMachine.OpenSubKey(fRegistryKey, false);
if (rk != null)
{
string fPnpInstanceID = rk.GetValue("PnpInstanceID", "").ToString();
//int fMediaSubType = Convert.ToInt32(rk.GetValue("MediaSubType", 0));
if (fPnpInstanceID.Length > 3 && fPnpInstanceID.Substring(0, 3) == "PCI")
{
macAddress = adapter.GetPhysicalAddress().ToString();
break;
}
}
}
}
}
catch (Exception ex)
{
string str = ex.Message;
}
return macAddress;
}
修改后代码:
public string GetMacAddressByNetworkInformation()
{
string key = "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\";
string macAddress = string.Empty;
try
{
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in nics)
{
if (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet
&& adapter.GetPhysicalAddress().ToString().Length != 0)
{
string fRegistryKey = key + adapter.Id + "\\Connection";
RegistryKey rk = Registry.LocalMachine.OpenSubKey(fRegistryKey, false);
if (rk != null)
{
string fPnpInstanceID = rk.GetValue("PnpInstanceID", "").ToString();
//int fMediaSubType = Convert.ToInt32(rk.GetValue("MediaSubType", 0));
if (fPnpInstanceID.Length > 3 && fPnpInstanceID.Substring(0, 3) == "PCI")
{
macAddress = adapter.GetPhysicalAddress().ToString();
break;
}
}
}
}
if (string.IsNullOrEmpty(macAddress))
{
foreach (NetworkInterface adapter in nics)
{
if (adapter.NetworkInterfaceType == NetworkInterfaceType.Wireless80211
&& adapter.GetPhysicalAddress().ToString().Length != 0)
{
string fRegistryKey = key + adapter.Id + "\\Connection";
RegistryKey rk = Registry.LocalMachine.OpenSubKey(fRegistryKey, false);
if (rk != null)
{
string fPnpInstanceID = rk.GetValue("PnpInstanceID", "").ToString();
//int fMediaSubType = Convert.ToInt32(rk.GetValue("MediaSubType", 0));
if (fPnpInstanceID.Length > 3 && fPnpInstanceID.Substring(0, 3) == "PCI")
{
macAddress = adapter.GetPhysicalAddress().ToString();
break;
}
}
}
}
}
}
catch (Exception ex)
{
string str = ex.Message;
}
return macAddress;
}
网友评论