Python – ARIN Whois

# Author: Kerry Cordero
# Version: 1.0.0
# Description: This script prompt for the ASN and output the IP Subnet blocks associated with that ASN.

import re
import socket

def query_arin(asn):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect(("whois.radb.net", 43))

    # The '-i origin' flag requests routes originating from the ASN
    sock.send(f"-i origin {asn}\n".encode())

    response = b""
    while True:
        data = sock.recv(4096)
        response += data
        if not data:
            break
    sock.close()
    
    return response.decode()

def parse_subnets(response):
    # Extract subnets using regular expression and remove duplicates by turning the list into a set
    return list(set(re.findall(r"route:\s+([0-9\.\/]+)", response)))

def main():
    asn = input("Please enter the ASN: ")
    response = query_arin(asn)
    subnets = parse_subnets(response)
    print(f"The subnets for ASN {asn} are:")
    for subnet in subnets:
        print(subnet)

if __name__ == "__main__":
    main()