2007年11月10日星期六

Get the visitor's IP address

http://www.developerfusion.co.uk/show/1626/
James Crowley

Whenever a browser sends a request for a page, it also sends a number of other headers to the script, containing information such as the browser type. It also includes information such as the visitors IP address. This can be particularly useful when creating an online security scan, or logging their IP address in an online forum.

There are two server variables of interest; REMOTE_ADDR and HTTP_X_FORWARDED_FOR. As many visitors access the internet via a third party (ie their ISP), REMOTE_ADDR does not always contain their IP address... it contains their ISP's address. If this is the case, most browsers then store the users IP address in the HTTP_X_FORWARDED_FOR variable. So, first, we check HTTP_X_FORWARDED_FOR, and then if that is empty, we try REMOTE_ADDR instead:

Dim sIPAddress

sIPAddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
If sIPAddress="" Then sIPAddress = Request.ServerVariables("REMOTE_ADDR")

One other thing worth bearing in mind. If the user also accesses the internet via a Proxy server, then HTTP_X_FORWARDED_FOR will contain the Proxy's IP address. If this is the case, there is no way to get the users 'real' IP address.


怎样得到访问者的IP地址,比如你想根据IP地址的不同为用户显示不同的内容或者做用户统计。这个量通常存储在ReMOTE_ADDR中,如果这里面没有数据,那么就在HTTP_X_FORWARDED_FOR中。

可以使用下面的函数得到IPAddress

Function IPAddress()
IPAddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
If IPAddress="" Then IPAddress = Request.ServerVariables("REMOTE_ADDR")
End Function

使用下面的函数隐藏最后一位

Function IPAddress2(IPAddress)
IF IsNull(IPAddress) Then
IPAddress2=""
Else
IPAddress2=Left(IPAddress,InStrRev(IPAddress,"."))&"*"
End IF
End Function

没有评论: