标签:
ASP.NET获取用户端的真实IP在各种场景都能用到,但是用户网端变幻莫测情况众多,获取真实IP还真是不容易啊。
下面分享个比较好一点的方法:
/// <summary> /// 获得当前页面客户端的IP /// Author:codeo.cn /// </summary> /// <returns>当前页面客户端的IP</returns> public static string GetIP() { string result = String.Empty; result = HttpContext.Current.Request.ServerVariables["HTTP_CDN_SRC_IP"]; if (string.IsNullOrEmpty(result)) result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; if (string.IsNullOrEmpty(result)) result = HttpContext.Current.Request.UserHostAddress; if (string.IsNullOrEmpty(result) || !Utils.IsIP(result)) return "127.0.0.1"; return result; } /// <summary> /// 是否为ip /// Author:codeo.cn /// </summary> /// <param name="ip"></param> /// <returns></returns> public static bool IsIP(string ip) { return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$"); }
/// <summary> /// 取得客户端真实IP。如果有代理则取第一个非内网地址 /// Author:codeo.cn /// </summary> /// <returns></returns> public static string GetIPAddress() { string strresult = string.Empty; strresult = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (strresult != null && strresult != string.Empty) { //可能有代理 if (strresult.IndexOf(".") == -1) //没有“.”肯定是非IPv4格式 { strresult = null; } else { if (strresult.IndexOf(".") != -1) { //有“,”,估计多个代理。取第一个不是内网的IP。 strresult = strresult.Replace(" ", "").Replace("‘", ""); string[] strarrtemparyip = strresult.Split(",;".ToCharArray()); for (int i = 0; i < strarrtemparyip.Length; i++) { if (IsIPAddress(strarrtemparyip[i]) && strarrtemparyip[i].Substring(0, 3) != "10." && strarrtemparyip[i].Substring(0, 7) != "192.168" && strarrtemparyip[i].Substring(0, 7) != "172.16.") { return strarrtemparyip[i]; //找到不是内网的地址 } } } else if (IsIPAddress(strresult)) //代理即是IP格式 { return strresult; } else { strresult = null; //代理中的内容 非IP,取IP } } } string strIpAddress = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null && HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != string.Empty ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]); if (null == strresult || strresult == string.Empty) { strresult = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; } if (strresult == null || strresult == string.Empty) { strresult = HttpContext.Current.Request.UserHostAddress; } return strresult; } /// <summary> /// 判断是否是IP地址格式 0.0.0.0 /// Author:codeo.cn /// </summary> /// <param name="strIp">待判断的IP地址</param> /// <returns>true or false</returns> private static bool IsIPAddress(string strIp) { if (strIp == null || strIp == string.Empty || strIp.Length < 7 || strIp.Length > 15) { return false; } string strRegformat = @"^d{1,3}[.]d{1,3}[.]d{1,3}[.]d{1,3}___FCKpd___0quot"; Regex regex = new Regex(strRegformat, RegexOptions.IgnoreCase); return regex.IsMatch(strIp); }
标签:
原文地址:http://www.cnblogs.com/huhangfei/p/4989060.html