(20250210) Worked on the IP addr util a bit.

This commit is contained in:
2025-02-10 19:34:52 +05:30
parent 800d6706ef
commit 95d90e807b
15 changed files with 1918 additions and 10 deletions
+55
View File
@@ -160,6 +160,61 @@ def get_ipv4_range(ip_string, as_string = True):
return start_ip, end_ip, count
# ---------------------------------------------------------------------------------------------------------------------
def to_hyphen_notation(value: str) -> str | None:
"""
Takes in an IP pool (range) in either CIDR notation or already in hyphen-separated notation and parses it into the
hyphen-separated notation.
:param value: The IP-range in either of the accepted formats.
:return: The IP range in hyphen-separated notation.
"""
# Let's start by assuming failure:
success = False
start_ip = None
end_ip = None
# Ensure that the input is treated as a string:
value = str(value)
# First we check if the IP has been given in the CIDR notation:
if not success:
try:
# Try to extract the first and last IP addressed from the input:
ip_net = ipaddress.IPv4Network(value, strict = False)
start_ip = ip_net.network_address
end_ip = ip_net.broadcast_address
success = True
# In case the CIDR interpretation doesn't work:
except:
success = False
# Now we try to parse the input string as a hyphen-separated input:
if not success:
try:
# Split at the hyphen and take the parts:
parts = value.split("-")
start_ip = parts[0]
end_ip = parts[1]
success = True
# In case the hyphen-separated interpretation doesn't work:
except:
success = False
# Done here:
value = f"{start_ip}-{end_ip}" if success else None
return value
# *****************************************************************************************************************
# ***** ****
# *** MAIN PROGRAM ***