Last active
December 21, 2016 06:45
-
-
Save azhai/5955280 to your computer and use it in GitHub Desktop.
Python判断是否中国大陆IP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
""" | |
需要存放IP段起止地址的二进制文件cnips.dat | |
""" | |
import os, os.path | |
from IPy import IP | |
def binary_search(total, callback, *args): | |
""" 二分(折半)查找算法 """ | |
step = total | |
offset = 0 | |
sign = 1 | |
while True: | |
step = (step + 1) / 2 | |
offset += sign * step | |
sign = callback(offset, *args) | |
if sign is 0 or step <= 1: | |
break | |
return sign is 0 | |
def compare_ip(offset, ip, fp): | |
fp.seek((offset - 1) * 8) | |
start_ip = fp.read(4) #读取之后0-4个字节 | |
end_ip = fp.read(4) #读取之后4-8个字节 | |
start_ip, end_ip = start_ip.encode('hex'), end_ip.encode('hex') | |
#指出下次偏移的方向 | |
if ip < start_ip: | |
return -1 | |
elif ip > end_ip: | |
return 1 | |
else: | |
return 0 #在IP段范围内(含两端) | |
def ip_in_china(ip_address): | |
#IP段数据文件,每个IP表示成一个8位hex整数,不足8位的前面补0 | |
datfile = 'cnips.dat' | |
total = os.stat(datfile).st_size / 8 #IP段总数 | |
#将要判断的IP转为8位hex整数 | |
ip = IP(ip_address).strHex()[2:] | |
fp = open(datfile, 'rb') | |
#比较IP并决定方向 | |
result = binary_search(total, compare_ip, ip, fp) | |
fp.close() | |
return result | |
if __name__ == "__main__": | |
for ip in ['49.114.165.195', '211.137.180.236', '175.223.16.46', '175.223.52.32', '219.74.86.136', '223.62.178.66', '223.33.184.117', '222.102.171.135', '113.162.202.32', '37.131.68.47', '178.77.154.240', '186.204.91.244', '119.139.14.70', '103.1.30.66', '192.168.102.42', '171.208.114.19', '27.42.26.56', '49.114.165.195', '211.137.180.236', '175.223.16.46', '175.223.52.32', '219.74.86.136', '223.62.178.66', '223.33.184.117', '222.102.171.135', '113.162.202.32', '37.131.68.47', '178.77.154.240', '186.123.135.229', '61.18.254.113', '210.91.142.47']: | |
print ip, int(ip_in_china(ip)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment