萬盛學電腦網

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

ASP IP 區段過濾限制函數:支援 CIDR 風格範圍判斷

需限制特定 IP 區段訪問 (如企業內網 10.0.0.0/16)?本文提供輕量級 ASP 函數,支援起始/結束 IP 任意區段判斷,邏輯清晰、無外部依賴。

核心函數:CheckIP

<%
Function CheckIP(clientIP, allowStartIP, allowEndIP)
    Dim clientParts, startParts, endParts, i
    Dim startVal, endVal, clientVal
    
    CheckIP = False
    
    ' 分割四段
    clientParts = Split(clientIP, ".")
    startParts = Split(allowStartIP, ".")
    endParts = Split(allowEndIP, ".")
    
    ' 基本合法性檢查
    If UBound(clientParts) <> 3 Or UBound(startParts) <> 3 Or UBound(endParts) <> 3 Then
        Exit Function
    End If
    
    ' 逐段比較
    For i = 0 To 3
        clientVal = CInt(clientParts(i))
        startVal = CInt(startParts(i))
        endVal = CInt(endParts(i))
        
        ' 起始 > 結束,區段定義錯誤
        If startVal > endVal Then
            Exit Function
        End If
        
        If clientVal < startVal Or clientVal > endVal Then
            ' 當前段超出範圍,直接判定不通過
            Exit Function
        ElseIf clientVal > startVal And clientVal < endVal Then
            ' 當前段在範圍內部,後續段無需比較,直接通過
            CheckIP = True
            Exit Function
        End If
        ' 當前段等於邊界,繼續比較下一段
    Next
    
    ' 四段全等於邊界,視為通過
    CheckIP = True
End Function
%>

使用範例

<%
Dim visitorIP, allowedStart, allowedEnd
visitorIP = Request.ServerVariables("REMOTE_ADDR")

' 允許 10.0.0.0 ~ 10.68.255.255 (相當於 10.0.0.0/16)
allowedStart = "10.0.0.0"
allowedEnd   = "10.68.255.255"

If CheckIP(visitorIP, allowedStart, allowedEnd) Then
    Response.Write "允許訪問"
Else
    Response.Write "IP 不在允許範圍內:" & visitorIP
    Response.End
End If
%>

邏輯解析

採用字典序比較:將 IP 視為四元組 (a,b,c,d),從高位到低位逐段比較:

  • 客戶段 < 起始段 → ❌ 拒絕
  • 客戶段 > 結束段 → ❌ 拒絕
  • 起始段 < 客戶段 < 結束段 → ✅ 通過 (後段任意)
  • 客戶段 = 邊界值 → 繼續比較下一段

擴展:支援多區段白名單

Function CheckIPMulti(clientIP, allowRanges)
    ' allowRanges 格式:"10.0.0.0-10.68.255.255|192.168.1.1-192.168.1.254"
    Dim ranges, i, rangeParts
    ranges = Split(allowRanges, "|")
    For i = 0 To UBound(ranges)
        rangeParts = Split(ranges(i), "-")
        If UBound(rangeParts) = 1 Then
            If CheckIP(clientIP, rangeParts(0), rangeParts(1)) Then
                CheckIPMulti = True
                Exit Function
            End If
        End If
    Next
    CheckIPMulti = False
End Function

生產環境建議

  • 結合 HTTP_X_FORWARDED_FOR 獲取真實客戶端 IP (參考文章 66764)
  • 白名單配置外置至資料庫/配置檔,避免硬編碼
  • 記錄被拒訪問日誌,便於安全審計
  • 考慮 IPv6 相容性 (本函數僅支援 IPv4)

輕量、無依賴、邏輯可驗證,適合嵌入舊版 ASP 專案作存取控制基礎設施。

copyright © 萬盛學電腦網 all rights reserved