ASP.NET获取IP的方法

本文介绍了五种获取客户端IP地址的方法,包括直接通过请求对象获取、利用服务器变量、应对代理服务器情况等。每种方法都提供了具体的.NET代码实现,并针对代理服务器可能带来的问题进行了特别说明。

//方法一
HttpContext.Current.Request.UserHostAddress;

//方法二
HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

//方法三 (局域网)
string strHostName = System.Net.Dns.GetHostName();
string clientIPAddress = System.Net.Dns.GetHostAddresses(strHostName).GetValue(0).ToString();

//方法四(无视代理)
HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

//方法五
if(Context.Request.ServerVariables["HTTP_VIA"]!=null) // using proxy
{
     ip=Context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();  // Return real client IP.
}
else// not using proxy or can't get the Client IP
{
     ip=Context.Request.ServerVariables["REMOTE_ADDR"].ToString(); //While it can't get the Client IP, it will return proxy IP.
}

 

备注:

 

1. 有些代理是不会发给我们真实IP地址的

2. 有些客户端会因为“header_access deny”的安全设置而不发给我们IP

转载于:https://www.cnblogs.com/terer/articles/1833281.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值