Skip to content

Instantly share code, notes, and snippets.

@kmark
Created December 7, 2025 09:14
Show Gist options
  • Select an option

  • Save kmark/cbf9d0eba649df53d12b4254fc85c972 to your computer and use it in GitHub Desktop.

Select an option

Save kmark/cbf9d0eba649df53d12b4254fc85c972 to your computer and use it in GitHub Desktop.
import json
import urllib.request
import sys
import os
from ipaddress import ip_address, ip_network
def check_aws_ip(ip):
"""
Checks if the given IP address belongs to AWS and retrieves relevant metadata.
Args:
ip (str): The IP address to check (e.g., '3.5.0.1').
Returns:
dict: Metadata including whether it's an AWS IP, region, service, and network border group.
"""
url = "https://ip-ranges.amazonaws.com/ip-ranges.json"
try:
with urllib.request.urlopen(url) as response:
data = json.loads(response.read().decode("utf-8"))
for prefix in data["prefixes"]:
if ip_address(ip) in ip_network(prefix["ip_prefix"]):
return {
"is_aws": True,
"region": prefix.get("region", "N/A"),
"service": prefix.get("service", "N/A"),
"network_border_group": prefix.get("network_border_group", "N/A"),
"ip_prefix": prefix["ip_prefix"],
}
return {"is_aws": False}
except urllib.error.URLError as e:
print(f"Error fetching AWS IP ranges: {e}")
return {"error": "Failed to fetch data"}
except json.JSONDecodeError as e:
print(f"Error parsing JSON: {e}")
return {"error": "Failed to parse data"}
except ValueError as e:
print(f"Invalid IP address: {e}")
return {"error": "Invalid IP address"}
if __name__ == "__main__":
script_name = os.path.basename(__file__)
if len(sys.argv) != 2:
print(f"Usage: python {script_name} <IP_ADDRESS>")
sys.exit(1)
user_ip = sys.argv[1].strip()
result = check_aws_ip(user_ip)
print(json.dumps(result, indent=2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment