Finding largest netmask for given set of hosts
Steve Holden
sholden at holdenweb.com
Mon Aug 12 09:15:22 EDT 2002
"Edvard Majakari" <edvard.majakari at staselog.com> wrote ...
>
> > 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!
>
Thank you. I'm sure that scrutiny would yield a better way to do it.
Note that the Python Cookbook includes rather better (though
less-comprehensible to a beginner) methods for IP address conversion.
import socket, struct
def dottedQuadToNum(ip):
return struct.unpack('>L', socket.inet_aton(ip))[0]
def numToDottedQuad(n):
return socket.inet_ntoa(struct.pack(">L', n))
regards
-----------------------------------------------------------------------
Steve Holden http://www.holdenweb.com/
Python Web Programming http://pydish.holdenweb.com/pwp/
-----------------------------------------------------------------------
More information about the Python-list
mailing list