一、思路(主要用于局域网内)
通过Web获取客户端的IP地址较简单,从客户端向web服务器发送的数据报中(Request对象)中即可解析出,但实际应用中,还要考虑代理服务器,路由器的转发等等。
而获取MAC的过程较复杂,因为客户端向服务器发送的请求对象中不包含MAC地址,因此得到两种思路来获取客户端MAC地址:
(1).在客户端来获取客户机的MAC地址,所以当请求到达客户端后,通过客户端脚本来获取客户端MAC地址,然后再传送给服务器端。
(2).先获取客户端IP地址,然后在局域网中发送ARP请求,通过ARP协议和已知的IP地址来解析客户端的MAC地址
下面为获取IP地址、MAC地址的的代码, 以及通过发送ARP请求解析MAC地址的过程:
二、获取IP地址:
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;
}
三、通过ARP协议由IP地址获取MAC地址
1.两种方式获取MAC:
1.1.只能获取本机的MAC
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 "";
}