Skip to content

Instantly share code, notes, and snippets.

@bizmate
Created March 22, 2019 15:33
Show Gist options
  • Save bizmate/f63d805917f8345cda4263dcaf07f2f2 to your computer and use it in GitHub Desktop.
Save bizmate/f63d805917f8345cda4263dcaf07f2f2 to your computer and use it in GitHub Desktop.
<?php
$ip = '35.185.31.87';
$ranges = [
'8.34.208.0/20', '8.35.192.0/21', '8.35.200.0/23', '108.59.80.0/20', '108.170.192.0/20', '108.170.208.0/21', '162.216.148.0/22', '162.222.176.0/21',
'173.255.112.0/20', '192.158.28.0/22', '199.192.112.0/22', '199.223.232.0/22', '199.223.236.0/23', '23.236.48.0/20', '23.251.128.0/19', '35.204.0.0/14',
'35.208.0.0/13', '107.167.160.0/19', '107.178.192.0/18', '146.148.2.0/23', '146.148.4.0/22', '146.148.8.0/21', '146.148.16.0/20', '146.148.32.0/19',
'146.148.64.0/18', '35.203.0.0/17', '35.203.128.0/18', '35.203.192.0/19', '35.203.240.0/20', '130.211.8.0/21', '130.211.16.0/20', '130.211.32.0/19',
'130.211.64.0/18', '130.211.128.0/17', '104.154.0.0/15', '104.196.0.0/14', '208.68.108.0/23', '35.184.0.0/14', '35.188.0.0/15', '35.216.128.0/17', '35.217.128.0/17'
];
foreach( $ranges as $range) {
echo "is in range " . $range . " : " . (ip_in_range( $ip, $range) ? 'yes':'no' ) . "\n<br/>";
}
/**
* Check if a given ip is in a network
* @param string $ip IP to check in IPV4 format eg. 127.0.0.1
* @param string $range IP/CIDR netmask eg. 127.0.0.0/24, also 127.0.0.1 is accepted and /32 assumed
* @return boolean true if the ip is in this range / false if not.
*/
function ip_in_range( $ip, $range ) {
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