asp屏蔽IP黑名单访问
<%
' IP黑名单
Call CheckIP(Request.ServerVariables("REMOTE_ADDR"), GetBlockedIPs())
' 增强版IP检查(支持CIDR)
Function CheckIP(clientIP, ipList)
Dim ip, range, startIP, endIP, block, ipParts, rangeParts
Dim comment, displayMsg
For Each block In ipList
' 解析注释分隔符(支持#、//、|三种分隔符)
If InStr(block, "#") > 0 Then
ip = Split(block, "#")(0)
comment = Trim(Split(block, "#")(1))
ElseIf InStr(block, "//") > 0 Then
ip = Split(block, "//")(0)
comment = Trim(Split(block, "//")(1))
ElseIf InStr(block, "|") > 0 Then
ip = Split(block, "|")(0)
comment = Trim(Split(block, "|")(1))
Else
ip = trim(block)
comment = "Blocked IP"
End If
block=ip
If InStr(block, "-") > 0 Then
' 处理IP范围
startIP = Split(block, "-")(0)
endIP = Split(block, "-")(1)
If IPToLong(clientIP) >= IPToLong(startIP) And IPToLong(clientIP) <= IPToLong(endIP) Then
'Response.write comment
Response.Status = "403 Forbidden"
Response.End
End If
ElseIf InStr(block, "/") > 0 Then
' 处理CIDR表示法
rangeParts = Split(block, "/")
ip = rangeParts(0)
range = CInt(rangeParts(1))
startIP = IPToLong(ip)
endIP = startIP + (2 ^ (32 - range)) - 1
If IPToLong(clientIP) >= startIP And IPToLong(clientIP) <= endIP Then
'Response.write comment
Response.Status = "403 Forbidden"
Response.End
End If
Else
' 精确IP匹配
If clientIP = block Then
'Response.write comment
Response.Status = "403 Forbidden"
Response.End
End If
End If
Next
End Function
' 辅助函数:将IP转换为长整型
Function IPToLong(ip)
Dim parts, i, result
parts = Split(ip, ".")
result = 0
For i = 0 To 3
result = result * 256 + CInt(parts(i))
Next
IPToLong = result
End Function
Function GetBlockedIPs()
Dim fs, filePath, file, content, line, lines, blockedIPs
Set fs = Server.CreateObject("Scripting.FileSystemObject")
filePath = Server.MapPath(".")&"\#ip_blacklist.txt"
Set file = fs.OpenTextFile(filePath, 1)
content = file.ReadAll
file.Close
lines = Split(content, vbCrLf)
blockedIPs = Array()
For Each line In lines
line = Trim(line)
If Left(line, 1) <> "#" And line <> "" Then
ReDim Preserve blockedIPs(UBound(blockedIPs) + 1)
blockedIPs(UBound(blockedIPs)) = line
End If
Next
GetBlockedIPs = blockedIPs
End Function
%>黑名单格式
# IP黑名单 # 支持精确IP匹配 # 支持IP范围匹配(192.168.1.0-192.168.1.255) # 支持CIDR表示法(192.168.1.0/24) # 支持备注(192.168.0.1 #局域网) 17.0.0.1#精确匹配 192.168.0.0-192.168.255.255 #区间匹配 192.168.0.0/16
