要想透過代理服務器取得客戶端的真實IP地址,就要使用 Request.ServerVariables("HTTP_X_FORWARDED_FOR") 來讀取。不過要注意的事,並不是每個代理服務器都能用 Request.ServerVariables("HTTP_X_FORWARDED_FOR") 來讀取客戶端的真實 IP,有些用此方法讀取到的仍然是代理服務器的IP。還有一點需要注意的是:如果客戶端沒有通過代理服務器來訪問,那麼用 Request.ServerVariables ("HTTP_X_FORWARDED_FOR") 取到的值將是空的。因此,如果要在程序中使用此方法,可以這樣處理:
......
userip = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
If userip = "" Then userip = Request.ServerVariables("REMOTE_ADDR")
......
即:如果客戶端通過代理服務器,則取 HTTP_X_FORWARDED_FOR 的值,如果沒通過代理服務器,就取 REMOTE_ADDR 的值。
'通用函數:如果不能取客戶端真實IP,就會取客戶端的代理IP
Private Function getIP()
Dim strIPAddr
If Request.ServerVariables("HTTP_X_FORWARDED_FOR") = "" OR InStr(Request.ServerVariables("HTTP_X_FORWARDED_FOR"), "unknown") > 0 Then
strIPAddr = Request.ServerVariables("REMOTE_ADDR")
ElseIf InStr(Request.ServerVariables("HTTP_X_FORWARDED_FOR"), ",") > 0 Then
strIPAddr = Mid(Request.ServerVariables("HTTP_X_FORWARDED_FOR"), 1, InStr(Request.ServerVariables("HTTP_X_FORWARDED_FOR"), ",")-1)
ElseIf InStr(Request.ServerVariables("HTTP_X_FORWARDED_FOR"), ";") > 0 Then
strIPAddr = Mid(Request.ServerVariables("HTTP_X_FORWARDED_FOR"), 1, InStr(Request.ServerVariables("HTTP_X_FORWARDED_FOR"), ";")-1)
Else
strIPAddr = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
End If
getIP = Trim(Mid(strIPAddr, 1, 30))
End Function