MacAddressHelper.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Management;
  6. using System.Net.NetworkInformation;
  7. using System.Runtime.InteropServices;
  8. using System.Text;
  9. namespace DllFileSoc
  10. {
  11. /// <summary>
  12. /// Mac地址获取帮助类 2019.10.16
  13. /// </summary>
  14. public class MacAddressHelper
  15. {
  16. /// <summary>
  17. /// 通过NetworkInterface获取MAC地址
  18. /// </summary>
  19. /// <returns></returns>
  20. public static List<string> GetMacByNetworkInterfaceList()
  21. {
  22. List<string> vs = new List<string>();
  23. try
  24. {
  25. NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
  26. foreach (NetworkInterface ni in interfaces)
  27. {
  28. vs.Add(BitConverter.ToString(ni.GetPhysicalAddress().GetAddressBytes()));
  29. }
  30. }
  31. catch (Exception)
  32. {
  33. }
  34. return vs;
  35. }
  36. ///<summary>
  37. /// 根据截取ipconfig /all命令的输出流获取网卡Mac,支持不同语言编码
  38. ///</summary>
  39. ///<returns></returns>
  40. public static string GetMacByIpConfig()
  41. {
  42. List<string> macs = new List<string>();
  43. var runCmd = Cmd.RunCmd("chcp 437&&ipconfig/all");
  44. foreach (var line in runCmd.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Select(l => l.Trim()))
  45. {
  46. if (!string.IsNullOrEmpty(line))
  47. {
  48. if (line.StartsWith("Physical Address"))
  49. {
  50. macs.Add(line.Substring(36));
  51. }
  52. else if (line.StartsWith("DNS Servers") && line.Length > 36 && line.Substring(36).Contains("::"))
  53. {
  54. macs.Clear();
  55. }
  56. else if (macs.Count > 0 && line.StartsWith("NetBIOS") && line.Contains("Enabled"))
  57. {
  58. return macs.Last();
  59. }
  60. }
  61. }
  62. return macs.FirstOrDefault();
  63. }
  64. ///<summary>
  65. /// 通过WMI读取系统信息里的网卡MAC
  66. ///</summary>
  67. ///<returns></returns>
  68. public static List<string> GetMacByWmi()
  69. {
  70. try
  71. {
  72. List<string> macs = new List<string>();
  73. ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
  74. ManagementObjectCollection moc = mc.GetInstances();
  75. foreach (ManagementObject mo in moc)
  76. {
  77. if ((bool)mo["IPEnabled"])
  78. {
  79. var mac = mo["MacAddress"].ToString();
  80. macs.Add(mac);
  81. }
  82. }
  83. return macs;
  84. }
  85. catch (Exception e)
  86. {
  87. return null;
  88. }
  89. }
  90. ///<summary>
  91. /// 通过NetworkInterface读取网卡Mac
  92. ///</summary>
  93. ///<returns></returns>
  94. public static List<string> GetMacByNetworkInterface()
  95. {
  96. List<string> macs = new List<string>();
  97. NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
  98. foreach (NetworkInterface ni in interfaces)
  99. {
  100. macs.Add(ni.GetPhysicalAddress().ToString());
  101. }
  102. return macs;
  103. }
  104. ///<summary>
  105. /// 通过SendARP获取网卡Mac
  106. /// 网络被禁用或未接入网络(如没插网线)时此方法失灵
  107. ///</summary>
  108. ///<param name="remoteIP"></param>
  109. ///<returns></returns>
  110. public static string GetMacBySendArp(string remoteIP)
  111. {
  112. StringBuilder macAddress = new StringBuilder();
  113. try
  114. {
  115. Int32 remote = inet_addr(remoteIP);
  116. Int64 macInfo = new Int64();
  117. Int32 length = 6;
  118. SendARP(remote, 0, ref macInfo, ref length);
  119. string temp = Convert.ToString(macInfo, 16).PadLeft(12, '0').ToUpper();
  120. int x = 12;
  121. for (int i = 0; i < 6; i++)
  122. {
  123. if (i == 5)
  124. {
  125. macAddress.Append(temp.Substring(x - 2, 2));
  126. }
  127. else
  128. {
  129. macAddress.Append(temp.Substring(x - 2, 2) + "-");
  130. }
  131. x -= 2;
  132. }
  133. return macAddress.ToString();
  134. }
  135. catch
  136. {
  137. return macAddress.ToString();
  138. }
  139. }
  140. [DllImport("Iphlpapi.dll")]
  141. private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
  142. [DllImport("Ws2_32.dll")]
  143. private static extern Int32 inet_addr(string ip);
  144. class Cmd
  145. {
  146. private static string CmdPath = @"C:\Windows\System32\cmd.exe";
  147. /// <summary>
  148. /// 执行cmd命令 返回cmd窗口显示的信息
  149. /// 多命令请使用批处理命令连接符:
  150. /// <![CDATA[
  151. /// &:同时执行两个命令
  152. /// |:将上一个命令的输出,作为下一个命令的输入
  153. /// &&:当&&前的命令成功时,才执行&&后的命令
  154. /// ||:当||前的命令失败时,才执行||后的命令]]>
  155. /// </summary>
  156. /// <param name="cmd">执行的命令</param>
  157. public static string RunCmd(string cmd)
  158. {
  159. cmd = cmd.Trim().TrimEnd('&') + "&exit";//说明:不管命令是否成功均执行exit命令,否则当调用ReadToEnd()方法时,会处于假死状态
  160. using (Process p = new Process())
  161. {
  162. p.StartInfo.FileName = CmdPath;
  163. p.StartInfo.UseShellExecute = false; //是否使用操作系统shell启动
  164. p.StartInfo.RedirectStandardInput = true; //接受来自调用程序的输入信息
  165. p.StartInfo.RedirectStandardOutput = true; //由调用程序获取输出信息
  166. p.StartInfo.RedirectStandardError = true; //重定向标准错误输出
  167. p.StartInfo.CreateNoWindow = true; //不显示程序窗口
  168. p.Start();//启动程序
  169. //向cmd窗口写入命令
  170. p.StandardInput.WriteLine(cmd);
  171. p.StandardInput.AutoFlush = true;
  172. //获取cmd窗口的输出信息
  173. string output = p.StandardOutput.ReadToEnd();
  174. p.WaitForExit();//等待程序执行完退出进程
  175. p.Close();
  176. return output;
  177. }
  178. }
  179. }
  180. }
  181. }