Friday challenge 2: spot the bug

Peter Corlett abuse at
Fri Apr 20 13:23:12 BST 2007

On Fri, Apr 20, 2007 at 01:02:08PM +0100, David Cantrell wrote:
> >From another mailing list, spot the bug.  This is meant to take an int
> in $netmask and count the number of bits so you can construct a
> CIDR-style address/bits.

>> for ($maskbits = 0, $i = $netmask; $i != 0; ++$maskbits) {
>>       if (($i & 0xc0000000) == 0x40000000) {
>>               die("Netmask must have contiguous leftmost '1' bits\n");
>>       }
>>       $i <<= 1;
>> }
> Yes, it's obviously translated from C. I'm not after stylistic criticisms.

Easy. $i isn't a 32 bit integer and so the left shift won't cause it to
overflow and be effectively taken modulo 2**32 and thus eventually set $i to
zero once all the bits have been shifted off the left.

$i &= 0xffffffff; after the left shift should fix it.

Having a lookup hash to map between netmask and CIDR bit count would be
better, of course.

More information about the mailing list