获取多级代理时客户端真实IP地址
一、取到客户端IP地址(包括多级代理情况下获取)
#region 获取 HTTP 请求的客户端 IP 地址(包括多级代理的情况)
/// <summary>
/// 获取 HTTP 请求的客户端 IP 地址。
/// </summary>
/// <param name="context">HTTP 的执行上下文对象。</param>
/// <returns>客户端 IP 地址。</returns>
public static String GetHttpClientIp(HttpContext context)
{
String ipAddress = String.Empty;
if (null != context && null != context.Request)
{
String remoteAddr = context.Request.ServerVariables["REMOTE_ADDR"] ?? String.Empty;
String httpXForwardedFor = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? String.Empty;
remoteAddr = remoteAddr.Trim();
httpXForwardedFor = httpXForwardedFor.Trim();
if (!string.IsNullOrEmpty(httpXForwardedFor))
{ // 存在代理的情况下。
if (httpXForwardedFor.IndexOf(".") > 0)
{ // 判断是否非IP V6(2001:0db8:85a3:08d3:1319:8a2e:0370:7344)。
if (httpXForwardedFor.IndexOf(",") > 0)
{ // 多个代理的情况下。
httpXForwardedFor = httpXForwardedFor.Replace(" ", "").Replace("'", "");
String[] tempArrayIp = httpXForwardedFor.Split(",;".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < tempArrayIp.Length; i++)
{
if (!IsIPV4Innner(tempArrayIp[i]) && IsIPV4(tempArrayIp[i]))
{
ipAddress = tempArrayIp[i];
}
}
}
else if (!IsIPV4Innner(httpXForwardedFor) && IsIPV4(httpXForwardedFor))
{ // 单个代理的情况下。
ipAddress = httpXForwardedFor;
}
}
}
if (string.IsNullOrEmpty(ipAddress) && IsIPV4(remoteAddr))
{
ipAddress = remoteAddr;
}
if (string.IsNullOrEmpty(ipAddress))
{
ipAddress = context.Request.UserHostAddress;
}
}
return ipAddress;
}
#endregion
二、根据实际业务需要验证是否为自己内网的IP地址(匹配规则根据自己内网IP).
#region 判断指定字符串是否是 IP V4 格式的内网 IP
/// <summary>
/// 判断指定字符串是否是 IP V4 格式的内网 IP。
/// </summary>
/// <param name="ipAddress">表示 IP V4 的字符串。</param>
/// <returns>
/// 如果是 IP V4 格式的内网 IP字符串,则返回<c>true</c>;否则,返回<c>false</c>。
/// </returns>
public static Boolean IsIPV4Innner(String ipAddress)
{
Int64 aBegin = IpAddressToLong("10.0.0.0");
Int64 aEnd = IpAddressToLong("10.255.255.255");
Int64 bBegin = IpAddressToLong("172.16.0.0");
Int64 bEnd = IpAddressToLong("172.31.255.255");
Int64 cBegin = IpAddressToLong("192.168.0.0");
Int64 cEnd = IpAddressToLong("192.168.255.255");
Int64 ip = IpAddressToLong(ipAddress);
if (IsIPV4(ipAddress) && ( // 是正确的 IPV4 字符串表达形式。
(ip >= aBegin && ip <= aEnd) || // IP 在 10.0.0.0 与 10.255.255.255 之间。
(ip >= bBegin && ip <= bEnd) || // IP 在 172.16.0.0 与 172.31.255.255 之间。
(ip >= cBegin && ip <= cEnd)) // IP 在 192.168.0.0 与 192.168.255.255 之间。
)
{
return true;
}
return false;
}
#endregion
三、验证IP串是否为IP V4 格式
#region 判断指定字符串是否是 IP V4 格式。
/// <summary>
/// 判断指定字符串是否是 IP V4 格式。
/// </summary>
/// <param name="ipAddress">表示 IP V4 的字符串。</param>
/// <returns>
/// 如果是 IP V4 格式的字符串,则返回<c>true</c>;否则,返回<c>false</c>。
/// </returns>
public static Boolean IsIPV4(String ipAddress)
{
Regex regex = new Regex(@"(((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))\.){3}((\d{1,2})|(1\d{2})|(2[0-4]\d)|(25[0-5]))");
return !string.IsNullOrEmpty(ipAddress) && regex.IsMatch(ipAddress);
}
#endregion
浙公网安备 33010602011771号