您的位置:首页 > 编程语言 > ASP

asp.net取CDN用户真实IP的方法,仅供参考!

2010-07-09 09:04 531 查看
     转文者,请注明本文转自:http://zituo.blog.sohu.com 谢谢。

     以下是asp.net代码,一共用到两个方法。

    

    当用户没有使用代理时,能正常取出用户的IP地址。用户使用代理时,取出的是代理IP。

     相对于网上的其他方法,自己认为这个方法较为完善,当然可能您碰到的情况比我这更复杂,也可以在此基础上进行扩展。

    

     方法一:

      public static string GetIP()
        {
            //取CDN用户真实IP的方法
            //当用户使用代理时,取到的是代理IP
            string result = String.Empty;
            result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (!string.IsNullOrEmpty(result))
            {
                //可能有代理
                if (result.IndexOf(".") == -1)    
                    result = null;
                else
                {
                    if (result.IndexOf(",") != -1)
                    {
                        result = result.Replace(" ", "").Replace("'", "");
                        string[] temparyip = result.Split(",;".ToCharArray());
                        for (int i = 0; i < temparyip.Length; i++)
                        {
                            if (IsIP(temparyip[i]) && temparyip[i].Substring(0, 3) != "10." && temparyip[i].Substring(0, 7) != "192.168" && temparyip[i].Substring(0, 7) != "172.16.")
                            {
                                result = temparyip[i];
                            }
                        }
                        string[] str = result.Split(',');
                        if(str.Length>0)
                            result = str[0].ToString().Trim();
                    }
                    else if (Utils.IsIP(result))
                        return result;
                }
            }

            if (string.IsNullOrEmpty(result))
                result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            if (string.IsNullOrEmpty(result))
                result = HttpContext.Current.Request.UserHostAddress;
            if (string.IsNullOrEmpty(result))
                result = "127.0.0.1";

            return result;
        }

 

 

方法二:

        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?)$");
        }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  asp.net string 扩展 null