Is there a good way to match an IPv6 address to an IPv6 subnet using CIDR notation? What I am looking for is the IPv6 equivalent to this: Matching an IP to a CIDR mask in PH
Here is an example that works by checking an IP address against a list of individual IPs or CIDRs, both IPv4 and IPv6:
https://gist.github.com/lyquix-owner/2620da22d927c99d57555530aab3279b
$h) $subnet[$i] = base_convert($h, 16, 2); // Array of Binary
$subnet = substr(implode('', $subnet), 0, $bits); // Subnet in Binary, only network bits
// Convert remote IP to binary string of $bits length
$ip = unpack('H*', inet_pton($ip_check)); // IP in Hex
foreach($ip as $i => $h) $ip[$i] = base_convert($h, 16, 2); // Array of Binary
$ip = substr(implode('', $ip), 0, $bits); // IP in Binary, only network bits
// Check network bits match
if($subnet == $ip) {
$allow = true;
break;
}
}
}
if(!$allow) {
die('IP not allowed');
}