php cidr prefix to netmask

Solution 1

I wrote a class that contains a method that does this.

function CIDRtoMask($int) {
    return long2ip(-1 << (32 - (int)$int));
}

I posted the entire class as a gist.

Solution 2

Example #1:

function cidr2NetmaskAddr()

  function cidr2NetmaskAddr ($cidr) {

    $ta = substr ($cidr, strpos ($cidr, '/') + 1) * 1;
    $netmask = str_split (str_pad (str_pad ('', $ta, '1'), 32, '0'), 8);

    foreach ($netmask as &$element)
      $element = bindec ($element);

    return join ('.', $netmask);

  }

Usage

  echo cidr2NetmaskAddr ('194.234.213.0/28');

Output

255.255.255.240


Example #2:

function createNetmaskAddr()

  function createNetmaskAddr ($bitcount) {

    $netmask = str_split (str_pad (str_pad ('', $bitcount, '1'), 32, '0'), 8);

    foreach ($netmask as &$element)
      $element = bindec ($element);

    return join ('.', $netmask);

  }

Usage

  echo createNetmaskAddr (28);

Output

255.255.255.240

Share:
Admin
Author by

Admin

Updated on June 16, 2022

Comments

  • Admin
    Admin about 2 months

Related