strlen( $ip_bin ) * 8 ) { return false; } $bytes = intdiv( $bits, 8 ); if ( substr( $ip_bin, 0, $bytes ) !== substr( $range_bin, 0, $bytes ) ) { return false; } $rest = $bits % 8; if ( 0 === $rest ) { return true; } $mask = ( 0xFF << ( 8 - $rest ) ) & 0xFF; return ( ord( $ip_bin[ $bytes ] ) & $mask ) === ( ord( $range_bin[ $bytes ] ) & $mask ); } /** * Anonymise an address for display: the last octet of IPv4, the last 80 bits of IPv6. * * @param string $ip Normalised IP. * @return string */ public static function anonymise( $ip ) { $packed = @inet_pton( $ip ); if ( false === $packed ) { return ''; } if ( 4 === strlen( $packed ) ) { return (string) inet_ntop( substr( $packed, 0, 3 ) . "\0" ); } return (string) inet_ntop( substr( $packed, 0, 6 ) . str_repeat( "\0", 10 ) ); } }