Skip to content

Instantly share code, notes, and snippets.

@huynhbaoan
Created April 21, 2025 11:25
Show Gist options
  • Save huynhbaoan/8e59ba597e6ce10cac2280aa213c97b5 to your computer and use it in GitHub Desktop.
Save huynhbaoan/8e59ba597e6ce10cac2280aa213c97b5 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import ipaddress, csv
# ◼ Adjust these file‐names/paths as needed
CIDR_FILE = 'cidrs.tsv'
IP_FILE = 'ips.txt'
OUTPUT_FILE = 'matched.tsv'
# 1) Load and parse your CIDRs
networks = []
with open(CIDR_FILE, newline='') as cf:
reader = csv.reader(cf, delimiter='\t')
for row in reader:
if not row or row[0].startswith('#'):
continue
provider, cidr_str, desc = row
network = ipaddress.ip_network(cidr_str)
networks.append((network, row))
# Sort so that more‐specific (longer) prefixes get matched first
networks.sort(key=lambda x: x[0].prefixlen, reverse=True)
# 2) Open the output TSV and start matching
with open(OUTPUT_FILE, 'w', newline='') as outf:
writer = csv.writer(outf, delimiter='\t')
# ← optional header
# writer.writerow(['IP','Provider','CIDR','Description'])
with open(IP_FILE) as ipf:
for line in ipf:
ip_str = line.strip()
if not ip_str:
continue
ip_addr = ipaddress.ip_address(ip_str)
matched_row = None
# find the first (most‐specific) network that contains this IP
for network, row in networks:
if ip_addr in network:
matched_row = row
break
# write out: IP + (the full TSV row from cidrs.tsv)
if matched_row:
writer.writerow([ip_str] + matched_row)
else:
# no match → just output the IP (or you can write blanks)
writer.writerow([ip_str])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment