页面增加CDN缓存后获取用户真实IP

页面增加CDN缓存后获取用户真实IP

 public string GetUserIp()
       {
           string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
           if (string.IsNullOrEmpty(ip) || ip.ToLower().IndexOf("unknown", System.StringComparison.Ordinal) > -1)
           {
               ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
           }
           else
           {
               if (ip.IndexOf(',') > -1)
               {
                   ip = ip.Substring(0, ip.IndexOf(','));
               }
               if (ip.IndexOf(';') > -1)
               {
                   ip = ip.Substring(0, ip.IndexOf(';'));
               }
           }

           Regex regex = new Regex("[^0-9.]");
           if (string.IsNullOrEmpty(ip) || regex.IsMatch(ip))
           {
               ip = HttpContext.Current.Request.UserHostAddress;
               if (ip == null || ip.Length == 0 || regex.IsMatch(ip))
               {
                   ip = "0.0.0.0";
               }
           }
           return ip;
       }

 

posted @ 2013-02-26 14:48  百里水上  阅读(305)  评论(0编辑  收藏  举报