public
Last active

php network functions

  • Download Gist
cidr2mask.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
<?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");
?>
get_network_id.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
<?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);
?>
hostincidr.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
<?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");
 
?>
mask2cidr.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
<?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");
 
?>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.