Skip to content

Instantly share code, notes, and snippets.

@josuecau
Created February 21, 2015 16:32
Show Gist options
  • Save josuecau/4fab416f5cfc5f2b7d5d to your computer and use it in GitHub Desktop.
Save josuecau/4fab416f5cfc5f2b7d5d to your computer and use it in GitHub Desktop.
Check if a given IPV4 belongs to Cloudflare. Usage : `php is-cloudflare-ip.php 108.162.242.71`
<?php
/**
* Check if a given ip is in a network.
*
* @link https://gist.github.com/tott/7684443
*
* @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));
}
/**
* Check if a given IPV4 belongs to Cloudflare.
*
* @param string $ip IP to check in IPV4 format eg. 127.0.0.1
*
* @return boolean true if the ip belongs to Cloudflare / false if not.
*/
function is_cloudflare($ip)
{
$cf_ips = array(
'199.27.128.0/21',
'173.245.48.0/20',
'103.21.244.0/22',
'103.22.200.0/22',
'103.31.4.0/22',
'141.101.64.0/18',
'108.162.192.0/18',
'190.93.240.0/20',
'188.114.96.0/20',
'197.234.240.0/22',
'198.41.128.0/17',
'162.158.0.0/15',
'104.16.0.0/12',
);
$is_cf_ip = false;
foreach ($cf_ips as $cf_ip) {
if (ip_in_range($ip, $cf_ip)) {
$is_cf_ip = true;
break;
}
}
return $is_cf_ip;
}
if (empty($argv[1])) {
exit(sprintf("Usage: php %s XXX.XXX.XXX.XXX\n", $argv[0]));
}
printf("%s is %sa Cloudflare IP\n", $argv[1], is_cloudflare($argv[1]) ? '' : 'not ');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment