获取客户端用户真实ip

来源:互联网 发布:淘宝几天售后 编辑:程序博客网 时间:2024/05/19 14:01

          通常通过Request.ServerVariables("REMOTE_ADDR") 或 Request.UserHostAddress 来获取客户端ip。如果在客户端使用了代理服务器或在服务器前加了反向代理服务器,获取的就是代理服务器的地址了,无法获取用户真实ip。怎么获取呢?

 

        public static string RemoteIp()
        {
                string realRemoteIP = "";
                if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
                {
                    realRemoteIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].Split(',')[0];
                }
                if (string.IsNullOrEmpty(realRemoteIP))
                {
                    realRemoteIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                }
                return realRemoteIP;
      }

   为什么用上述方法可以呢?因为很多代理会自动在HTTP_X_FORWARDED_FOR字段信息中加入对方最后一层TCP/IP信息。

所以使用该方法的前提是,要自动把ip信息加入到HTTP_X_FORWARDED_FOR字段中,否则用该方法仍然是获取不到的。

     顺便贴个获取服务器自身ip的方法吧!如下:


    public static string HostIp()
        {
             return HttpContext.Current.Request.ServerVariables["LOCAL_ADDR"];
        }

 

 

原创粉丝点击