C#获取本机和其它计算机物理网卡地址(MAC)

验证计算机MAC地址进行软件授权是一种通用的方法,C#可以轻松获取计算机的MAC地址,本文采用实际的源代码讲述了两种获取网卡的方式,

第一种方法使用ManagementClass类,只能获取本机的计算机网卡物理地址,

第二种方法使用Iphlpapi.dll的SendARP方法,可以获取 本机和其它计算机的MAC地址。

 

方法1:使用ManagementClass类

示例:

 1 /// <summary>
 2 /// 获取网卡物理地址
 3 /// </summary>
 4 /// <returns></returns>
 5 public static string getMacAddr_Local()
 6 {
 7     string madAddr = null;
 8     ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
 9     ManagementObjectCollection moc2 = mc.GetInstances();
10     foreach (ManagementObject mo in moc2)
11     {
12         if (Convert.ToBoolean(mo["IPEnabled"]) == true)
13         {
14             madAddr = mo["MacAddress"].ToString();
15             madAddr = madAddr.Replace(':', '-');
16         }
17         mo.Dispose();
18     }
19     return madAddr;
20 }

说明:

   1.需要给项目增加引用:System.Management,如图:

   2.在程序开始添加包引入语句:using System.Management;

   3.本方案只能获取本机的MAC地址;

 

方法2:使用SendARP类

示例:

 1 //下面一种方法可以获取远程的MAC地址
 2 [DllImport("Iphlpapi.dll")]
 3 static extern int SendARP(Int32 DestIP, Int32 SrcIP, ref Int64 MacAddr, ref Int32 PhyAddrLen);
 4 [DllImport("Ws2_32.dll")]
 5 static extern Int32 inet_addr(string ipaddr);        
 6 /// <summary>
 7 /// SendArp获取MAC地址
 8 /// </summary>
 9 /// <param name="RemoteIP">目标机器的IP地址如(192.168.1.1)</param>
10 /// <returns>目标机器的mac 地址</returns>
11 public static string getMacAddr_Remote(string RemoteIP)
12 {
13     StringBuilder macAddress = new StringBuilder();
14     try
15     {
16         Int32 remote = inet_addr(RemoteIP);
17         Int64 macInfo = new Int64();
18         Int32 length = 6;
19         SendARP(remote, 0, ref macInfo, ref length);
20         string temp = Convert.ToString(macInfo, 16).PadLeft(12, '0').ToUpper();
21         int x = 12;
22         for (int i = 0; i < 6; i++)
23         {
24             if (i == 5)
25             {
26                 macAddress.Append(temp.Substring(x - 2, 2));
27             }
28             else
29             {
30                 macAddress.Append(temp.Substring(x - 2, 2) + "-");
31             }
32             x -= 2;
33         }
34         return macAddress.ToString();
35     }
36     catch
37     {
38         return macAddress.ToString();
39     }
40 }

说明:

   1.在程序开始添加包引入语句:using System.Runtime.InteropServices;

   2.该方法可以获取远程计算机的MAC地址;

 

 

posted @ 2014-01-24 14:20  fanjf  阅读(1416)  评论(0编辑  收藏  举报