C# 获取当前活动网络连接mac地址

 1                 IPAddress localIp = null;
 2                 IPAddress[] ipArray;
 3                 ipArray = Dns.GetHostAddresses(Dns.GetHostName());
 4                 localIp = ipArray.First(ip => ip.AddressFamily == AddressFamily.InterNetwork);
 5                 string resMac = "";
 6                 string resIP = "";
 7                 ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
 8                 ManagementObjectCollection moc2 = mc.GetInstances();
 9                 foreach (ManagementObject mo in moc2)
10                 {
11                     if ((bool)mo["IPEnabled"] == true && mo["IPAddress"] != null)
12 
13                     {
14                         if (((string[])mo["IPAddress"])[0] == localIp.ToString())
15                         {
16                             resMac = mo["MacAddress"].ToString();
17                             resIP = mo["IPAddress"].ToString();
18 
19                             mo.Dispose();
20 
21                             macAddress = resMac;
22                             break;
23                         }
24 
25                     }
26 
27                 }

 

posted @ 2018-06-19 16:02  dyfisgod  阅读(357)  评论(0编辑  收藏  举报