From 58a12c414cdf55881816fba79c277c7a00e9f78d Mon Sep 17 00:00:00 2001 From: Simon Rettberg Date: Tue, 10 Dec 2019 15:21:00 +0100 Subject: [inc/IpUtil] Add missing class --- inc/iputil.inc.php | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 inc/iputil.inc.php diff --git a/inc/iputil.inc.php b/inc/iputil.inc.php new file mode 100644 index 00000000..5cdd583c --- /dev/null +++ b/inc/iputil.inc.php @@ -0,0 +1,72 @@ + (int), 'end' => (int)] representing + * the according start and end addresses as integer + * values. Returns false on malformed input. + * @param string $cidr 192.168.101/24, 1.2.3.4/16, ... + * @return array|false start and end address, false on error + */ + public static function parseCidr($cidr) + { + $parts = explode('/', $cidr); + if (count($parts) !== 2) + return false; + $ip = $parts[0]; + $bits = $parts[1]; + if (!is_numeric($bits) || $bits < 0 || $bits > 32) + return false; + $dots = substr_count($ip, '.'); + if ($dots < 3) { + $ip .= str_repeat('.0', 3 - $dots); + } + $ip = ip2long($ip); + if ($ip === false) + return false; + $bits = pow(2, 32 - $bits) - 1; + if (PHP_INT_SIZE === 4) + return ['start' => sprintf('%u', $ip & ~$bits), 'end' => sprintf('%u', $ip | $bits)]; + return ['start' => $ip & ~$bits, 'end' => $ip | $bits]; + } + +} -- cgit v1.2.3-55-g7522