获取用户ip

/// <summary>
        /// 获取客户端IP地址,优先取得代理IP,没有代理IP则直接取客户端IP
        /// </summary>
        /// <returns></returns>
        public static string GetRealUserHostAddress()
        {
            string ip = "";
            try
            {
                if (HttpContext.Current.Request.Headers["ZZReader-X-Forwarded-For"] == null)
                {
                    //优先取得代理IP
                    ip = HttpContext.Current.Request.UserHostAddress;
                }
                else
                {
                    //没有代理IP则直接取客户端IP
                    string tempStr = HttpContext.Current.Request.Headers["ZZReader-X-Forwarded-For"].ToString().Split(',')[0].Trim();
                    if (tempStr.IndexOf(":") == -1)
                    {
                        ip = tempStr;
                    }
                    else
                    {
                        ip = tempStr.Substring(0, tempStr.IndexOf(":"));
                    }
                }
            }
            catch
            {
                ip = "";
            }

            return ip;
        }

 

posted @ 2013-07-01 15:12  梦醒心晴  Views(275)  Comments(0)    收藏  举报