C# 获取机器的MAC地址信息方法

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Text;
  4 using System.Runtime.InteropServices;
  5 using System.Net.NetworkInformation;
  6 using System.Diagnostics;
  7 using System.Management;
  8 using System.Net;
  9 using Microsoft.Win32;
 10 using System.IO;
 11 
 12 namespace TestMoreMethodGetMac
 13 {
 14     public enum NCBCONST
 15     {
 16         NCBNAMSZ = 16,             
 17         MAX_LANA = 254,            
 18         NCBENUM = 0x37,            
 19         NRC_GOODRET = 0x00,        
 20         NCBRESET = 0x32,           
 21         NCBASTAT = 0x33,           
 22         NUM_NAMEBUF = 30,          
 23     }
 24 
 25     [StructLayout(LayoutKind.Sequential)]
 26     public struct ADAPTER_STATUS
 27     {
 28         [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
 29         public byte[] adapter_address;
 30         public byte rev_major;
 31         public byte reserved0;
 32         public byte adapter_type;
 33         public byte rev_minor;
 34         public ushort duration;
 35         public ushort frmr_recv;
 36         public ushort frmr_xmit;
 37         public ushort iframe_recv_err;
 38         public ushort xmit_aborts;
 39         public uint xmit_success;
 40         public uint recv_success;
 41         public ushort iframe_xmit_err;
 42         public ushort recv_buff_unavail;
 43         public ushort t1_timeouts;
 44         public ushort ti_timeouts;
 45         public uint reserved1;
 46         public ushort free_ncbs;
 47         public ushort max_cfg_ncbs;
 48         public ushort max_ncbs;
 49         public ushort xmit_buf_unavail;
 50         public ushort max_dgram_size;
 51         public ushort pending_sess;
 52         public ushort max_cfg_sess;
 53         public ushort max_sess;
 54         public ushort max_sess_pkt_size;
 55         public ushort name_count;
 56     }
 57 
 58     [StructLayout(LayoutKind.Sequential)]
 59     public struct NAME_BUFFER
 60     {
 61         [MarshalAs(UnmanagedType.ByValArray, SizeConst = (int)NCBCONST.NCBNAMSZ)]
 62         public byte[] name;
 63         public byte name_num;
 64         public byte name_flags;
 65     }
 66 
 67     [StructLayout(LayoutKind.Sequential)]
 68     public struct NCB
 69     {
 70         public byte ncb_command;
 71         public byte ncb_retcode;
 72         public byte ncb_lsn;
 73         public byte ncb_num;
 74         public IntPtr ncb_buffer;
 75         public ushort ncb_length;
 76         [MarshalAs(UnmanagedType.ByValArray, SizeConst = (int)NCBCONST.NCBNAMSZ)]
 77         public byte[] ncb_callname;
 78         [MarshalAs(UnmanagedType.ByValArray, SizeConst = (int)NCBCONST.NCBNAMSZ)]
 79         public byte[] ncb_name;
 80         public byte ncb_rto;
 81         public byte ncb_sto;
 82         public IntPtr ncb_post;
 83         public byte ncb_lana_num;
 84         public byte ncb_cmd_cplt;
 85         [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
 86         public byte[] ncb_reserve;
 87         public IntPtr ncb_event;
 88     }
 89 
 90     [StructLayout(LayoutKind.Sequential)]
 91     public struct LANA_ENUM
 92     {
 93         public byte length;
 94         [MarshalAs(UnmanagedType.ByValArray, SizeConst = (int)NCBCONST.MAX_LANA)]
 95         public byte[] lana;
 96     }
 97 
 98     [StructLayout(LayoutKind.Auto)]
 99     public struct ASTAT
100     {
101         public ADAPTER_STATUS adapt;
102         [MarshalAs(UnmanagedType.ByValArray, SizeConst = (int)NCBCONST.NUM_NAMEBUF)]
103         public NAME_BUFFER[] NameBuff;
104     }
105     public class Win32API
106     {
107         [DllImport("NETAPI32.DLL")]
108         public static extern char Netbios(ref   NCB ncb);
109     }
110 
111     [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
112     public class IP_Adapter_Addresses
113     {
114         public uint Length;
115         public uint IfIndex;
116         public IntPtr Next;
117 
118         public IntPtr AdapterName;
119         public IntPtr FirstUnicastAddress;
120         public IntPtr FirstAnycastAddress;
121         public IntPtr FirstMulticastAddress;
122         public IntPtr FirstDnsServerAddress;
123 
124         public IntPtr DnsSuffix;
125         public IntPtr Description;
126 
127         public IntPtr FriendlyName;
128 
129         [MarshalAs(UnmanagedType.ByValArray,
130              SizeConst = 8)]
131         public Byte[] PhysicalAddress;
132 
133         public uint PhysicalAddressLength;
134         public uint flags;
135         public uint Mtu;
136         public uint IfType;
137 
138         public uint OperStatus;
139 
140         public uint Ipv6IfIndex;
141         public uint ZoneIndices;
142 
143         public IntPtr FirstPrefix;
144     }
145     /// <summary>
146     /// 获取MAC地址的几种方法
147     /// 作者:yys(Sam Young)
148     /// 日期:2011-12-21
149     /// </summary>
150     public class MoreMethodGetMAC
151     {
152         public string GetMacAddress()
153         {
154             if (!GetMacAddressByWMI().Equals(""))
155             {
156                 return GetMacAddressByWMI();
157             }
158             if (!GetMacAddressByNetBios().Equals(""))
159             {
160                 return GetMacAddressByNetBios();
161             }
162             if (!GetMacAddressBySendARP().Equals(""))
163             {
164                 return GetMacAddressBySendARP();
165             }
166             if (!GetMacAddressByAdapter().Equals(""))
167             {
168                 return GetMacAddressByAdapter();
169             }
170             if (!GetMacAddressByDos().Equals(""))
171             {
172                 return GetMacAddressByDos();
173             }
174             return "";
175         }
176 
177         /// <summary>
178         /// 通过WMI获得电脑的mac地址
179         /// </summary>
180         /// <returns></returns>
181         public string GetMacAddressByWMI()
182         {
183             string mac = "";
184             try
185             {
186                 ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = 'TRUE'");
187                 ManagementObjectCollection queryCollection = query.Get();
188 
189                 foreach (ManagementObject mo in queryCollection)
190                 {
191                     if (mo["IPEnabled"].ToString() == "True")
192                     {
193                         mac = mo["MacAddress"].ToString();
194                         break;
195                     }
196 
197                 }
198             }
199             catch (Exception ex)
200             {
201             }
202             return mac;
203         }
204 
205         [DllImport("Iphlpapi.dll")]
206         static extern int SendARP(Int32 DestIP, Int32 SrcIP, ref Int64 MacAddr, ref Int32 PhyAddrLen);
207         /// <summary>
208         /// SendArp获取MAC地址
209         /// </summary>
210         /// <returns></returns>
211         public string GetMacAddressBySendARP()
212         {
213             StringBuilder strReturn = new StringBuilder();
214             try
215             {
216                 System.Net.IPHostEntry Tempaddr = (System.Net.IPHostEntry)Dns.GetHostByName(Dns.GetHostName());
217                 System.Net.IPAddress[] TempAd = Tempaddr.AddressList;
218                 Int32 remote = (int)TempAd[0].Address;
219                 Int64 macinfo = new Int64();
220                 Int32 length = 6;
221                 SendARP(remote, 0, ref macinfo, ref length);
222 
223                 string temp = System.Convert.ToString(macinfo, 16).PadLeft(12, '0').ToUpper();
224 
225                 int x = 12;
226                 for (int i = 0; i < 6; i++)
227                 {
228                     if (i == 5) { strReturn.Append(temp.Substring(x - 2, 2)); }
229                     else { strReturn.Append(temp.Substring(x - 2, 2) + ":"); }
230                     x -= 2;
231                 }
232 
233                 return strReturn.ToString();
234             }
235             catch
236             {
237                 return "";
238             }
239         }
240 
241 
242 
243 
244 
245         [DllImport("Iphlpapi.dll")]
246         public static extern uint GetAdaptersAddresses(uint Family, uint flags, IntPtr Reserved,
247             IntPtr PAdaptersAddresses, ref uint pOutBufLen);
248 
249         /// <summary>
250         /// 通过适配器信息获取MAC地址
251         /// </summary>
252         /// <returns></returns>
253         public string GetMacAddressByAdapter()
254         {
255             string macAddress = "";
256             try
257             {
258                 IntPtr PAdaptersAddresses = new IntPtr();
259 
260                 uint pOutLen = 100;
261                 PAdaptersAddresses = Marshal.AllocHGlobal(100);
262 
263                 uint ret =
264                     GetAdaptersAddresses(0, 0, (IntPtr)0, PAdaptersAddresses, ref pOutLen);
265 
266                 if (ret == 111)
267                 {
268                     Marshal.FreeHGlobal(PAdaptersAddresses);
269                     PAdaptersAddresses = Marshal.AllocHGlobal((int)pOutLen);
270                     ret = GetAdaptersAddresses(0, 0, (IntPtr)0, PAdaptersAddresses, ref pOutLen);
271                 }
272 
273                 IP_Adapter_Addresses adds = new IP_Adapter_Addresses();
274 
275                 IntPtr pTemp = PAdaptersAddresses;
276 
277                 while (pTemp != (IntPtr)0)
278                 {
279                     Marshal.PtrToStructure(pTemp, adds);
280                     string adapterName = Marshal.PtrToStringAnsi(adds.AdapterName);
281                     string FriendlyName = Marshal.PtrToStringAuto(adds.FriendlyName);
282                     string tmpString = string.Empty;
283 
284                     for (int i = 0; i < 6; i++)
285                     {
286                         tmpString += string.Format("{0:X2}", adds.PhysicalAddress[i]);
287 
288                         if (i < 5)
289                         {
290                             tmpString += ":";
291                         }
292                     }
293 
294 
295                     RegistryKey theLocalMachine = Registry.LocalMachine;
296 
297                     RegistryKey theSystem
298                         = theLocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces");
299                     RegistryKey theInterfaceKey = theSystem.OpenSubKey(adapterName);
300 
301                     if (theInterfaceKey != null)
302                     {
303                         macAddress = tmpString;
304                         break;
305                     }
306 
307                     pTemp = adds.Next;
308                 }
309             }
310             catch 
311             { }
312             return macAddress;
313         }
314 
315         /// <summary>
316         /// 通过NetBios获取MAC地址
317         /// </summary>
318         /// <returns></returns>
319         public string GetMacAddressByNetBios()
320         {
321             string macAddress = "";
322             try
323             {
324                 string addr = "";
325                 int cb;
326                 ASTAT adapter;
327                 NCB Ncb = new NCB();
328                 char uRetCode;
329                 LANA_ENUM lenum;
330 
331                 Ncb.ncb_command = (byte)NCBCONST.NCBENUM;
332                 cb = Marshal.SizeOf(typeof(LANA_ENUM));
333                 Ncb.ncb_buffer = Marshal.AllocHGlobal(cb);
334                 Ncb.ncb_length = (ushort)cb;
335                 uRetCode = Win32API.Netbios(ref   Ncb);
336                 lenum = (LANA_ENUM)Marshal.PtrToStructure(Ncb.ncb_buffer, typeof(LANA_ENUM));
337                 Marshal.FreeHGlobal(Ncb.ncb_buffer);
338                 if (uRetCode != (short)NCBCONST.NRC_GOODRET)
339                     return "";
340 
341                 for (int i = 0; i < lenum.length; i++)
342                 {
343                     Ncb.ncb_command = (byte)NCBCONST.NCBRESET;
344                     Ncb.ncb_lana_num = lenum.lana[i];
345                     uRetCode = Win32API.Netbios(ref   Ncb);
346                     if (uRetCode != (short)NCBCONST.NRC_GOODRET)
347                         return "";
348 
349                     Ncb.ncb_command = (byte)NCBCONST.NCBASTAT;
350                     Ncb.ncb_lana_num = lenum.lana[i];
351                     Ncb.ncb_callname[0] = (byte)'*';
352                     cb = Marshal.SizeOf(typeof(ADAPTER_STATUS)) + Marshal.SizeOf(typeof(NAME_BUFFER)) * (int)NCBCONST.NUM_NAMEBUF;
353                     Ncb.ncb_buffer = Marshal.AllocHGlobal(cb);
354                     Ncb.ncb_length = (ushort)cb;
355                     uRetCode = Win32API.Netbios(ref   Ncb);
356                     adapter.adapt = (ADAPTER_STATUS)Marshal.PtrToStructure(Ncb.ncb_buffer, typeof(ADAPTER_STATUS));
357                     Marshal.FreeHGlobal(Ncb.ncb_buffer);
358 
359                     if (uRetCode == (short)NCBCONST.NRC_GOODRET)
360                     {
361                         if (i > 0)
362                             addr += ":";
363                         addr = string.Format("{0,2:X}:{1,2:X}:{2,2:X}:{3,2:X}:{4,2:X}:{5,2:X}",
364                               adapter.adapt.adapter_address[0],
365                               adapter.adapt.adapter_address[1],
366                               adapter.adapt.adapter_address[2],
367                               adapter.adapt.adapter_address[3],
368                               adapter.adapt.adapter_address[4],
369                               adapter.adapt.adapter_address[5]);
370                     }
371                 }
372                 macAddress = addr.Replace(' ', '0');
373 
374             }
375             catch
376             {
377 
378             }
379 
380             return macAddress;
381         }
382 
383         /// <summary>
384         /// 通过DOS命令获得MAC地址
385         /// </summary>
386         /// <returns></returns>
387         public string GetMacAddressByDos()
388         {
389             string macAddress = "";
390             Process p = null;
391             StreamReader reader = null;
392             try
393             {
394                 ProcessStartInfo start = new ProcessStartInfo("cmd.exe"); 
395 
396                 start.FileName = "ipconfig";
397                 start.Arguments = "/all"; 
398 
399                 start.CreateNoWindow = true; 
400 
401                 start.RedirectStandardOutput = true; 
402 
403                 start.RedirectStandardInput = true; 
404 
405                 start.UseShellExecute = false; 
406 
407                 p = Process.Start(start);
408 
409                 reader = p.StandardOutput; 
410 
411                 string line = reader.ReadLine(); 
412 
413                 while (!reader.EndOfStream)
414                 {
415                     if (line.ToLower().IndexOf("physical address") > 0 || line.ToLower().IndexOf("物理地址") > 0)
416                     {
417                         int index = line.IndexOf(":");
418                         index += 2;
419                         macAddress = line.Substring(index);
420                         macAddress = macAddress.Replace('-', ':');
421                         break;
422                     }
423                     line = reader.ReadLine();
424                 }
425             }
426             catch
427             {
428 
429             }
430             finally
431             {
432                 if (p != null)
433                 {
434                     p.WaitForExit(); 
435                     p.Close(); 
436                 }
437                 if (reader != null)
438                 {
439                     reader.Close(); 
440                 }
441             }
442             return macAddress;
443         }
444 
445         /// <summary>
446         /// 通过网络适配器获取MAC地址
447         /// </summary>
448         /// <returns></returns>
449         public string GetMacAddressByNetworkInformation()
450         {
451             string macAddress = "";
452             try
453             {
454                 NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
455                 foreach (NetworkInterface adapter in nics)
456                 {
457                     if (!adapter.GetPhysicalAddress().ToString().Equals(""))
458                     {
459                         macAddress = adapter.GetPhysicalAddress().ToString();
460                         for (int i = 1; i < 6; i++)
461                         {
462                             macAddress = macAddress.Insert(3 * i - 1, ":");
463                         }
464                         break;
465                     }
466                 }
467 
468             }
469             catch
470             {
471             }
472             return macAddress;
473         }
474     }
475 }
posted @ 2012-05-01 01:22  小罗》  阅读(1491)  评论(0)    收藏  举报