how to convert ipaddress/mask to CIDR using c++?

chingupt picture chingupt · Dec 13, 2013 · Viewed 8.1k times · Source

I have a list of ipaddress/mask which needs to be converted to CIDR notation.

for e.g. 12.174.36.240/24 needs to be converted to 12.174.36.0/24 or something like what http://www.subnet-calculator.com/cidr.php does

How can this be acheived?

PS: the mask value is not always 24.

Answer

Elliot Robinson picture Elliot Robinson · Dec 13, 2013

Just to lead you in the right direction, consider what an IPv4 address is (a 32-bit integer). Now, consider what a mask is (a bit field used in bitwise operations).

Take the address 127.0.0.1 on a big-endian system. In hex, that's 0x7f000001. A 24-bit mask is 0xffffff00 (24 bits of 1, 8 bits of 0, 32 bits total). The bitwise and of the address and the mask 0x7f000001 & 0xffffff00 = 0x7f000000 is the CIDR format.

I leave it to you to determine how best to parse the address, convert the IPv4 address to its integer form (and back), and create a bit mask from a routing prefix mask, though I will tell you that there are standard functions for at least the address manipulation.