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

时间:2022-10-14 13:41:20
 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                 }