原文链接: http://www.oschina.net/code/snippet_101424_6811
class ip2address{
ctor( path ){
ipData = ..io.open(path,"rb")
index = ipData.read({INT beginIndex;INT endIndex})
indexCount = (index.endIndex - index.beginIndex)/7 + 1
//自动关闭文件流
this._gc = ..gcdata(
_gc = function(){
ipData.close()
}
)
};
string2ip = function (str){
var ss = ..string.split(str,'.')
var ip = 0
for( i =1;#ss;1){
ip = (ip << 8) + tonumber(ss[ i ])
}
return ip;
}
find = function(ip,left,right){
if(right-left==1){
return left;
}
else {
var middle = ..math.floor((left + right)/2)
var offset = index.beginIndex + middle*7
ipData.seek("set",offset)
var newIp = ipData.read({INT buf}).buf
if(ip<=newIp){
return this.find(ip,left,middle);
}
else {
return this.find( ip,middle,right );
}
}
}
getLong3 = function (offset = 0){
if(offset){
ipData.seek("set",offset)
}
var str = ipData.read({WORD n;BYTE m})
return (str.m << 16) + str.n;
}
getString = function(offset = 0){
if(offset!=0){
ipData.seek("set",offset)
}
var str = ""
var ch = ipData.read(1)
var byte = ..string.unpack(ch)
while(byte!=0){
str = str + ch
ch = ipData.read(1)
byte = ..string.unpack(ch)
}
return str;
}
getAreaAddr = function(offset=0){
if(offset){
ipData.seek("set",offset)
}
var byte = ipData.read({BYTE byte}).byte
if(byte==0x01||byte==0x02){
var p = this.getLong3()
if(p)
return this.getString( p );
else
return "";
}
else {
return this.getString( offset )
}
}
getAddr = function (offset,ip=0){
ipData.seek("set",offset + 4)
var countryAddr = ""
var areaAddr = ""
var byte = ipData.read({BYTE b}).b
if(byte==0x01){
var countryOffset = this.getLong3()
ipData.seek("set",countryOffset)
var byte2 = ipData.read({BYTE b}).b
if(byte2==0x02){
countryAddr = this.getString( this.getLong3() )
ipData.seek("set",countryOffset + 4)
}
else {
countryAddr = this.getString( countryOffset )
}
areaAddr = this.getAreaAddr()
}
elseif(byte==0x02){
countryAddr = this.getString( this.getLong3() )
areaAddr = this.getAreaAddr( offset + 8 )
}
else {
countryAddr = this.getString( offset + 4 )
areaAddr = this.getAreaAddr( )
}
return countryAddr + "/" + areaAddr;
}
getIpAddr=function (ip){
var ip = this.string2ip(ip)
var aindex = this.find(ip,0,indexCount - 1)
var ioffset = (index.beginIndex) + aindex * 7
var aoffset = this.getLong3( ioffset + 4)
var address = this.getAddr( aoffset )
return address;
}
}
io.open()
ip = '123.123.123.123'
chunzhen = ip2address("D:\Program Files\cz88.net\ip\qqwry.dat")
io.print(chunzhen.getIpAddr(ip))
execute("pause")
io.close()
AAuto 纯真ip数据库读取源码
最新推荐文章于 2025-04-11 13:54:26 发布