# Finding largest netmask for given set of hosts

Steve Holden sholden at holdenweb.com
Mon Aug 12 15:15:22 CEST 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()
>
>             net = net & mask
>
>             zeros = 0
>             for bit in range(32, 0, -1):
>                 pos = bit -1
>                 zeros = zeros | (~mask & (1<< pos))
>                 if zeros:
>
>             net = net & 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

return struct.unpack('>L', socket.inet_aton(ip))[0]

return socket.inet_ntoa(struct.pack(">L', n))

regards
-----------------------------------------------------------------------
Steve Holden                                 http://www.holdenweb.com/
Python Web Programming                http://pydish.holdenweb.com/pwp/
-----------------------------------------------------------------------

```