然而纯真数据库是由网友反馈所提供的,很多数据描述并不准确,所以我上网找了一些其他的ip数据库,最后就找到了 ipip.net 这个网站所提供的ip数据库。
ipip所提供的数据库有付费和免费两个版本,我们可以直接使用其中的免费版本。
下载地址 https://www.ipip.net/download.html (需要先注册一个帐号)
压缩包内有一个php的解析类,还有一个 17monipdb.dat 文件就是数据库了,我们只需要用到它就可以了。
将 17monipdb.dat 复制到程序的主目录,使用下面的代码:
imports system.io imports system.text public class ipip shared offset as integer shared index as uinteger() = new uinteger(255) {} shared databuffer as byte() shared indexbuffer as byte() shared lastmodifytime as long = 0l shared ipfile as string shared rwlock as new threading.readerwriterlock shared sub new() load("17monipdb.dat") end sub shared sub load(byval filename as string) ipfile = new fileinfo(filename).fullname load() end sub shared sub load() rwlock.acquirewriterlock(-1) dim fi as new fileinfo(ipfile) lastmodifytime = fi.lastwritetime.ticks try databuffer = file.readallbytes(fi.fullname) dim indexlength = bytestolong(databuffer(0), databuffer(1), databuffer(2), databuffer(3)) indexbuffer = new byte(indexlength - 1) {} array.copy(databuffer, 4, indexbuffer, 0, indexlength) offset = ctype(indexlength, integer) for lp as integer = 0 to 255 index(lp) = bytestolong( _ indexbuffer(lp * 4 + 3), _ indexbuffer(lp * 4 + 2), _ indexbuffer(lp * 4 + 1), _ indexbuffer(lp * 4) _ ) next catch ex as exception throw ex end try rwlock.releasewriterlock() end sub private shared function bytestolong(byval a as byte, byval b as byte, byval c as byte, byval d as byte) as uinteger return (ctype(a, uinteger) << 24) or (ctype(b, uinteger) << 16) or (ctype(c, uinteger) << 8) or d end function shared function find(byval ip as string) as string() rwlock.acquirereaderlock(-1) dim ips = ip.split(".") dim ip_prefix_value = integer.parse(ips(0)) dim ip2long_value as long = bytestolong(byte.parse(ips(0)), byte.parse(ips(1)), byte.parse(ips(2)), byte.parse(ips(3))) dim start = index(ip_prefix_value) dim max_comp_len = offset - 1028 dim index_offset as long = -1l dim index_length as integer = -1 dim b as byte = 0 start = start * 8 + 1024 while start < max_comp_len if bytestolong(indexbuffer(start + 0), indexbuffer(start + 1), indexbuffer(start + 2), indexbuffer(start + 3)) >= ip2long_value then index_offset = bytestolong(b, indexbuffer(start + 6), indexbuffer(start + 5), indexbuffer(start + 4)) index_length = &hff and indexbuffer(start + 7) exit while end if start += 8 end while dim areabytes = new byte(index_length - 1) {} array.copy(databuffer, offset + index_offset - 1024, areabytes, 0, index_length) dim ret as string() = encoding.utf8.getstring(areabytes).split(vbtab) rwlock.releasereaderlock() return ret end function end class
此代码是我从官方提供的c#版本翻译过来的,并且去除了一些冗余代码,只留下核心功能。
未经过完全的测试,有bug请反馈给我。
使用方法很简单:
dim ret = ipip.find("127.0.0.1" ' 用换行分隔所有信息 dim ipdesc = string.join(vbcrlf, ret)
以上就是通过ipip.net实现数据库来查询ip地址的实例的详细内容。
