Created
July 21, 2021 05:03
-
-
Save illuzian/24e58f79994d033d01e9aa99eb1936cf to your computer and use it in GitHub Desktop.
Moderately Efficient ASN/Org Lookup by 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
import csv | |
import ipaddress | |
database = {} | |
with open('GeoLite2-ASN-Blocks-IPv4.csv') as csvfile: | |
reader = csv.DictReader(csvfile) | |
for row in reader: | |
ip_net = ipaddress.IPv4Interface(row['network']) | |
database[ip_net] = {} | |
database[ip_net]['autonomous_system_organization'] = row['autonomous_system_organization'] | |
database[ip_net]['autonomous_system_number'] = row['autonomous_system_number'] | |
# The returned network (i) is the key to databse. The provided ip is checked to see if it is within the subnet. | |
def get_net_key(ip, db): | |
as_list = list(db.keys()) | |
ip_as_ip = ipaddress.IPv4Network(ip, strict=False) | |
for i in as_list: | |
if ip_as_ip.subnet_of(i.network): | |
return i | |
raise ValueError | |
nkey = get_net_key('1.1.1.1', database) | |
print(database[nkey]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment