Asp限制IP存取阻止某一個IP段禁止存取本站的代碼
常常有些地方性的B2B或B2C網站到處都被大量發布好多垃圾訊息,把我的解決辦法分享給大家
代碼如下:
<%
''取得訪客的地址
ip=Request.ServerVariables(REMOTE_ADDR)
''允許的IP位址段為10.0.0.0~10.68.63.255
allowip1=10.0.0.0
allowip2=10.68.10.71
response.writecheckip(ip,allowip1,allowip2)
functioncheckip(ip,allowip1,allowip2)
dimcheck(4)
checkip=false
ipstr=split(ip,.)
allow1=split(allowip1,.)
allow2=split(allowip2,.)
ifcint(allow1(0))>cint(allow2(0))then''判斷IP位址段是否合法
response.write禁止訪問
exitfunction
endif
fori=0toubound(ipstr)
ifcint(allow1(i))<cint(allow2(i))then
ifcint(allow1(i))=cint(ipstr(i))then
check(i)=true
checkip=true
exitfor
else
ifcint(ipstr(i))<cint(allow2(i))then
check(i)=true
checkip=true
exitfor
else
ifcint(ipstr(i))>cint(allow2(i))then
check(i)=false
checkip=false
exitfor
else
check(i)=true
checkip=true
endif
endif
endif
else
ifcint(allow1(i))>cint(ipstr(i))orcint(allow1(i))<cint(ipstr(i))then
check(i)=false
checkip=false
ifi<>ubound(ipstr)then
exitfor
endif
else
check(i)=true
endif
endif
next
if(check(0)=trueandcheck(1)=trueandcheck(2)=trueandcheck(3)=false)and(cint(allow2(2))>cint(ipstr(2)))then
checkip=true
endif
endfunction
%>
把以下程式碼加入你的ASP頁面就可以測試到效果了:
複製代碼代碼如下:
<%
'受屏蔽IP位址(段)集合,星號為通配符,通常保存於設定檔中。
Const BadIPGroup = 192.168.1.*|202.68.*.*|*.12.55.34|185.*.96.24|127.*.0.1|192.168.0.1
If IsForbidIP(BadIPGroup) = True Then
Response.Write(GetIP &IP位址禁止存取)
Response.End()
End If
'參數vBadIP:要屏蔽的IP段,IP位址集合,用|符號分隔多個IP位址(段)
'回傳Bool:True用戶IP在被屏蔽範圍,False 反之
Function IsForbidIP(vBadIP)
Dim counter, arrIPPart, arrBadIP, arrBadIPPart, i, j
arrBadIP = Split(vBadIP, |)
arrIPPart = Split(GetIP(), .)
為 i = 0 To UBound(arrBadIP)
counter = 0
arrBadIPPart = Split(arrBadIP(i), .)
為 j = 0 To UBound(arrIPPart)
If(arrBadIPPart(j)) = * or Cstr(arrIPPart(j)) = Cstr(arrBadIPPart(j)) Then
counter = counter + 1
End If
Next
If counter = 4 Then
IsForbidIP = True
Exit Function
End If
Next
IsForbidIP = False
End Function
''返回客戶IP位址
Function GetIP()
Dim IP
IP = Request.ServerVariables(HTTP_X_FORWARDED_FOR)
If IP = Then IP = Request.ServerVariables(REMOTE_ADDR)
GetIP = IP
End Function
%>
這樣就可以限制網站存取的IP段了,你可以依照地區的IP段來設定。
我就是用這個方法防止外地用戶使用流氓軟體惡意到我網站發布資訊的!