using Microsoft.Win32; using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.IO; using System.Linq; using System.Management; using System.Net.NetworkInformation; using System.Runtime.InteropServices; using System.Text; namespace CnasSynchronousCommon { public class ComputeMessage { /// /// 获取本地MAC地址 /// /// public static string getLocalMac(ref string strErrorMsg) { string madAddr = null; List lstMacs = new List(); try { string strMethod=ConfigurationManager.AppSettings["GetMacMethod"].ToString(); switch (strMethod) { case "2": lstMacs=GetMacByIPConfig(); if (lstMacs.Count > 0) madAddr = lstMacs[0]; break; case "3": lstMacs = GetMacByNetworkInterface(); if (lstMacs.Count > 0) madAddr = lstMacs[0]; break; case "1": default: ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc2 = mc.GetInstances(); foreach (ManagementObject mo in moc2) { if (Convert.ToBoolean(mo["IPEnabled"]) == true) { madAddr = mo["MacAddress"].ToString(); madAddr = madAddr.Replace(':', '-'); } mo.Dispose(); } break; } if (madAddr == null) { strErrorMsg = "未能成功获得本机网卡的物理地址"; AppLog.Error($"没有找到本地网卡的物理地址"); return "unknown"; } } catch (Exception ex) { //这里写异常的处理 strErrorMsg = "未能成功获得本机网卡的物理地址"; AppLog.Error($"没有找到本地网卡的物理地址,{ex.Message}"); } return madAddr; } /// /// 根据截取ipconfig /all命令的输出流获取网卡Mac /// /// public static List GetMacByIPConfig() { List macs = new List(); ProcessStartInfo startInfo = new ProcessStartInfo("ipconfig", "/all"); startInfo.UseShellExecute = false; startInfo.RedirectStandardInput = true; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; startInfo.CreateNoWindow = true; Process p = Process.Start(startInfo); //截取输出流 StreamReader reader = p.StandardOutput; string line = reader.ReadLine(); while (!reader.EndOfStream) { if (!string.IsNullOrEmpty(line)) { line = line.Trim(); if (line.StartsWith("Physical Address")|| line.StartsWith("物理地址")) { if(!macs.Contains(line)) macs.Add(line); } } line = reader.ReadLine(); } //等待程序执行完退出进程 p.WaitForExit(); p.Close(); reader.Close(); return macs; } /// /// 通过NetworkInterface读取网卡Mac /// /// public static List GetMacByNetworkInterface() { List macs = new List(); NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface ni in interfaces) { if(!macs.Contains(ni.GetPhysicalAddress().ToString())) macs.Add(ni.GetPhysicalAddress().ToString()); } return macs; } } }