Skip to content

Instantly share code, notes, and snippets.

@linickx
Created October 24, 2011 16:04
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save linickx/1309388 to your computer and use it in GitHub Desktop.
Save linickx/1309388 to your computer and use it in GitHub Desktop.
php network functions
<?php
function cidr2mask($netmask) {
$netmask_result="";
for($i=1; $i <= $netmask; $i++) {
$netmask_result .= "1";
}
for($i=$netmask+1; $i <= 32; $i++) {
$netmask_result .= "0";
}
$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
}
$subnet = join( ".", $netmask_ip_decimal_array );
return $subnet;
}
echo cidr2mask("23");
?>
<?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");
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment