在反向代理、CDN、負載平衡器 (Nginx/ALB/Cloudflare) 之後,`Request.ServerVariables("REMOTE_ADDR")` 只會拿到代理伺服器的 IP。必須解析 `X-Forwarded-For` (XFF) 標頭,並處理多層代理、IPv6、偽造標頭等邊界情況。
X-Forwarded-For: client, proxy1, proxy2
最左側為**原始客戶端 IP**,後續為經過的代理鏈。但:
unknownFunction GetClientIP()
Dim xff, ip, arr, i
xff = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
' 1. 無 XFF 或含 unknown → 退回 REMOTE_ADDR
If xff = "" Or InStr(LCase(xff), "unknown") > 0 Then
GetClientIP = Trim(Request.ServerVariables("REMOTE_ADDR"))
Exit Function
End If
' 2. 切分多層代理,取第一個合法 IPv4/IPv6
arr = Split(Replace(xff, ";", ","), ",")
For i = 0 To UBound(arr)
ip = Trim(arr(i))
' 簡易 IPv4 格式檢查 (生產環境建議用 RegExp)
If ip <> "" And IsValidIPv4(ip) Then
GetClientIP = Left(ip, 45) ' IPv6 最大 45 字元
Exit Function
End If
Next
' 3. 找不到合法 IP → 退回 REMOTE_ADDR
GetClientIP = Trim(Request.ServerVariables("REMOTE_ADDR"))
End Function
' 簡易 IPv4 驗證 (四段數字 0-255)
Function IsValidIPv4(ip)
Dim parts, p
If InStr(ip, ".") <> 3 Then IsValidIPv4 = False : Exit Function
parts = Split(ip, ".")
If UBound(parts) <> 3 Then IsValidIPv4 = False : Exit Function
For Each p In parts
If Not IsNumeric(p) Then IsValidIPv4 = False : Exit Function
If CInt(p) < 0 Or CInt(p) > 255 Then IsValidIPv4 = False : Exit Function
Next
IsValidIPv4 = True
End Function
'--- 使用範例 ---
Dim realIP
realIP = GetClientIP()
Response.Write "Client IP: " & realIP
僅信任已知代理 IP 範圍 (如 Cloudflare、自家 Nginx 節點) 送來的 XFF,忽略不明來源:
Function GetClientIPSecure()
Dim trustedProxies, remote, xff, arr, i, ip
trustedProxies = Array("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "103.21.244.0/22") ' Cloudflare IPv4 範例
remote = Request.ServerVariables("REMOTE_ADDR")
' 只有當直接連線來源在信任清單時,才解析 XFF
If Not IPInCIDRList(remote, trustedProxies) Then
GetClientIPSecure = remote
Exit Function
End If
xff = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
If xff = "" Then GetClientIPSecure = remote : Exit Function
arr = Split(Replace(xff, ";", ","), ",")
For i = 0 To UBound(arr)
ip = Trim(arr(i))
If IsValidIPv4(ip) Then
GetClientIPSecure = Left(ip, 45)
Exit Function
End If
Next
GetClientIPSecure = remote
End Function
' CIDR 比對函數略 (需將 IP 與網段轉長整數比對)
// Startup.cs
services.Configure(o => {
o.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
o.KnownNetworks.Clear();
o.KnownNetworks.Add(new IPNetwork(IPAddress.Parse("10.0.0.0"), 8)); // 信任內網代理
});
app.UseForwardedHeaders();
// Controller
var ip = HttpContext.Connection.RemoteIpAddress;
總結:舊 ASP 專案請部署GetClientIP()並配合 IIS 「IP 位址與網域限制」模組;新專案務必使用標準中介軟體UseForwardedHeaders搭配KnownNetworks白名單,切勿盲目信任 XFF。