因为ip库里的数据需要及时更新,一个更新的依据就是apnic上的ip地址划分,所以需要定期地从apnic上抓取所有中国区的ip,来保证ip库里的数据的时效性。
下面是用python写的两个小程序,用于从apnic抓取所有的中国区ip,第二个程序会将结果写入到ips.txt文件中:
程序一:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|
import os import re import urllib import socket import struct
def log2(x,pow=32): if x<=1: return pow pow-=1 return log2(x/2,pow)
def int2ip(intnum): return socket.inet_ntoa(struct.pack('I',socket.htonl(intnum)))
def ip2int(ip): return socket.ntohl(struct.unpack("I",socket.inet_aton(ip))[0])
def getchinaip(): f=urllib.urlopen("http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest") regular=re.compile(r'apnic\|CN\|ipv4\|') for line in f: if regular.search(line): iprange=line.split("|")[3:5] ip=iprange[0] cnt=int(iprange[1]) endip = int2ip(ip2int(ip)+cnt-1) mask=str(log2(cnt)) print ip+'/'+mask+','+ip+','+endip
if __name__ == '__main__': getchinaip()
|
程序二:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
|
import re import urllib
def test(): regularIpv4 = re.compile(r'apnic\|CN\|ipv4\|(.*)\|(.*)\|(.*)\|allocated')
with open("ips.txt", 'w') as f: for i in urllib.urlopen("http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest"): if regularIpv4.findall(i): """ sub(repl, string[, count]): 功能: 使用repl替换string中每一个匹配的子串后返回替换后的字符串。 当repl是一个方法时,这个方法应当只接受一个参数(Match对象, 并返回一个字符串用于替换(返回的字符串中不能再引用分组)。 count用于指定最多替换次数, 不指定时全部替换, 缺省值为1。
参考: http://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html """ result = regularIpv4.sub(func, i) f.write(result)
def func(m): """ 功能: sub函数第一个参数 repl, 用来返回一个字符串替换sub函数中的第二个参数 string
apnic|CN|ipv4|27.112.0.0|16384|20100702|allocated
m.group(1) 中存放的是 ip 地址 如上面的 27.112.0.0 m.group(2) 中存放的是 待处理的掩码数 如上面的 16384 """ return m.group(1) + "/" + str(32 - testlog2(m.group(2)))
def testlog2(num): """ 功能: 已知 b 且 2^x=b, 求其中的x 具体实现请参考: http://blog.csdn.net/hackbuteer1/article/details/6681157 """
num = int(num) x = 0 while num > 1: num >>= 1 x += 1 return x if __name__ == '__main__': test()
|
说明
本程序由好友▌March\╲,编写,在此分享给大家,供借鉴学习>_<
参考文档