获取客户端IP地址
public string GetIPAddress()
{
string user_IP = string.Empty;
if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
{
if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
{
user_IP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
else
{
user_IP = System.Web.HttpContext.Current.Request.UserHostAddress;
}
}
else
{
user_IP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
if (user_IP == "::1" || user_IP == "127.0.0.1")
{
string strHostName = Dns.GetHostName();
IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
if (ipEntry.AddressList.Length > 0)
{
foreach (var item in ipEntry.AddressList)
{
if (IsIP(item.ToString()))
{
user_IP = item.ToString();
}
}
}
}
}
return user_IP;
}
检查IP地址格式
public static bool IsIP(string ip)
{
return System.Text.RegularExpressions.Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?).){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
}