首页 > 代码库 > C# 获取网卡MAC的两种方式

C# 获取网卡MAC的两种方式

获取网卡MAC第一种

不能判断当前使用的是那张网卡

 1         /// <summary> 2         /// 获取网卡ID代码  3         /// </summary> 4         /// <returns></returns> 5         public static string GetNetworkAdpaterID() 6         { 7             NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); 8             return nics[0].GetPhysicalAddress().ToString(); 9 10         }

获取网卡MAC第二种

可以判断出来当前使用的是哪张网卡 但是要引入

using System.Management;

        /// <summary>        /// 获取网卡ID代码         /// </summary>        /// <returns></returns>        public static string GetNetworkAdpaterID()        {            try            {                string mac = "";                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");                ManagementObjectCollection moc = mc.GetInstances();                foreach (ManagementObject mo in moc)                    if ((bool)mo["IPEnabled"] == true)                    {                        mac += mo["MacAddress"].ToString();                        break;                    }                string[] macs = mac.Split(:);                mac = "";                foreach (string m in macs)                {                    mac += m;                }                moc = null;                mc = null;                return mac.Trim();            }            catch (Exception e)            {                return "uMnIk";            }        }

 

C# 获取网卡MAC的两种方式