用asp判断某IP是否属于某网段的另类算法 - asp语言 -

用asp判断某IP是否属于某网段的另类算法

时间:2013-04-02 16:53:23   来源:   评论:加载中...   点击:加载中...
有时候我们需要判断某一个IP地址是否属于一个网段,以决定该用户能否访...

Function check_ip(UserIp,NetIP)
currentip=UserIp
collection_ips=split(iplist,",") '将网络按点分割成4段
check_ip=false '初始函数值,false假设IP不在这网段
NetIP=trim(NetIP)
slashPos=inStr(NetIP,"/")
if slashPos=0 then '网段没含有/符号,他只是一个IP,所以比较比个字符串是否相同就可以了
if NetIP=currentip then
check_ip=true 'check_ip=true表示IP相等
exit function
end if
else
netRang=mid(NetIP,slashPos+1) '得到/后边的数字
if not isNumeric(netRang) then '/后边不是数字,格式不正确
exit function
end if
netRang=cint(netRang) '将字符转为数字
if netRang>31 then
exit function '/后的数字不能超过32位
end if
ipsets=split(currentip,".") '将用户IP按点分成四段

C_IP_BIN=pad(dec2bin(ipsets(0))) & pad(dec2bin(ipsets(1))) & pad(dec2bin(ipsets(2))) & pad(dec2bin(ipsets(3)))
'上边这行是将用户IP地址手工转换为对应的一个32个字符长的二进制
ipsets=split(NetIP,".") '按上边的过程将网段IP同样转为32个字符长的二进制
sPos=instr(ipsets(3),"/") '最后一点格式应该是 数字/数字
if sPos=0 then
exit function
end if
ipsets(3)=left(ipsets(3),sPos-1) '得到最后一段/前边的数字
S_IP_BIN=pad(dec2bin(ipsets(0))) & pad(dec2bin(ipsets(1))) & pad(dec2bin(ipsets(2))) & pad(dec2bin(ipsets(3)))
'将其转换为32个字符长的二进制
if left(C_IP_BIN,netRang) = left(S_IP_BIN,netRang) then '比较网段络是否相同就可以判断用户IP否属于某个网段了
check_ip=true
end if
end if
end function

应用举例:

要判断61.139.1.1是否在61.139.0.0/16 (255.255.0.0)这个网段
只需要简单的使用这个函数就可以了,如:

if check_ip("61.139.1.1","61.139.0.0/16") then
Response.write "同一网段"
else
Response.write "不是同一网段"
end if



相关热词搜索:

 
上一篇:源码实例:ASP实现远程保存图片
下一篇:用ASP+DLL实现WEB方式修改服务器时间
收藏 将此文推荐给朋友
分享到: