需限制特定 IP 區段訪問 (如企業內網 10.0.0.0/16)?本文提供輕量級 ASP 函數,支援起始/結束 IP 任意區段判斷,邏輯清晰、無外部依賴。
<%
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)輕量、無依賴、邏輯可驗證,適合嵌入舊版 ASP 專案作存取控制基礎設施。