perl and network addresses

Jason Stephenson jason at sigio.com
Fri Mar 31 21:01:01 EST 2006


Stephen Ryan wrote:

>>Can anyone think of a better way to blit an arbitrary number of bits 
>>from 0 to 1?
> 
> 
> Well, let's see....
> 
> Taking advantage of the fact that all of the '1' bits are at the end of
> the hostmask, you've actually almost gotten it already.
> 
> hostmask = (1 << (32 - n)) - 1
> netmask = ~ hostmask

Doh! That's so obvious, so obviously, I overlooked it. ;)

> 
> 1 << (32 - n) in binary is (n-1) '0' bits, a '1', then (32 - n) '0'
> bits.  Subtracting 1 from that gives n '0' bits followed by (32 - n) '1'
> bits.  The 'not' operator flips all the bits for the netmask.
> 
> This works for /1 through /32 networks, even though some of those are
> nonsensical.  A /0 might break this because of overflow (1 << (32 -n)
> overflows a 32-bit integer); theoretically, it should work even for /0
> so long as 1 << (32-n) returns 0 (32-bit gcc 4.0 on my Athlon64 desktop
> computes this correctly, but complains 'warning: left shift count >=
> width of type' while compiling.  Anyway, if you're running a /0, you've
> got other, bigger problems.

Using gcc 3.4.4 on a 32-bit Pentium III, I get no warnings when 
compiling your test program, even with -Wall. When it runs, 0 gives the 
same result as 32, so it overflows (silently) on my machine.

If you're running a /0, you really must be Root. ;)

I'm going to limit the input on my network calculator and throw an error 
on IPv4 net masks that are not between /8 and /30 inclusive. The reason 
being that < /8 and > /30 don't really give valid IPv4 networks.

Cheers and thanks,
Jason




More information about the gnhlug-discuss mailing list