Tuesday, January 20, 2009

2 Line PHP Function To Convert CIDR Postfix to Netmask

This is a problem with lots of really ugly solutions. Here's one that works, producing the correct output when called as a parameter to long2ip:
function cidr2longnetmask($cidr) {
  if($cidr > 32 || $cidr < 0) {
    return false;
  }
  $netmask = pow(2,$cidr) - 1;
  $netmask = $netmask << (32 - $cidr);
  return $netmask;
}

That's it. Tested with all integers from 0-32 (others return false.)