Skip to content

Instantly share code, notes, and snippets.

@ryanwinchester
Forked from tott/ip_in_range.php
Last active March 15, 2021 18:25
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ryanwinchester/578c5b50647df3541794 to your computer and use it in GitHub Desktop.
Save ryanwinchester/578c5b50647df3541794 to your computer and use it in GitHub Desktop.
php check if IP is in given network range
<?php
/**
* Check if a given ip is in a network.
*
* @see https://gist.github.com/ryanwinchester/578c5b50647df3541794
*
* @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 bool 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);
$ip_decimal = ip2long($ip);
$range_decimal = ip2long($range);
$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