C#獲取本機和其它計算機物理網(wǎng)卡地址(MAC) 驗證計算機MAC地址進行軟件授權是一種通用的方法,C#可以輕松獲取計算機的MAC地址,本文采用實際的源代碼講述了兩種獲取網(wǎng)卡的方式,第一種 方法使用ManagementClass類,只能獲取本機的計算機網(wǎng)卡物理地址,第二種方法使用Iphlpapi.dll的SendARP方法,可以獲取 本機和其它計算機的MAC地址。 方法1:使用ManagementClass類 示例: /// 獲取網(wǎng)卡物理地址 /// </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地址; 方法2:使用SendARP類 示例: //下面一種方法可以獲取遠程的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地址;
|
|