Skip to content

Instantly share code, notes, and snippets.

@altaurog
Created Aug 12, 2015
Embed
What would you like to do?
Python classes for working with ipv4 addresses
tohex = lambda a:'.'.join('%02X' % p for p in a)
fromhex = lambda h:[int(p,16) for p in h.split('.')]
tobin = lambda a:'.'.join('{0:08b}'.format(p) for p in a)
frombin = lambda h:[int(p,2) for p in h.split('.')]
class IPAddr(object):
def __init__(self, address):
if isinstance(address, (int,long)):
self.long = address
else:
self.addr_tuple = tuple(address)
def gethex(self):
return tohex(self.addr_tuple)
def sethex(self, hexaddr):
self.addr_tuple = tuple(fromhex(hexaddr))
hex = property(gethex, sethex)
def getbin(self):
return tobin(self.addr_tuple)
def setbin(self, binaddr):
self.addr_tuple = tuple(frombin(binaddr))
bin = property(getbin, setbin)
def getdec(self):
return '.'.join(str(p) for p in self.addr_tuple)
def setdec(self, decaddr):
self.addr_tuple = tuple(int(p) for p in decaddr.split('.'))
dec = property(getdec, setdec)
def getlong(self):
return sum(b << i for b, i in zip(self.addr_tuple, (24,16,8,0)))
def setlong(self, L):
self.addr_tuple = tuple(0xff & (L >> i) for i in (24,16,8,0))
long = property(getlong, setlong)
def __repr__(self):
return self.hex
class CIDR(IPAddr):
def __init__(self, address, num_bits):
super(CIDR, self).__init__(address)
self.num_bits = num_bits
netmask = 1 << 32 - num_bits
for i in range(num_bits):
netmask |= (netmask << i)
self.netmask = IPAddr(netmask)
self.wildcard = IPAddr(0xffffffff ^ netmask)
self.broadcast = IPAddr(self.long + self.wildcard.long)
def __contains__(self, address):
return self.long < address.long < self.broadcast.long
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment