[C#] 取得網卡的 MAC Address

  • 17551
  • 0

[C#] 取得網卡的 MAC Address


using System.Net.NetworkInformation;

NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();

List<string> macList = new List<string>();
foreach (var nic in nics)
{
    // 因為電腦中可能有很多的網卡(包含虛擬的網卡),
    // 我只需要 Ethernet 網卡的 MAC
    if (nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
    {
        macList.Add(nic.GetPhysicalAddress().ToString());
    }
}

 

LINQ 的寫法:


var macs = from nic in NetworkInterface.GetAllNetworkInterfaces()
           where nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet
           select nic.GetPhysicalAddress().ToString();

 

嗯,乍看之下 LINQ 好像簡潔很多,其實也還好,

不用 LINQ 也可以精簡一下:


List<string> macList = new List<string>();
foreach (var nic in NetworkInterface.GetAllNetworkInterfaces())
    if (nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
        macList.Add(nic.GetPhysicalAddress().ToString());

 

參考:

[1] C# Get Computer's MAC address “OFFLINE”