验证计算机MAC地址进行软件授权是一种通用的方法,C#可以轻松获取计算机的MAC地址,本文采用实际的源代码讲述了两种获取网卡的方式,第一种 方法使用ManagementClass类,只能获取本机的计算机网卡物理地址,第二种方法使用Iphlpapi.dll的SendARP方法,可以获取 本机和其它计算机的MAC地址。
示例:
/// <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,如图:
2.在程序开始添加包引入语句:using System.Management;
3.本方案只能获取本机的MAC地址;
示例:
//下面一种方法可以获取远程的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地址;