通过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(), “.")
For i = 0 To UBound(arrBadIP)
counter = 0
arrBadIPPart = Split(arrBadIP(i), “.")
For 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段来设置.


也许下面的会对您有所帮助:

虚拟主机重要功能升级公告?
http://www.34514.cn/style/info/shownews.asp?id=298

易网主机防止论坛发帖机最有效的方法?
http://www.34514.cn/style/info/shownews.asp?id=250

彻底屏蔽网页木马代码?
http://www.34514.cn/style/info/shownews.asp?id=61