Skip to content

Instantly share code, notes, and snippets.

@gerbenjacobs
Last active December 4, 2018 06:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gerbenjacobs/6973722 to your computer and use it in GitHub Desktop.
Save gerbenjacobs/6973722 to your computer and use it in GitHub Desktop.
Get the start and end IP from an IP Range by a CIDR (Classless Inter-Domain Routing) notation, complete or incomplete. As discussed here: https://blog.gerbenjacobs.nl/get-ip-range-by-cidr-notation.html
<?php
function getIPRangeByCIDR($cidr) {
// Making sure IPs are valid
$ipdata = explode('/', ltrim($cidr, '0'));
$dotcount = substr_count($ipdata[0], '.');
if ($dotcount != 3) {
$ipdata[0] .= str_repeat('.0', (3-$dotcount));
}
$cidr_address = sprintf('%s/%s', $ipdata[0], $ipdata[1]);
// By 'unknown' http://www.php.net/manual/en/ref.network.php#30910
$first = substr($cidr_address, 0, strpos($cidr_address, "/"));
$netmask = substr(strstr($cidr_address, "/"), 1);
$first_bin = str_pad(decbin(ip2long($first)), 32, "0", STR_PAD_LEFT);
$last_bin = '';
$netmask_bin = str_pad(str_repeat("1", (integer)$netmask), 32, "0", STR_PAD_RIGHT);
for ($i = 0; $i < 32; $i++) {
if ($netmask_bin[$i] == "1")
$last_bin .= $first_bin[$i];
else
$last_bin .= "1";
}
$last = long2ip(bindec($last_bin));
return array($first, $last);
}
print_r(getIPRangeByCIDR('190.151.192/18'));
// Array ( [0] => 190.151.192.0 [1] => 190.151.255.255 )
print_r(getIPRangeByCIDR('17/8'));
// (Apple) Array ( [0] => 17.0.0.0 [1] => 17.255.255.255 )
print_r(getIPRangeByCIDR('65.192/11'));
// (NSA?) Array ( [0] => 65.192.0.0 [1] => 65.223.255.255 )
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment