Files

47 lines
1.4 KiB
PHP
Raw Permalink Normal View History

<?php
declare( strict_types=1 );
namespace StreamGoals\Core;
/** Pure IPv4/IPv6 CIDR membership test (no WordPress, no network). Malformed input never matches. */
final class CidrMatcher {
/** @param string[] $cidrs e.g. ['173.245.48.0/20', '2606:4700::/32'] */
public static function contains( string $ip, array $cidrs ): bool {
$ipBin = @inet_pton( trim( $ip ) );
if ( false === $ipBin ) {
return false;
}
foreach ( $cidrs as $cidr ) {
if ( self::inRange( $ipBin, (string) $cidr ) ) {
return true;
}
}
return false;
}
private static function inRange( string $ipBin, string $cidr ): bool {
$parts = explode( '/', trim( $cidr ), 2 );
if ( 2 !== count( $parts ) || ! ctype_digit( $parts[1] ) ) {
return false;
}
$netBin = @inet_pton( $parts[0] );
if ( false === $netBin || strlen( $netBin ) !== strlen( $ipBin ) ) { // different address families never match
return false;
}
$bits = (int) $parts[1];
if ( $bits < 0 || $bits > strlen( $netBin ) * 8 ) {
return false;
}
$fullBytes = intdiv( $bits, 8 );
if ( $fullBytes > 0 && substr( $ipBin, 0, $fullBytes ) !== substr( $netBin, 0, $fullBytes ) ) {
return false;
}
$rest = $bits % 8;
if ( 0 === $rest ) {
return true;
}
$mask = ( 0xFF << ( 8 - $rest ) ) & 0xFF;
return ( ord( $ipBin[ $fullBytes ] ) & $mask ) === ( ord( $netBin[ $fullBytes ] ) & $mask );
}
}