0 && substr($ip_packed, 0, $bytes) !== substr($range_packed, 0, $bytes)) { return false; } if ($remainder === 0) { return true; } $mask = 0xFF << (8 - $remainder) & 0xFF; return (ord($ip_packed[$bytes]) & $mask) === (ord($range_packed[$bytes]) & $mask); } private static function in_ranges(string $ip, array $ranges): bool { foreach ($ranges as $range) { if (self::matches($ip, (string) $range)) { return true; } } return false; } /** * Canonical text form, with IPv4-mapped IPv6 turned back into IPv4. Some * proxies (Azure among them) add the port: "203.0.113.9:51234", "[2001:db8::1]:443". * Empty when invalid. */ private static function normalize(string $ip): string { if (preg_match('/^\[([0-9a-fA-F:.]+)\](?::\d+)?$/', $ip, $match)) { $ip = $match[1]; } elseif (preg_match('/^(\d{1,3}(?:\.\d{1,3}){3}):\d+$/', $ip, $match)) { $ip = $match[1]; } $packed = @inet_pton($ip); if ($packed === false) { return ''; } if (strlen($packed) === 16 && substr($packed, 0, 12) === str_repeat("\0", 10)."\xff\xff") { $packed = substr($packed, 12); } return (string) inet_ntop($packed); } }