C#获得MAC地址(网卡序列号)的实现代码



using System;
using System.Net.NetworkInformation;

class Program
{
    static void Main()
    {
        string macAddress = GetMacAddress();
        Console.WriteLine("MAC Address: " + macAddress);
    }

    static string GetMacAddress()
    {
        NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
        foreach (NetworkInterface ni in networkInterfaces)
        {
            // 通常,物理网络接口卡的OperationalStatus为Operational
            if (ni.OperationalStatus == OperationalStatus.Up)
            {
                // 过滤出以太网接口
                if (ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
                {
                    PhysicalAddress pa = ni.GetPhysicalAddress();
                    byte[] bytes = pa.GetAddressBytes();
                    return BitConverter.ToString(bytes).Replace("-", ":");
                }
            }
        }
        return "MAC Address Not Found";
    }
}

这段代码演示了如何在C#中获取本机的MAC地址。它遍历了所有网络接口,并寻找处于活动状态且类型为以太网的接口。一旦找到,就获取其物理地址(即MAC地址),并将其转换为标准的冒号分隔格式后返回。如果找不到符合条件的网络接口,则返回"MAC Address Not Found"。