Skip to content

Commit

Permalink
Update china_ip.py, speed up with binary search
Browse files Browse the repository at this point in the history
  • Loading branch information
v3aqb committed Dec 11, 2014
1 parent 3ee10a7 commit 85ec928
Showing 1 changed file with 17 additions and 8 deletions.
25 changes: 17 additions & 8 deletions fqsocks/china_ip.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
import math
import os
import logging
import bisect

LOGGER = logging.getLogger(__name__)


def load_china_ip_ranges():
with open(os.path.join(os.path.dirname(__file__), 'china_ip.txt')) as f:
line = f.readline()
Expand All @@ -17,14 +19,14 @@ def load_china_ip_ranges():
continue
if 'CN|ipv4' not in line:
continue
# apnic|CN|ipv4|223.255.252.0|512|20110414|allocated
# apnic|CN|ipv4|223.255.252.0|512|20110414|allocated
_, _, _, start_ip, ip_count, _, _ = line.split('|')
start_ip_as_int = ip_to_int(start_ip)
end_ip_as_int = start_ip_as_int + int(ip_count)
yield start_ip_as_int, end_ip_as_int
line = f.readline()
yield translate_ip_range('111.0.0.0', 10) # china mobile
yield translate_ip_range('202.55.0.0', 19) # china telecom
yield translate_ip_range('111.0.0.0', 10) # china mobile
yield translate_ip_range('202.55.0.0', 19) # china telecom


def translate_ip_range(ip, netmask):
Expand All @@ -35,11 +37,18 @@ def ip_to_int(ip):
return struct.unpack('!i', socket.inet_aton(ip))[0]


CHINA_IP_RANGES = list(load_china_ip_ranges())
CHINA_IP_RANGES = sorted(list(load_china_ip_ranges()))
CHINA_IP_RANGES_I = [a for a, b in CHINA_IP_RANGES]


def is_china_ip(ip):
ip_as_int = ip_to_int(ip)
for start_ip_as_int, end_ip_as_int in CHINA_IP_RANGES:
if start_ip_as_int <= ip_as_int <= end_ip_as_int:
return True
return False
index = bisect.bisect(CHINA_IP_RANGES_I, ip_as_int) - 1
start_ip_as_int, end_ip_as_int = CHINA_IP_RANGES[index]
if start_ip_as_int <= ip_as_int <= end_ip_as_int:
return True
return False

if __name__ == '__main__':
print is_china_ip('101.226.200.226')
print is_china_ip('74.125.224.100')

0 comments on commit 85ec928

Please sign in to comment.