Convert netmask to CIDR format in C ++

I need to convert 2 DWORDs, IP address and netmask to CDIR format ... Therefore, I have 2 DWORDs corresponding to 1.1.1.1 and 255.255.255.255, and I want to come up with the line 1.1.1.1/32

Any thoughts on this?

thanks

+1
source share
4 answers

Since there is a small and fixed number of valid network masks (more precisely, 32), the fastest way is probably just to build a mask map with a prefix length once during init, and the conversion is just a search into the map.

+3
source

The prefix length is equal to the number (leading) in the binary representation of the subnet mask. Therefore, you just need to count the number of (leading).

+2

The easiest approach:

  static unsigned short toCidr(char* ipAddress)
  {
      unsigned short netmask_cidr;
      int ipbytes[4];

      netmask_cidr=0;
      sscanf(ipAddress, "%d.%d.%d.%d", &ipbytes[0], &ipbytes[1], &ipbytes[2], &ipbytes[3]);

      for (int i=0; i<4; i++)
      {
          switch(ipbytes[i])
          {
              case 0x80:
                  netmask_cidr+=1;
                  break;

              case 0xC0:
                  netmask_cidr+=2;
                  break;

              case 0xE0:
                  netmask_cidr+=3;
                  break;

              case 0xF0:
                  netmask_cidr+=4;
                  break;

              case 0xF8:
                  netmask_cidr+=5;
                  break;

              case 0xFC:
                  netmask_cidr+=6;
                  break;

              case 0xFE:
                  netmask_cidr+=7;
                  break;

              case 0xFF:
                  netmask_cidr+=8;
                  break;

              default:
                  return netmask_cidr;
                  break;
          }
      }

      return netmask_cidr;
  }
+2
source

It is inefficient if you have a large number of these functions, since it passes through the bits one at a time. But a very simple way to count each bit in a netmask:

int cidr = 0;
while ( netmask )
{
    cidr += ( netmask & 0x01 );
    netmask >>= 1;
}

Then combine the IP address with this CIDR value.

0
source

All Articles