Skip to content

Instantly share code, notes, and snippets.

@kjanshair
Created December 18, 2023 13:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kjanshair/0333154721fe9ab64ff73ed049b4d229 to your computer and use it in GitHub Desktop.
Save kjanshair/0333154721fe9ab64ff73ed049b4d229 to your computer and use it in GitHub Desktop.
Python IP Address with CIDR Validators
import ipaddress
def check_ip(s_ip_or_net):
b_valid = True
try:
# The IP Addresses are expected to be passed without / even if it's /32 it would fail
# If it uses / so, the CIDR notation, check it as a Network, even if it's /32
if "/" in s_ip_or_net:
o_net = ipaddress.ip_network(s_ip_or_net)
else:
o_ip = ipaddress.ip_address(s_ip_or_net)
except ValueError:
b_valid = False
return b_valid
if __name__ == "__main__":
a_ips = ["192.168.1.0/20",
"10.0.0.0/16"
]
for s_ip in a_ips:
b_success = check_ip(s_ip)
if b_success is True:
print(f"The IP Address or Network {s_ip} is valid")
else:
print(f"The IP Address or Network {s_ip} is not valid")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment