#coding=utf8
from scapy.all import *

def dec2addr(dec):  
	"将十进制整数IP转换成点分十进制的字符串IP地址"  
	return ".".join([str(dec >> x & 0xff) for x in [24, 16, 8, 0]]) 

def ip2int(ip):
	return reduce(lambda x,y:(x<<8)+y,map(int,ip.split('.')))

def expand(line):
	ip = ip2int(line.split('/')[0])
	offset = 32-int(line.split('/')[1])
	stop = ip >> offset
	result = []
	while (ip>>offset) <= stop:
		result.append(dec2addr(ip))
		ip += 256
	return result

def isExternalIP(ip):
	try:
		ip = ip2int(ip)
	except:
		return False
	net_a = ip2int('10.255.255.255') >> 24
	net_b = ip2int('172.31.255.255') >> 20
	net_c = ip2int('192.168.255.255') >> 16
	return not (ip >> 24 == net_a or ip >>20 == net_b or ip >> 16 == net_c)

def getRouters(target):
	#target = [target]
	result, unans = traceroute(target,maxttl=32)
	ips = set([i[1].src for i in result])
	routers = filter(isExternalIP, ips)
	return routers
'''
with open('cn.zone', 'r') as f:
	data = f.read().split("\n")

with open('cn.expand', 'a') as fp:
	for i in data:
		fp.write('\n'.join(expand(i))+"\n")
'''
with open('cn.expand', 'r') as f:
	data = f.read().split("\n")


result = set()
for i in range(0, len(data), 1000):
	r = getRouters(data[i:i+1000])
	result.update(r)
	print r


'''
data = '\n'.join(result)

with open('out', 'w') as fw:
	fw.write(data)
'''
