获得mac地址的四个方法

来源:互联网 发布:战锤2全面战争 优化 编辑:程序博客网 时间:2024/05/19 13:27
  1. using System;
  2. using System.Diagnostics;
  3. using System.Management;
  4. using System.Net;
  5. using System.Runtime.InteropServices;
  6. using System.Text.RegularExpressions;
  7. namespace MACAddress
  8. {
  9. /**//// <summary>
  10. /// MainClass 的摘要描述。
  11. /// </summary>
  12. internal class MainClass
  13. {
  14. /**//// <summary>
  15. /// 應用程式的主進入點。
  16. /// </summary>
  17. [STAThread]
  18. private static void Main(string[] args)
  19. {
  20. GetMACByWMI();
  21. IPAddress[] ips = GetLocalIP();
  22. foreach (IPAddress ip in ips)
  23. {
  24. Console.WriteLine(GetMacByARP(ip.ToString()));
  25. string mac = GetRemoteMacByNetBIOS(ip.ToString());
  26. if ( mac.Length != 0 )
  27. Console.WriteLine(mac);
  28. else
  29. Console.WriteLine("Fail to get MACAddress by NetBIOS");
  30. GetMACBySNMP(ip.ToString(),"yourGroupName@yourVlanNumber");
  31. }
  32. Console.ReadLine();
  33. }
  34. By WMI#region By WMI
  35. public static void GetMACByWMI()
  36. {
  37. string query = "select MACAddress from Win32_NetworkAdapterConfiguration where IPEnabled='TRUE'";
  38. ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
  39. ManagementObjectCollection collection = searcher.Get();
  40. foreach (ManagementObject mo in collection)
  41. {
  42. string mac = mo["MACAddress"].ToString();
  43. Console.WriteLine(" Network card MAC Address is :{0}", mac);
  44. }
  45. }
  46. #endregion
  47. By ARP#region By ARP
  48. [DllImport("Iphlpapi.dll")]
  49. private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
  50. [DllImport("Ws2_32.dll")]
  51. private static extern Int32 inet_addr(string ip);
  52. public static string GetMacByARP(string clientIP)
  53. {
  54. string ip = clientIP;
  55. Int32 ldest = inet_addr(ip);
  56. Int64 macinfo = new Int64();
  57. Int32 len = 6;
  58. try
  59. {
  60. SendARP(ldest, 0, ref macinfo, ref len);
  61. }
  62. catch
  63. {
  64. return "";
  65. }
  66. string originalMACAddress = Convert.ToString(macinfo, 16);
  67. if (originalMACAddress.Length < 12)
  68. {
  69. originalMACAddress = originalMACAddress.PadLeft(12, '0');
  70. }
  71. string macAddress;
  72. if (originalMACAddress != "0000" && originalMACAddress.Length == 12)
  73. {
  74. string mac1, mac2, mac3, mac4, mac5, mac6;
  75. mac1 = originalMACAddress.Substring(10, 2);
  76. mac2 = originalMACAddress.Substring(8, 2);
  77. mac3 = originalMACAddress.Substring(6, 2);
  78. mac4 = originalMACAddress.Substring(4, 2);
  79. mac5 = originalMACAddress.Substring(2, 2);
  80. mac6 = originalMACAddress.Substring(0, 2);
  81. macAddress = mac1 + "-" + mac2 + "-" + mac3 + "-" + mac4 + "-" + mac5 + "-" + mac6;
  82. }
  83. else
  84. {
  85. macAddress = "";
  86. }
  87. return macAddress.ToUpper();
  88. }
  89. public static IPAddress[] GetLocalIP()
  90. {
  91. string hostName = Dns.GetHostName();
  92. IPHostEntry ipEntry = Dns.GetHostByName(hostName);
  93. return ipEntry.AddressList;
  94. }
  95. #endregion
  96. By NetBIOS#region By NetBIOS
  97. public static string GetRemoteMacByNetBIOS(string clientIP)
  98. {
  99. string ip = clientIP;
  100. string dirResults = "";
  101. ProcessStartInfo psi = new ProcessStartInfo();
  102. Process proc = new Process();
  103. psi.FileName = "nbtstat.exe";
  104. //psi.RedirectStandardInput = false; 
  105. psi.RedirectStandardOutput = true;
  106. psi.RedirectStandardError = true;
  107. psi.Arguments = "-A " + ip;
  108. psi.UseShellExecute = false;
  109. proc = Process.Start(psi);
  110. dirResults = proc.StandardOutput.ReadToEnd();
  111. string error = proc.StandardError.ReadToEnd();
  112. proc.WaitForExit();
  113. dirResults = dirResults.Replace("/r", "").Replace("/n", "").Replace("/t", "");
  114. Regex reg = new Regex("Mac[ ]{0,}Address[ ]{0,}=[ ]{0,}(?((.)*?))__MAC", RegexOptions.IgnoreCase | RegexOptions.Compiled);
  115. Match mc = reg.Match(dirResults + "__MAC");
  116. if (mc.Success)
  117. {
  118. return mc.Groups["key"].Value.ToUpper();
  119. }
  120. else
  121. {
  122. return "";
  123. }
  124. }
  125. #endregion
  126. By SNMP#region By SNMP
  127. public static void GetMACBySNMP(string ip,string vlan)
  128. {
  129. int commLength,mibLength,dataStart,dataLength;
  130. string nextMib,value;
  131. SNMP conn = new SNMP();
  132. string mib = "1.3.6.1.2.1.17.4.3.1.1";
  133. int orgMibLength = mib.Length;
  134. byte[] response = new byte[1024];
  135. nextMib = mib;
  136. while ( true)
  137. {
  138. response = conn.Get("getnext",ip,vlan,nextMib);
  139. commLength = Convert.ToInt16(response[6]);
  140. mibLength = Convert.ToInt16(response[23+commLength]);
  141. dataLength = Convert.ToInt16(response[25+commLength+mibLength]);
  142. dataStart = 26 + commLength + mibLength;
  143. value = BitConverter.ToString(response,dataStart,dataLength);
  144. nextMib = conn.GetNextMIB(response);
  145. if ( !(nextMib.Substring(0,orgMibLength) == mib))
  146. {
  147. break;
  148. }
  149. Console.WriteLine("{0}={1}",nextMib,value);
  150. }
  151. }
  152. #endregion
  153. }
  154. }
  155. SNMP Class
  156. using System;
  157. using System.Net;
  158. using System.Net.Sockets;
  159. using System.Text;
  160. namespace MACAddress
  161. {
  162. /**//**//**//// <summary>
  163. /// SNMP 的摘要描述。
  164. /// </summary>
  165. public class SNMP
  166. {
  167. public SNMP()
  168. {
  169. }
  170. public byte[] Get(string request, string host, string community, string mibString)
  171. {
  172. byte[] packet = new byte[1024];
  173. byte[] mib = new byte[1024];
  174. int snmpLen;
  175. int comLen = community.Length;
  176. string[] mibVals = mibString.Split('.');
  177. int mibLen = mibVals.Length;
  178. int cnt = 0;
  179. int temp;
  180. int orgmibLen = mibLen;
  181. int pos = 0;
  182. for (int i = 0; i < orgmibLen; i++)
  183. {
  184. temp = Convert.ToInt16(mibVals[i]);
  185. if (temp > 127)
  186. {
  187. mib[cnt] = Convert.ToByte(128 + (temp / 128));
  188. mib[cnt + 1] = Convert.ToByte(temp - ((temp / 128) * 128));
  189. cnt += 2;
  190. mibLen++;
  191. }
  192. else
  193. {
  194. mib[cnt] = Convert.ToByte(temp);
  195. cnt++;
  196. }
  197. }
  198. snmpLen = 29 + comLen + mibLen - 1;
  199. packet[pos++] = 0x30;
  200. packet[pos++] = Convert.ToByte(snmpLen - 2);
  201. packet[pos++] = 0x02;
  202. packet[pos++] = 0x01;
  203. packet[pos++] = 0x00;
  204. packet[pos++] = 0x04;
  205. packet[pos++] = Convert.ToByte(comLen);
  206. byte[] data = Encoding.ASCII.GetBytes(community);
  207. for (int i = 0; i < data.Length; i++)
  208. {
  209. packet[pos++] = data[i];
  210. }
  211. if (request == "get")
  212. {
  213. packet[pos++] = 0xA0;
  214. }
  215. else
  216. {
  217. packet[pos++] = 0xA1;
  218. }
  219. packet[pos++] = Convert.ToByte(20 + mibLen - 1);
  220. packet[pos++] = 0x02;
  221. packet[pos++] = 0x04;
  222. packet[pos++] = 0x00;
  223. packet[pos++] = 0x00;
  224. packet[pos++] = 0x00;
  225. packet[pos++] = 0x01;
  226. packet[pos++] = 0x02;
  227. packet[pos++] = 0x01;
  228. packet[pos++] = 0x00;
  229. packet[pos++] = 0x02;
  230. packet[pos++] = 0x01;
  231. packet[pos++] = 0x00;
  232. packet[pos++] = 0x30;
  233. packet[pos++] = Convert.ToByte(6 + mibLen - 1);
  234. packet[pos++] = 0x30;
  235. packet[pos++] = Convert.ToByte(6 + mibLen - 1 - 2);
  236. packet[pos++] = 0x06;
  237. packet[pos++] = Convert.ToByte(mibLen - 1);
  238. packet[pos++] = 0x2b;
  239. for (int i = 2; i < mibLen; i++)
  240. {
  241. packet[pos++] = Convert.ToByte(mib[i]);
  242. }
  243. packet[pos++] = 0x05;
  244. packet[pos++] = 0x00;
  245. Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  246. sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 5000);
  247. IPHostEntry ihe = Dns.Resolve(host);
  248. IPEndPoint iep = new IPEndPoint(ihe.AddressList[0], 161);
  249. EndPoint ep = (EndPoint) iep;
  250. sock.SendTo(packet, snmpLen, SocketFlags.None, iep);
  251. try
  252. {
  253. int recv = sock.ReceiveFrom(packet, ref ep);
  254. }
  255. catch (SocketException)
  256. {
  257. packet[0] = 0xff;
  258. }
  259. return packet;
  260. }
  261. public string GetNextMIB(byte[] mibIn)
  262. {
  263. string output = "1.3";
  264. int commLength = mibIn[6];
  265. int mibStart = 6 + commLength + 17;
  266. int mibLength = mibIn[mibStart] - 1;
  267. mibStart += 2;
  268. int mibValue;
  269. for (int i = mibStart; i < mibStart + mibLength; i++)
  270. {
  271. mibValue = Convert.ToInt16(mibIn[i]);
  272. if (mibValue > 128)
  273. {
  274. mibValue = (mibValue / 128) * 128 + Convert.ToInt16(mibIn[i + 1]);
  275. i++;
  276. }
  277. output += "." + mibValue;
  278. }
  279. return output;
  280. }
  281. }
  282. }

 

原文地址:http://hi.baidu.com/ringbelling/blog/item/ab202086f0ddf43a66096ed3.html

原创粉丝点击