Thursday, November 22, 2012

Netmask , prefix length :
==========================

  netmask is also measured as prefix length. The number of bits set in netmask value is called as prefix length.
Example :   Netmask:255.255.255.0 Prefix : 24 //number of bits set in 255.255.255.0 value.

 To convert the netmask to prefix I added below code in Java:

  netmask= lookupHost("255.255.255.128");
   while ( netmask !=0)
   {
      if( netmask & 1)
        ++prefixLength;
       netmask = netmask >> 1;
    
   }

  Simple code :
     The above code is working fine for sometime. Sometimes it is not working...
    I found that netmask to prefix conversion is breaking and makes the system hangs....

 The input 255.255.255.0 is working fine. But 255.255.255.128 is breaking ...

Finally figured that the problem is with the code.

    In a 32 bit signed integer, 255.255.255.0 is not giving any problem. So LSB is stored as a first byte in memory ...

   lookupHost converts the string as 0 255 255 255[bits set] as integer..[0x00ffffff].
when it comes to 255.255.255.128, 128 255 255 255 [bits set as 0x80ffffff. So netmask will always not equal to 0, So it is in infinite loop.
>> shift operator operates on bits not on sign bit. netmask's sign bit will always 1 & it satisfies netmask != 0 condition infinitely.

Solution:
   To avoid this problem,
    1)I have to use >>> operator which will also operates on sign bit.
    2) I can also check for the maximum limit.

   Above code can be modified as below:

      
  netmask= lookupHost("255.255.255.128");
   while ( netmask !=0)
   {
      if( netmask & 1)
      {
        ++prefixLength;
         if (prefixLength == 32)
         {
           break; //exit while loop since maximum allowed value is reached for prefix length for 32 bit IP address, maximum prefix len is 32
         }
      }
       netmask = netmask >>> 1;// >>>     Unsigned right shift
         
   }

No comments: