Skip to content

Instantly share code, notes, and snippets.

@mttaggart
Last active March 17, 2022 02:47
Show Gist options
  • Save mttaggart/fc4d7ae060e69466da57c8aa7081066a to your computer and use it in GitHub Desktop.
Save mttaggart/fc4d7ae060e69466da57c8aa7081066a to your computer and use it in GitHub Desktop.
Functional vs. OO Subnet Calculators
"""
FUNCTIONAL IP SUBNET CALCULATOR/GENERATOR
"""
import sys
from functools import reduce
def is_ip(ip_string: str) -> bool:
try:
return all(map(lambda o: int(o) in range(0, 256), ip_string.split(".")))
except ValueError:
return False
def is_subnet(cidr_string: str) -> bool:
try:
components = cidr_string.split("/")
return len(components) == 2 and \
is_ip(components[0]) and \
int(components[1]) in range(0,33)
except ValueError:
return False
def octet_int(ip_string: str) -> int:
return reduce(
lambda a, o: (a << 8) + int(o),
ip_string.split("."),
0
)
def from_int(ip_int: int):
res = ""
for i in range(4):
res = "." + str(ip_int & 0xff) + res
ip_int = ip_int >> 8
return res[1::]
def subnet_addrs(cidr_string: str) -> list:
subnet_max = 0xffffffff
components = cidr_string.split("/")
address = components[0]
subnet_mask = int(components[1])
subnet_range = (subnet_max << (32 - subnet_mask)) & subnet_max
net_addr = octet_int(address) & subnet_range
broadcast_addr = (subnet_max - subnet_range) + net_addr
return list(map(from_int, range(net_addr + 1, broadcast_addr)))
def main():
in_string = sys.argv[1]
if is_subnet(in_string):
print(f"{in_string} is a valid subnet!")
elif is_ip(in_string):
print(f"{in_string} is a valid IP!")
else:
print(f"{in_string} is NOT a valid IP or subnet!")
if __name__ == "__main__":
main()
"""
OBJECT ORIENTED SUBNET CALCULATOR/GENERATOR
"""
import sys
SUBNET_MAX = 0xffffffff
class IPSubnet:
@staticmethod
def is_subnet(cidr_string: str) -> bool:
try:
components = cidr_string.split("/")
return len(components) == 2 and \
IPAddress.is_ip(components[0]) and \
int(components[1]) in range(0,33)
except ValueError:
return False
def __init__(self, cidr_string: str):
if IPSubnet.is_subnet(cidr_string):
components = cidr_string.split("/")
self.cidr = cidr_string
self.address = IPAddress(components[0])
self.subnet_mask = int(components[1])
else:
raise ValueError("Not a valid Subnet!")
def subnet_addrs(self) -> list:
subnet_range = (0xffffffff << (32 - self.subnet_mask)) & 0xffffffff
net_addr = self.address.octet_int() & subnet_range
broadcast_addr = (SUBNET_MAX - subnet_range) + net_addr
addrs = []
for a in range(net_addr + 1, broadcast_addr):
addrs.append(IPAddress.from_int(a))
class IPAddress:
total_addresses = 0
@staticmethod
def is_ip(ip_string: str) -> bool:
try:
octets = ip_string.split(".")
for o in octets:
o_int = int(o)
if o_int < 0 or o_int > 255:
return False
return True
except:
return False
@classmethod
def inc_addrs(cls):
cls.total_addresses += 1
@staticmethod
def from_int(ip_int: int):
res = ""
for i in range(4):
res = "." + str(ip_int & 0xff) + res
ip_int = ip_int >> 8
return res[1::]
def __init__(self, ip_string: str):
if IPAddress.is_ip(ip_string):
self.address = ip_string
IPAddress.inc_addrs()
else:
raise ValueError("Not a valid IP!")
def octet_int(self) -> int:
res = 0
for o in self.address.split("."):
res << 8
res += int(o)
def main():
in_string = sys.argv[1]
try:
subnet = IPSubnet(in_string)
print(f"Subnet: {subnet.cidr}")
except:
print(f"{in_string} is not an IP Subnet")
try:
addr = IPAddress(in_string)
print(f"Address: {addr.address}")
except:
print(f"{in_string} is not an IP Address")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment