Last active
February 27, 2024 15:57
-
-
Save leleobhz/4fe91dbe3c214040651242a4b6c35cd9 to your computer and use it in GitHub Desktop.
A little script to convert https://ftp.lacnic.net/pub/stats/lacnic/delegated-lacnic-latest to an IP address list
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
from requests import get | |
from io import StringIO | |
import pandas as pd | |
url = "https://ftp.lacnic.net/pub/stats/lacnic/delegated-lacnic-latest" | |
country = "br" | |
def nr_address_to_cidr(df): | |
if df['address_type'] == "ipv4": | |
mask = pow(2,32) | df['nr_address'] | |
elif df['address_type'] == "ipv6": | |
mask = pow(2,128) | df['nr_address'] | |
else: | |
return None | |
return CountTrailingZerosIgnoringFirstOne(mask) | |
def CountTrailingZerosIgnoringFirstOne(n): | |
bit = bin(n)[2:] | |
bit = bit[::-1] | |
zero = 0 | |
ignore = 1 | |
for i in range(len(bit)): | |
if (bit[i] == '0'): | |
if ignore == 0: | |
zero += 1 | |
# if '1' comes then break | |
else: | |
if ignore == 1: | |
ignore = 0 | |
else: | |
break | |
return zero + 1 | |
lacnic_data = ''.join(get(url).text.splitlines(keepends=True)[4:]) | |
df = pd.read_csv( | |
StringIO(lacnic_data), | |
names=["nic", "country", "address_type", "address", "nr_address","date", "status"], | |
header=None, | |
sep="|") | |
df['nr_address'] = pd.to_numeric(df['nr_address']) | |
# TODO: Write proper field creator. IPv4 needs to be calculated, IPv6 does not. | |
df[df['address_type'] == 'ipv4']['cidr'] = df[df['address_type'] == 'ipv4'].apply(nr_address_to_cidr, axis=1) | |
df[df['address_type'] == 'ipv6']['cidr'] = df[df['address_type'] == 'ipv6']['nr_address'] | |
''' | |
Selective output for example: All BR country of family ipv6 | |
''' | |
br_df = df[df['country'] == 'BR'] | |
for index, row in br_df[df['address_type'] == 'ipv6'].iterrows(): | |
try: | |
print(str(row['address']) + '/' + str('%.0d' % row['cidr']) ) | |
except: | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment