using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// IPAddress 的摘要说明
/// </summary>
public static class IPAddress
{
public static string getIPAddress(bool isAll)
{
string result = string.Empty;
result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!isAll)
{
if (!string.IsNullOrEmpty(result))
{
//可能有代理
if (result.IndexOf(".") == -1)
{
//没有“.”肯定是非IPv4格式
result = string.Empty;
}
else
{
if (result.IndexOf(",") != -1)
{
//有“,”,估计多个代理。取第一个不是内网的IP。
result = result.Replace(" ", "").Replace("'", "");
string[] temparyip = result.Split(",;".ToCharArray());
for (int i = 0; i <= temparyip.Length - 1; i++)
{
if (IsIPAddress(temparyip[i]) && temparyip[i].Substring(0, 3) != "10." && temparyip[i].Substring(0, 7) != "192.168" && temparyip[i].Substring(0, 7) != "172.16.")
{
//找到不是内网的地址
return temparyip[i];
}
}
}
else if (IsIPAddress(result))
{
//代理即是IP格式
return result;
}
else
{
result = string.Empty;
//代理中的内容 非IP,取IP
}
}
}
}
if (string.IsNullOrEmpty(result))
{
result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
if (string.IsNullOrEmpty(result))
{
result = HttpContext.Current.Request.UserHostAddress;
}
if (IsIPAddress(result))
return result;
else
return null;
}
/// <summary>
/// 判断是否是IP地址格式 0.0.0.0
/// </summary>
/// <param name="str1">待判断的IP地址</param>
/// <returns>true or false</returns>
public static bool IsIPAddress(string str1)
{
if (String.IsNullOrEmpty(str1) || str1.Length < 7 || str1.Length > 15)
{
return false;
}
//string regformat = @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$";
//System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(regformat, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
//return regex.IsMatch(str1);
return System.Text.RegularExpressions.Regex.IsMatch(str1, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
}
public static string GetHostAddress()
{
string userHostAddress = HttpContext.Current.Request.UserHostAddress;
if (string.IsNullOrEmpty(userHostAddress))
{
userHostAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
//最后判断获取是否成功,并检查IP地址的格式(检查其格式非常重要)
if (!string.IsNullOrEmpty(userHostAddress) && IsIPAddress(userHostAddress))
{
return userHostAddress;
}
return "127.0.0.1";
}
}