2011-04-18 23:39:45|170次阅读|上传:huigezrx【已有0条评论】发表评论
关键词:C# , Windows编程|来源:VC编程网
验证计算机MAC地址进行软件授权是一种通用的方法,C#可以轻松获取计算机的MAC地址,本文采用实际的源代码讲述了两种获取网卡的方式,第一种 方法使用ManagementClass类,只能获取本机的计算机网卡物理地址,第二种方法使用Iphlpapi.dll的SendARP方法,可以获取 本机和其它计算机的MAC地址。
方法1:使用ManagementClass类
示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 |
/// <summary> /// 获取网卡物理地址 /// </summary> /// <returns></returns> public static string getMacAddr_Local() { string madAddr = null ; 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(); } return madAddr; } |
1.需要给项目增加引用:System.Management,如图:
3.本方案只能获取本机的MAC地址;
方法2:使用SendARP类
示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40 |
//下面一种方法可以获取远程的MAC地址 [DllImport( "Iphlpapi.dll" )] static extern int SendARP(Int32 DestIP, Int32 SrcIP, ref Int64 MacAddr, ref Int32 PhyAddrLen); [DllImport( "Ws2_32.dll" )] static extern Int32 inet_addr( string ipaddr); /// <summary> /// SendArp获取MAC地址 /// </summary> /// <param name="RemoteIP">目标机器的IP地址如(192.168.1.1)</param> /// <returns>目标机器的mac 地址</returns> public static string getMacAddr_Remote( string RemoteIP) { StringBuilder macAddress = new StringBuilder(); try { Int32 remote = inet_addr(RemoteIP); Int64 macInfo = new Int64(); Int32 length = 6; SendARP(remote, 0, ref macInfo, ref length); string temp = Convert.ToString(macInfo, 16).PadLeft(12, '0' ).ToUpper(); int x = 12; for ( int i = 0; i < 6; i++) { if (i == 5) { macAddress.Append(temp.Substring(x - 2, 2)); } else { macAddress.Append(temp.Substring(x - 2, 2) + "-" ); } x -= 2; } return macAddress.ToString(); } catch { return macAddress.ToString(); } } |
1.在程序开始添加包引入语句:using System.Runtime.InteropServices;
2.该方法可以获取远程计算机的MAC地址;