62,041
社区成员
发帖
与我相关
我的任务
分享
private static string GetClientIp(bool skipproxy)
{
string result = null;
if (skipproxy)
{
//忽略代理,获取客户端IP或最后一个代理IP
result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
else
{
#region 有代理,获取客户端IP,有伪造可能
foreach (var header in new[] { "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR", "HTTP_FROM", "REMOTE_ADDR" })
{
string temp = System.Web.HttpContext.Current.Request.ServerVariables[header];
if (!string.IsNullOrEmpty(temp) && IsIpAddress(temp))
{
result = temp;
break;
}
}
if (string.IsNullOrEmpty(result))
{
result = HttpContext.Current.Request.UserHostAddress;
}
if (string.IsNullOrEmpty(result))
{
#region get local(LAN) Connected ip address
//LAN ip地址
string stringHostName = Dns.GetHostName();
//Get Ip Host Entry
IPHostEntry ipHostEntries = Dns.GetHostEntry(stringHostName);
//Ip Host地址集
IPAddress[] arrIpAddress = ipHostEntries.AddressList;
if (arrIpAddress.Length >= 2)
{
result = arrIpAddress[arrIpAddress.Length - 2].ToString();
}
else if (arrIpAddress.Length > 0)
{
result = arrIpAddress[0].ToString();
}
else
{
arrIpAddress = Dns.GetHostAddresses(stringHostName);
result = arrIpAddress.Length >= 0 ? arrIpAddress[0].ToString() : "127.0.0.1";
}
#endregion
}
//多个代理情况处理,一般第一个会是真实iP
if (!string.IsNullOrEmpty(result))
{
result = result.Split(',')[0].Trim();
}
#endregion
}
if (result == "::1")
{
return "127.0.0.1";
}
return IsIpAddress(result) ? result : "invalid ip";
}