简体   繁体   English

如何在 C# 中仅检索以太网 MAC 地址

[英]How do I retrieve only Ethernet MAC Address in C#

I want to get MAC address of Ethernet Only but It sometime shows Wifi MAC Address too.我想仅获取以太网的 MAC 地址,但有时也会显示 Wifi MAC 地址。

I Tried this code and while debugging I found out PC used only Wifi Network Interface Type.我试过这段代码,在调试时我发现 PC 只使用了 Wifi 网络接口类型。 But whenever Ethernet is unplugged the code works.但是只要拔掉以太网,代码就会起作用。 Network Interface Type changes to ethernet itself.网络接口类型更改为以太网本身。

public static PhysicalAddress GetMacAddress()
{
       foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
       {
           // Only consider Ethernet network interfaces
           if (nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet) 
           {
               return nic.GetPhysicalAddress();
           }
           else
           {
               MessageBox.Show("Error ", "Error!");
               Environment.Exit(1);
           }
       }
       return null;
}

As long as the computer has a LAN (ethernet) adapter installed and the adapter isn't disabled, it will show up regardless of whether or not it is connected (has an IP address).只要计算机安装了 LAN(以太网)适配器并且该适配器未被禁用,无论它是否已连接(具有 IP 地址),它都会显示出来。 If you only want to get the MAC address if it is connected then do the following:如果您只想获取已连接的 MAC 地址,请执行以下操作:

using System.Net.NetworkInformation;

public static PhysicalAddress GetMacAddress()
{
    foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
    {
        // Only consider Ethernet network interfaces
        if ((nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet || nic.NetworkInterfaceType == NetworkInterfaceType.GigabitEthernet) && nic.OperationalStatus == OperationalStatus.Up)
        {
            return nic.GetPhysicalAddress();
        }
        else
        {
            MessageBox.Show("Error ", "Error!");
            Environment.Exit(1);
        }
    }
    return null;
}

See also也可以看看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM