我们有请求。UserHostAddress在ASP. ASP. ASP中获取IP地址。NET,但这通常是用户的ISP的IP地址,而不是用户点击链接的机器IP地址。如何获取真实IP地址?
例如,在Stack Overflow用户配置文件中,它是:“上次帐户活动:4小时前从86.123.127.8开始”,但我的机器IP地址有点不同。Stack Overflow如何获得这个地址?
在一些web系统中,出于某些目的有一个IP地址检查。例如,对于某个IP地址,每24小时用户只能点击5次下载链接吗?这个IP地址应该是唯一的,而不是针对一个拥有大量客户端或互联网用户的ISP。
我听懂了吗?
就像别人说的,你不可能做到你所要求的。如果你描述一下你想要解决的问题也许有人可以帮你?
如。
您是否试图唯一地标识您的用户?
您是否可以使用cookie或会话ID来代替IP地址?
Edit The address you see on the server shouldn't be the ISP's address, as you say that would be a huge range. The address for a home user on broadband will be the address at their router, so every device inside the house will appear on the outside to be the same, but the router uses NAT to ensure that traffic is routed to each device correctly. For users accessing from an office environment the address may well be the same for all users. Sites that use IP address for ID run the risk of getting it very wrong - the examples you give are good ones and they often fail. For example my office is in the UK, the breakout point (where I "appear" to be on the internet) is in another country where our main IT facility is, so from my office my IP address appears to be not in the UK. For this reason I can't access UK only web content, such as the BBC iPlayer). At any given time there would be hundreds, or even thousands, of people at my company who appear to be accessing the web from the same IP address.
当你在写服务器代码时,你永远不能确定你看到的IP地址指的是什么。一些用户喜欢这种方式。有些人故意使用代理或VPN来进一步混淆你。
当你说你的机器地址与StackOverflow上显示的IP地址不同时,你是如何找到你的机器地址的?如果您只是使用ipconfig或类似的工具在本地查找,我希望由于我上面概述的原因它会有所不同。如果你想再次确认外界的看法,可以看看whatismyipaddress.com/。
这个关于NAT的维基百科链接将为您提供一些背景知识。
通常你会想知道访问你网站的人的IP地址。而ASP。NET有几种方法可以做到这一点,我们所见过的最好的方法之一是使用ServerVariables集合的“HTTP_X_FORWARDED_FOR”。
这是为什么…
有时,您的访问者位于代理服务器或路由器和标准请求的后面。UserHostAddress仅捕获代理服务器或路由器的IP地址。在这种情况下,用户的IP地址存储在服务器变量(“HTTP_X_FORWARDED_FOR”)中。
所以我们要做的是首先检查“HTTP_X_FORWARDED_FOR”,如果这是空的,我们然后简单地返回ServerVariables(“REMOTE_ADDR”)。
虽然这种方法不是万无一失的,但它可以带来更好的结果。下面是ASP。NET代码在VB。NET,摘自James Crowley的博客文章“Gotcha: HTTP_X_FORWARDED_FOR返回多个IP地址”
C#
protected string GetIPAddress()
{
System.Web.HttpContext context = System.Web.HttpContext.Current;
string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ipAddress))
{
string[] addresses = ipAddress.Split(',');
if (addresses.Length != 0)
{
return addresses[0];
}
}
return context.Request.ServerVariables["REMOTE_ADDR"];
}
VB。网
Public Shared Function GetIPAddress() As String
Dim context As System.Web.HttpContext = System.Web.HttpContext.Current
Dim sIPAddress As String = context.Request.ServerVariables("HTTP_X_FORWARDED_FOR")
If String.IsNullOrEmpty(sIPAddress) Then
Return context.Request.ServerVariables("REMOTE_ADDR")
Else
Dim ipArray As String() = sIPAddress.Split(New [Char]() {","c})
Return ipArray(0)
End If
End Function