Home » Php » ipv4 – php cidr prefix to netmask

ipv4 – php cidr prefix to netmask

Posted by: admin July 12, 2020 Leave a comment

Questions:

I’m looking to convert a cidr prefix (e.g. /28) to a netmask (e.g. 255.255.255.240) and have not located a function for this, does one exist in php? If not, how would I go about doing this?

How to&Answers:

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 at snipplr.

Answer:

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