Skip to content

Instantly share code, notes, and snippets.

@elliotwutingfeng
Last active June 3, 2023 22:25
Show Gist options
  • Save elliotwutingfeng/b960c3068f9d8f5fcdb3b91b70adb726 to your computer and use it in GitHub Desktop.
Save elliotwutingfeng/b960c3068f9d8f5fcdb3b91b70adb726 to your computer and use it in GitHub Desktop.
How many unique AWS EC2 IPv4 Addresses are there?
import ipaddress
import json
from collections import defaultdict
from itertools import chain
from urllib.request import urlopen
with urlopen("https://ip-ranges.amazonaws.com/ip-ranges.json") as req:
resp_json = json.loads(req.read())
ip_prefixes_and_regions = (
(x["ip_prefix"], x["region"])
for x in resp_json["prefixes"]
if x["service"].upper() == "EC2"
)
region_to_ip_ranges_map = defaultdict(list)
for ip_prefix, region in ip_prefixes_and_regions:
region_to_ip_ranges_map[region].append(ip_prefix)
regions, ip_ranges = zip(*region_to_ip_ranges_map.items())
all_ip_ranges = chain.from_iterable(ip_ranges)
nets = (ipaddress.ip_network(_ip) for _ip in all_ip_ranges)
cidrs = (
str(ip_range).strip() for ip_range in ipaddress.collapse_addresses(nets) # type:ignore
)
# ips = []
ip_count = 0
for cidr in cidrs:
for ip_address in ipaddress.IPv4Network(cidr):
# ips.append(ip_address)
ip_count += 1
print("Number of unique Amazon EC2 IPv4 addresses:", "{:,}".format(ip_count))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment