Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add getSubnet util to Grav\Common\Utils #2465

Merged
merged 1 commit into from
Apr 19, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions system/src/Grav/Common/Utils.php
Original file line number Diff line number Diff line change
Expand Up @@ -1469,4 +1469,44 @@ public static function processMarkdown($string, $block = true)

return $string;
}

/**
* Find the subnet of an ip with CIDR prefix size
*
* @param string $ip
* @param int $prefix
*
* @return string
* @throws \InvalidArgumentException if provided an invalid IP
*/
public static function getSubnet($ip, $prefix = 64)
{
if (!filter_var($ip, FILTER_VALIDATE_IP)) {
throw new \InvalidArgumentException('Invalid IP: ' . $ip);
}

// Packed representation of IP
$ip = inet_pton($ip);

// Maximum netmask length = same as packed address
$len = 8*strlen($ip);
if ($prefix > $len) $prefix = $len;

$mask = str_repeat('f', $prefix>>2);

switch($prefix & 3)
{
case 3: $mask .= 'e'; break;
case 2: $mask .= 'c'; break;
case 1: $mask .= '8'; break;
}
$mask = str_pad($mask, $len>>2, '0');

// Packed representation of netmask
$mask = pack('H*', $mask);
// Bitwise - Take all bits that are both 1 to generate subnet
$subnet = inet_ntop($ip & $mask);

return $subnet;
}
}