Skip to content

Instantly share code, notes, and snippets.

@dentarg
Last active December 2, 2023 10:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dentarg/854aa237db1e530f1881043a3ea3d5a0 to your computer and use it in GitHub Desktop.
Save dentarg/854aa237db1e530f1881043a3ea3d5a0 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
if %w(-h --help).include?(ARGV.first)
abort <<~USAGE
#{__FILE__} <FILE> to count IPs in given file
#{__FILE__} to count IPs using latest file on disk
DL=1 #{__FILE__} to download the AWS IP ranges
USAGE
end
require "ipaddr"
require "json"
require "net/http"
ip_ranges_url = "https://ip-ranges.amazonaws.com/ip-ranges.json"
filename = ARGV.first
if ENV.key?("DL")
date = Time.now.strftime("%F")
filename = "ip-ranges_#{date}.json"
ip_ranges_data = Net::HTTP.get(URI(ip_ranges_url))
puts "✅ Downloaded #{ip_ranges_url}"
File.write(filename, ip_ranges_data)
puts "💾 Saved them to #{filename}"
else
filename = Dir["ip-ranges_*.json"].reverse.first
end
no_file = filename.nil? || !File.exist?(filename)
abort "Run with DL=1 to download #{ip_ranges_url}" if no_file
puts "✏️ Counting IPs in #{filename}"
ip_ranges_data ||= File.read(filename)
ip_ranges = JSON.parse(ip_ranges_data)
count_v4 = ip_ranges["prefixes"]
.select { |pref| pref["service"] == "EC2" }
.map { |pref| 2 ** (32 - IPAddr.new(pref["ip_prefix"]).prefix) }
.sum
count_v6 = ip_ranges["ipv6_prefixes"]
.select { |pref| pref["service"] == "EC2" }
.map { |pref| 2 ** (128 - IPAddr.new(pref["ipv6_prefix"]).prefix) / 2**(128-64) }.sum
puts "IPv4: #{count_v4}"
puts "IPv6: #{count_v6}"
@dentarg
Copy link
Author

dentarg commented Jan 19, 2022

$ ./count_ec2_ips.rb
✏️   Counting IPs in ip-ranges_2022-01-19.json
IPv4: 56574589
IPv6: 24162205707

$ ./count_ec2_ips.rb ip-ranges_2021-09-15.json
✏️   Counting IPs in ip-ranges_2022-01-19.json
IPv4: 56574589
IPv6: 24162205707

@dentarg
Copy link
Author

dentarg commented Aug 29, 2022

$ DL=1 ruby ~/home.git/gists/count_ec2_ips/count_ec2_ips.rb
✅  Downloaded https://ip-ranges.amazonaws.com/ip-ranges.json
💾  Saved them to ip-ranges_2022-08-29.json
✏️   Counting IPs in ip-ranges_2022-08-29.json
IPv4: 57394293
IPv6: 27570798603

@dentarg
Copy link
Author

dentarg commented Jul 31, 2023

$ DL=1 ruby ~/home.git/gists/count_ec2_ips/count_ec2_ips.rb
✅  Downloaded https://ip-ranges.amazonaws.com/ip-ranges.json
💾  Saved them to ip-ranges_2023-07-31.json
✏️   Counting IPs in ip-ranges_2023-07-31.json
IPv4: 58541589
IPv6: 47340798211

@dentarg
Copy link
Author

dentarg commented Dec 2, 2023

$ DL=1 ruby ~/home.git/gists/count_ec2_ips/count_ec2_ips.rb
✅  Downloaded https://ip-ranges.amazonaws.com/ip-ranges.json
💾  Saved them to ip-ranges_2023-12-02.json
✏️   Counting IPs in ip-ranges_2023-12-02.json
IPv4: 59507813
IPv6: 50212528388

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment