萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP 程式設計

ASP 獲取客戶端真實 IP 地址:穿透代理與負載均衡的最佳實踐

ASP 中精準獲取真實客戶端 IP 的完整方案

由於代理服務器、負載均衡器、CDN 等中間層的存在,Request.ServerVariables("REMOTE_ADDR") 往往只能拿到代理 IP。本文提供穿透多層代理獲取真實 IP 的健壯實現。

核心原理

  • REMOTE_ADDR:TCP 連接直接來源 IP(最後一跳代理/客戶端)。
  • HTTP_X_FORWARDED_FOR:代理鏈傳遞的原始客戶端 IP 列表,格式 client, proxy1, proxy2...。
  • HTTP_CLIENT_IP:部分代理使用的非標準頭。

標準獲取函數

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

關鍵注意事項

  1. 不可盲信 HTTP_X_FORWARDED_FOR:客戶端可偽造,必須結合信任代理 IP 白名單驗證。
  2. 多層代理場景:Nginx/Apache 反向代理需配置 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 正確傳遞鏈路。
  3. CDN 環境:Cloudflare 等使用 CF-Connecting-IP 頭,需優先讀取。
  4. IPv6 支持:現代應用應擴展解析 IPv6 格式(含端口的方括號表示法)。

生產環境增強版

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。

copyright © 萬盛學電腦網 all rights reserved