Last active
December 28, 2021 09:57
-
-
Save snower/1ecc87c017838cb6a6b30812d9fee6e3 to your computer and use it in GitHub Desktop.
check_ip
This file contains 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 -*- | |
#14-6-6 | |
# create by: snower | |
import struct | |
from collections import defaultdict | |
import socket | |
default_networds = ( | |
"10.0.0.0/8", | |
"172.16.0.0/12", | |
"192.168.0.0/16" | |
) | |
networks = defaultdict(dict) | |
masks = [] | |
def load_networks(): | |
global networks, masks | |
networks, masks = defaultdict(dict), [] | |
try: | |
try: | |
with open("china_ip_list.txt") as fp: | |
for line in fp: | |
if "#" in line or not line.strip(): | |
continue | |
info = line.strip().split("/") | |
mask = int(info[1]) if len(info) >= 2 else 32 | |
try: | |
network = struct.unpack(">I", socket.inet_aton(info[0]))[0] >> (32 - mask) | |
except: | |
continue | |
networks[mask][network] = True | |
except: | |
pass | |
for line in default_networds: | |
info = line.strip().split("/") | |
mask = int(info[1]) if len(info) >= 2 else 32 | |
network = struct.unpack(">I", socket.inet_aton(info[0]))[0] >> (32 - mask) | |
networks[mask][network] = True | |
masks = sorted(networks.keys()) | |
for i in range(len(masks)): | |
for j in range(i + 1, len(masks)): | |
for network in networks[masks[j]]: | |
network = network >> (masks[j] - masks[i]) | |
if network in networks[masks[i]]: | |
continue | |
networks[masks[i]][network] = False | |
except Exception as e: | |
return | |
def check_ip(ip): | |
try: | |
ip = struct.unpack(">I", socket.inet_aton(ip))[0] | |
for mask in masks: | |
network = ip >> (32 - mask) | |
if network not in networks[mask]: | |
return False | |
if networks[mask][network]: | |
return True | |
except Exception as e: | |
return False | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment