import sys import socket from socket import inet_aton from netaddr import * class SubnetTools: def __init__(self): self.INVALID = -1 def getBitMask(self,netmask): b = '' for octal in netmask: b += bin(int(octal))[2:].zfill(8) return str(len(b.rstrip('0'))) def validateIP(self,ip): try: inet_aton(ip) except: return False return True def createCIDR(self,ipaddr,netmask): if(self.validateIP(ipaddr) and self.validateIP(netmask) ): ipArray = ipaddr.split('.') netArray = netmask.split('.') # calculate network start net_start = [str(int(ipArray[x]) & int(netArray[x])) for x in range(0,4)] # print CIDR notation CIDR_address = '.'.join(net_start) + '/' + self.getBitMask(netArray) return (CIDR_address) else: return(self.INVALID) def isIPinNetwork(self,ip,cidr): set = IPSet([cidr]) return (ip in set) def ipListMatchNetwork(self,iplist,network): match_list = [] for ip in iplist: if(self.isIPinNetwork(ip,network)): match_list.append(ip) return match_list ''' convertCIDRtoNetmask() and CIDR2MASK() do the exact same thing -- just two examples ''' def convertCIDRtoNetmask(self,CIDR_address): mask = IPNetwork(CIDR_address) return mask.netmask def CIDR2MASK(self,CIDR_address): (ip,bits) = CIDR_address.split('/') cbits = int(bits) mask = [] if (not isinstance(cbits, int) or cbits < 0 or cbits > 32): print ("Error: %s (which is a %s)" % (str(cbits), type(cbits).__name__)) return None for t in range(4): if cbits > 7: mask.append('255') else: dec = 255 - (2**(8 - cbits) - 1) mask.append(str(dec)) cbits -= 8 if cbits < 0: cbits = 0 return '.'.join(mask) stool = SubnetTools() ipV4Address = "10.2.10.14" ipV4Netmask = "255.255.255.248" cidr = stool.createCIDR(ipV4Address,ipV4Netmask) print("IP: %s" % ipV4Address) print("MASK: %s" % ipV4Netmask) print("CIDR: %s" % cidr) print("CIDR: %s is MASK: %s" % (cidr,stool.convertCIDRtoNetmask(cidr) )) print("CIDR: %s is MASK: %s [longhand]" % (cidr,stool.CIDR2MASK(cidr) )) ''' Basic use of isIPinNetwork() ''' FirstIPToCheck = "10.2.10.15" print("%s is in %s: %s" % (FirstIPToCheck,cidr,stool.isIPinNetwork(FirstIPToCheck,cidr))) SecondIPToCheck = "10.2.10.22" print("%s is in %s: %s" % (SecondIPToCheck,cidr,stool.isIPinNetwork(SecondIPToCheck,cidr))) ''' Advanced use of isIPinNetwork()using ipListMatchNetwork() Pass an array of IP addresses to test and get back a list of only the IP addresses that are in the requested network subnet ''' testIPs = ['10.2.10.15','10.2.10.14','10.2.10.11','10.2.10.22'] subnetIPs = stool.ipListMatchNetwork(testIPs,cidr) print("Check the following list of IPs: %s" % testIPs) print("These IPs were in %s:\n\t%s" % (cidr,subnetIPs)) # Example of all masks with a dummy ip #for len in range(32,-1,-1): # checkcidr = ("%s/%s") % ("0.0.0.0",len) # print ("/%d = %s" % (len, stool.CIDR2MASK(checkcidr)))