Finding largest netmask for given set of hosts
Edvard Majakari
edvard.majakari at staselog.com
Mon Aug 12 09:11:29 EDT 2002
> The first thing to note is that (version 4) IP addresses are 32-bit
> numbers, which means that most Python implementations can handle them as
> integers and use the bit-wise operations on them. Consequently, if all
> addresses are converted before use, you won't need dec2bin. A naiive
> implementation will end up producing long integers for anything above
> the class A space, however. Unless efficiency is *really* important I'd
> overlook this as long as your Python is recent enough to implicitly
> convert. You could even explicitly use longs if you wanted.
Ah, ok.
I knew that I could use Python's normal integers, but didn't think of any
fast & neat method for converting IP's to integers. Your method seems to
be fast enough, and what's most important, your implementation of the
algorithm I suggested worked ok. Thank you for your help! Now I have
def calculate_nw(self):
net = self._list[0].ip()
mask = 0xFFFFFFFFL
for addr in self._list[1:]:
mask = net ^ ~addr.ip()
net = net & mask
zeros = 0
for bit in range(32, 0, -1):
pos = bit -1
zeros = zeros | (~mask & (1<< pos))
if zeros:
mask = mask & ~(1 << pos)
net = net & mask
return ipaddr(numtoip(net) + '/' + str(bit2netmask(mask)))
That is, calculate_nw assumes that the object attribute self._list[]
contains list of ip objects, each of which has method ip() to return their
value as long. Your method of zeroing each one after the first zero is
quite ingenious!
--
# Edvard Majakari Software Engineer
# PGP PUBLIC KEY available Soli deo gloria - Glory to God alone!
$_ = '456476617264204d616a616b6172692c20612043687269737469616e20'; print
join('',map{chr hex}(split/(\w{2})/)),uc substr(crypt(60281449,'es'),2,4),"\n";
More information about the Python-list
mailing list