Skip to content

Instantly share code, notes, and snippets.

@timothymarois
Last active March 18, 2019 20:51
Show Gist options
  • Save timothymarois/768040f60943859cd65fbbf6b6c2f05b to your computer and use it in GitHub Desktop.
Save timothymarois/768040f60943859cd65fbbf6b6c2f05b to your computer and use it in GitHub Desktop.
IP: Get IP Range based on CIDR Block
/**
* Get the IP range block based on CIDR
*
* @param string $cidr 127.0.0.1/28
* @return array
*/
function ipCalculateRange($cidr) {
$range = array();
$cidr = explode('/', $cidr);
$range[0] = long2ip((ip2long($cidr[0])) & ((-1 << (32 - (int)$cidr[1]))));
$range[1] = long2ip((ip2long($range[0])) + pow(2, (32 - (int)$cidr[1])) - 1);
return $range;
}
/**
* Check if IP address is within CIDR range
*
* @param string $ip 127.0.0.1
* @param string $cidr 127.0.0.1/28
* @return bool
*/
function ipInRange($ip, $cidr) {
if ( strpos( $range, '/' ) == false ) {
$range .= '/32';
}
// $range is in IP/CIDR format eg 127.0.0.1/24
list( $range, $netmask ) = explode( '/', $range, 2 );
$range_decimal = ip2long( $range );
$ip_decimal = ip2long( $ip );
$wildcard_decimal = pow( 2, ( 32 - $netmask ) ) - 1;
$netmask_decimal = ~ $wildcard_decimal;
return ( ( $ip_decimal & $netmask_decimal ) == ( $range_decimal & $netmask_decimal ) );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment