由於代理服務器、負載均衡器、CDN 等中間層的存在,Request.ServerVariables("REMOTE_ADDR") 往往只能拿到代理 IP。本文提供穿透多層代理獲取真實 IP 的健壯實現。
client, proxy1, proxy2...。Function GetRealIP()
Dim ip, forwarded
forwarded = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
If forwarded <> "" Then
' 取第一個非私有 IP(客戶端真實 IP)
Dim ips, i, candidate
ips = Split(forwarded, ",")
For i = 0 To UBound(ips)
candidate = Trim(ips(i))
If IsPublicIP(candidate) Then
ip = candidate
Exit For
End If
Next
End If
If ip = "" Then ip = Request.ServerVariables("REMOTE_ADDR")
If ip = "" Then ip = Request.ServerVariables("HTTP_CLIENT_IP")
GetRealIP = ip
End Function
Function IsPublicIP(ip)
' 簡易私有 IP 段過濾:10.x, 172.16-31.x, 192.168.x, 127.x, 169.254.x
Dim parts : parts = Split(ip, ".")
If UBound(parts) <> 3 Then Exit Function
Dim first : first = CInt(parts(0))
Dim second : second = CInt(parts(1))
If first = 10 Then Exit Function
If first = 127 Then Exit Function
If first = 169 And second = 254 Then Exit Function
If first = 172 And second >= 16 And second <= 31 Then Exit Function
If first = 192 And second = 168 Then Exit Function
IsPublicIP = True
End Function
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 正確傳遞鏈路。CF-Connecting-IP 頭,需優先讀取。Function GetClientIP()
Dim trustedProxies, ip, header
trustedProxies = Array("10.0.0.1", "192.168.1.100") ' 信任的反向代理 IP
' 1. 檢查是否來自信任代理
Dim remoteIP : remoteIP = Request.ServerVariables("REMOTE_ADDR")
Dim isTrustedProxy : isTrustedProxy = False
For Each ip In trustedProxies
If ip = remoteIP Then isTrustedProxy = True : Exit For
Next
' 2. 信任代理時讀取 X-Forwarded-For 首個公網 IP
If isTrustedProxy Then
header = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
If header <> "" Then
Dim ips : ips = Split(header, ",")
For Each ip In ips
ip = Trim(ip)
If IsPublicIP(ip) Then GetClientIP = ip : Exit Function
Next
End If
End If
' 3. 回退鏈
header = Request.ServerVariables("HTTP_CLIENT_IP")
If header <> "" And IsPublicIP(header) Then GetClientIP = header : Exit Function
GetClientIP = remoteIP
End Function
將此函數集成至公共庫,所有業務邏輯統一調用 GetClientIP(),即可在複雜網絡拓撲下穩定獲取真實客戶端 IP。