Search code examples
phpnetwork-programmingipipv4cidr

convert ipv4 netmask to cidr format


I have the ip and netmask

192.168.1.0 255.255.255.0

I need to convert the netmask into cidr format

192.168.1.0/24

How do I convert ipv4 address and netmask into cidr format?

I am using PHP5.6


Solution

  • The complicated way would be to convert the netmask to binary and count the number of leading 1 bits. But since there are only 33 possible values, a simpler way is just an associative array:

    $netmask_to_cidr = array(
        '255.255.255.255' => 32,
        '255.255.255.254' => 31,
        '255.255.255.252' => 30,
        ...
        '128.0.0.0' => 1,
        '0.0.0.0' => 0);