APS.NET获取用户端真实IP

asp.net的request自带一个获取用户端ip的属性 request.userhostaddress,但通过userhostaddress获取的ip地址并不能保证真实、准确,并且上客户端使用了代理怎么办?

                if (request.servervariables["remote_addr"] != null)//发出请求的远程主机的ip地址
        {
                    this.ipaddress = request.servervariables["remote_addr"].tostring();
                }
                else if (request.servervariables["http_via"] != null)//判断是否设置代理,若使用了代理
        {
                    if (request.servervariables["http_x_forwarded_for"] != null)//获取代理服务器的ip
                    {
                        this.ipaddress = request.servervariables["http_x_forwarded_for"].tostring();
                    }
                    else
                    {
                        this.ipaddress = request.userhostaddress;
                    }
                }
                else
                {
                    this.ipaddress = request.userhostaddress;
                }
使用上述代码,可以保证准确的获取到客户端ip地址。

 

posted on 2009-11-04 11:07  周奇  阅读(626)  评论(0编辑  收藏  举报