PHP and networks

Well, I did not install the perl PHP extension. I think my friend Benjamin summed it up the best when he responded to my post about it on facebook:

Dmitry Stogov claims to be the lead developer, but I'm pretty sure that it was the devil.

So now I am back to looking for a good way to do diffs in PHP of files that are sometimes 75,000+ lines. Either my google-fu has improved and I have not seen some of these solutions before, or it has not and I blocked out the memory of having tested some of these solutions. We'll see which it is when I get into the office tomorrow.

Also, the other special kind of fun that I was trying to find a solution for was a replacement for the perl module Net::Netmask. Thanfully I found a github gist that had just what I was looking for!

Reproduced here are the ones that I adapted for what I needed, mainly so I can find them again later.

<?php

# REFERENCE - http://stackoverflow.com/questions/2942299/converting-cidr-address-to-subnet-mask-and-network-address

$ipNetmask = "192.168.1.12/16";
list($ip, $netmask) = split( "/", $ipNetmask );
$ip_elements_decimal = split( "[.]", $ip );
$netmask_result="";
for($i=1; $i <= $netmask; $i++) {
$netmask_result .= "1";
}
for($i=$netmask+1; $i <= 32; $i++) {
   $netmask_result .= "0";
echo $netmask_result;
}
$netmask_ip_binary_array = str_split( $netmask_result, 8 );
$netmask_ip_decimal_array = array();
foreach( $netmask_ip_binary_array as $k => $v ){
   $netmask_ip_decimal_array[$k] = bindec( $v ); // "100" => 4
   $network_address_array[$k] = ( $netmask_ip_decimal_array[$k] & $ip_elements_decimal[$k] );
}
$network_address = join( ".", $network_address_array );

print_r($network_address);
?>
<?php

# REFERENCE http://stackoverflow.com/questions/594112/matching-an-ip-to-a-cidr-mask-in-php5

function cidr_match($ip, $range)
{
   list ($subnet, $bits) = split('/', $range);
   $ip = ip2long($ip);
   $subnet = ip2long($subnet);
   $mask = -1 << (32 - $bits);
   $subnet &= $mask; # nb: in case the supplied subnet wasn't correctly aligned
   return ($ip & $mask) == $subnet;
}

if (cidr_match("10.128.0.0", "10.128.1.0/16")) {
   echo 'match';
} else {
   echo 'no match';
}

echo cidr_match("10.128.0.0", "10.128.1.0/16");

?>
<?php

function mask2cidr($mask) {

$mask = split( "[.]", $mask );

$bits = 0;

foreach ($mask as $octect) {
   $bin = decbin($octect);
   $bin = str_replace ( "0" , "" , $bin);
   $bits = $bits + strlen($bin);
}
   return $bits;
}

echo mask2cidr("255.255.252.0");

?>