Skip to content

Instantly share code, notes, and snippets.

@52617365
Created October 14, 2024 15:52
Show Gist options
  • Save 52617365/ddc28e35defcfc26a62fb8b28476757d to your computer and use it in GitHub Desktop.
Save 52617365/ddc28e35defcfc26a62fb8b28476757d to your computer and use it in GitHub Desktop.
Check if an ip is within a certain subnet mask
import ipaddress
def is_ip_in_cidr(ip_address, cidr_range):
try:
network = ipaddress.ip_network(cidr_range, strict=False)
ip = ipaddress.ip_address(ip_address)
return ip in network
except ValueError as e:
return f"Error: {e}"
# Example
print(is_ip_in_cidr("10.0.0.1", "10.0.0.0/8")) # True
print(is_ip_in_cidr("172.16.0.1", "172.16.0.0/12")) # True
print(is_ip_in_cidr("192.168.1.1", "192.168.2.0/24")) # False
print(is_ip_in_cidr("invalid_ip", "192.168.1.0/24")) # Error message
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment