通過Web獲取客戶端的IP地址較簡單,從客戶端向web服務器發送的數據報中(Request對象)中即可解析出,但實際應用中,還要考慮代理服務器,路由器的轉發等等。
而獲取MAC的過程較復雜,因為客戶端向服務器發送的請求對象中不包含MAC地址,因此得到兩種思路來獲取客戶端MAC地址:
(1).在客戶端來獲取客戶機的MAC地址,所以當請求到達客戶端後,通過客戶端腳本來獲取客戶端MAC地址,然後再傳送給服務器端。
(2).先獲取客戶端IP地址,然後在局域網中發送ARP請求,通過ARP協議和已知的IP地址來解析客戶端的MAC地址
下面為獲取IP地址、MAC地址的的代碼, 以及通過發送ARP請求解析MAC地址的過程:
public static string GetWebClientIp() { string userIP = "未獲取用戶IP"; try { if (System.Web.HttpContext.Current == null || System.Web.HttpContext.Current.Request == null || System.Web.HttpContext.Current.Request.ServerVariables == null) return ""; string CustomerIP = ""; //CDN加速後取到的IP CustomerIP = System.Web.HttpContext.Current.Request.Headers["Cdn-Src-Ip"]; if (!string.IsNullOrEmpty(CustomerIP)) { return CustomerIP; } CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (!String.IsNullOrEmpty(CustomerIP)) return CustomerIP; if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null) { CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (CustomerIP == null) CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; } else { CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; } if (string.Compare(CustomerIP, "unknown", true) == 0) return System.Web.HttpContext.Current.Request.UserHostAddress; return CustomerIP; } catch { } return userIP; }
using System.Management;
public string getMac() { ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc2 = mc.GetInstances(); foreach (ManagementObject mo in moc2) { if ((bool)mo["IPEnabled"] == true) { return mo["MacAddress"].ToString(); mo.Dispose(); } } return ""; }
using System.Runtime.InteropServices; using System.Text;
[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); ////// SendArp獲取MAC地址 /// ///目標機器的IP地址如(192.168.1.1) ///目標機器的mac 地址 public static string GetMacAddress(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(); } }
首先要知道交換機是通過MAC地址通信的,但是我們是如何獲得目標主機的MAC地址呢?這時我們就需要使用ARP協議了,在每台主機中都有一張ARP表,它記錄著主機的IP地址和MAC地址的對應關系。
ARP協議是工作在網絡層的協議,它負責將IP地址解析為MAC地址。下面講解ARP的工作原理: