C#获得本机物理网卡的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();
                        for (int i = 1; i < 6; i++)
                        {
                            macAddress = macAddress.Insert(3 * i - 1, ":");
                        }
                        break;
                    }
                }  
                        
            }
        }
    }
    catch(Exception ex)
    {
        //这里写异常的处理
    }
    return macAddress;
}

你可能感兴趣的:(C#获得本机物理网卡的MAC地址而非虚拟网卡MAC地址)