import sys, re class IP: def __init__(self, input_str): try: ip, netmask = input_str.split("/") except: return None if not re.match('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', ip): return None if not re.match('\d{1,2}', netmask): return None octects = [ int(o) for o in ip.split(".") ] for o in octects: if not 0 <= o <= 255: return None netmask = int(netmask) if not 0 <= netmask <= 32: return None self.ip = ip self.netmask = netmask self.octects = octects def print_network_address(self): masks,masks_inverted = [], [] for i in range(4): masks.append(int((("1" * self.netmask + "0" * (32 - self.netmask))[i*8:(i+1)*8]), 2)) masks_inverted.append(int((("0" * self.netmask + "1" * (32 - self.netmask))[i*8:(i+1)*8]), 2)) print('{:>21}'.format("Subnet Address: "), end='') for i in range(3): print(self.octects[i] & masks[i], end='.') print(self.octects[3] & masks[3]) print("Broadcast Address: ", end='') for i in range(3): print(self.octects[i] | masks_inverted[i], end='.') print(self.octects[3] | masks_inverted[3]) if len(sys.argv) == 2: try: my_ip = IP(sys.argv[1]) my_ip.print_network_address() except AttributeError: print("\nHelp:") print("\n\tip-subnet.py IP_Address\CIDR_Notation") print("\tExample: ip-subnet.py 192.168.137.89/27") sys.exit(1) else: print("\nHelp:") print("\n\tip-subnet.py IP_Address\CIDR_Notation") print("\tExample: ip-subnet.py 192.168.137.89/27") sys.exit(1)