代码改变世界

IP解析

2013-08-23 14:40  ATP_  阅读(603)  评论(1编辑  收藏  举报
 1 import sys,re
 2 
 3 ip_1_stat = {}
 4 source_fp = open("ip_region","r")
 5 p = re.compile("(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})")
 6 for line in source_fp:
 7     line = line.strip()
 8     list = line.split('|')
 9 
10     start = p.match(list[0].strip())
11     end = p.match(list[1].strip()[:-3])
12     region = list[2].strip()
13 
14     if start and end:
15         key = start.group(1)
16         if key not in ip_1_stat:
17             ip_1_stat[key] = {"line":{}}
18         if line not in ip_1_stat[key]["line"]:
19             ip_1_stat[key]["line"][line] = {"s2":int(start.group(2)), "s3":int(start.group(3)), "s4":int(start.group(4)), "e2":int(end.group(2)), "e3":int(end.group(3)), "e4":int(end.group(4)), "prov":region}
20 source_fp.close()
21 
22 #ip index
23 index = sys.argv[1]
24 
25 for line in sys.stdin:
26     line = line.strip()
27     list = line.split('\t')
28 
29     ip = list[index].strip()
30     #ip = list[2].strip()
31     match = p.match(ip)
32     i1 = match.group(1)
33     i2 = int(match.group(2))
34     i3 = int(match.group(3))
35     i4 = int(match.group(4))
36     prov = "NotFound"
37 
38     key = i1
39     if key not in ip_1_stat:
40         continue
41 
42     flag = 0
43     #ergodic
44     for l in ip_1_stat[key]["line"]:
45         #start
46         if i2 > ip_1_stat[key]["line"][l]["s2"]:
47             flag = 1
48         elif i2 == ip_1_stat[key]["line"][l]["s2"]:
49             if i3 > ip_1_stat[key]["line"][l]["s3"]:
50                 flag = 1
51             elif i3 == ip_1_stat[key]["line"][l]["s3"]:
52                 if i4 >= ip_1_stat[key]["line"][l]["s4"]:
53                     flag = 1
54         #flag 
55         if flag == 0:
56             continue
57 
58         #end
59         if i2 < ip_1_stat[key]["line"][l]["e2"]:
60             flag = ip_1_stat[key]["line"][l]["prov"]
61         elif i2 == ip_1_stat[key]["line"][l]["e2"]:
62             if i3 < ip_1_stat[key]["line"][l]["e3"]:
63                 flag = ip_1_stat[key]["line"][l]["prov"]
64             elif i3 == ip_1_stat[key]["line"][l]["e3"]:
65                 if i4 <= ip_1_stat[key]["line"][l]["e4"]:
66                     flag = ip_1_stat[key]["line"][l]["prov"]
67         if flag != 1:
68             break
69                 
70 
71     print "%s\t%s" % (line, flag)