/* * Check if the IP belong to mask. Recursive. * Octet by octet for IPv4 * Hextet by hextet for IPv6 * @param ip string * @param cird mixed (string|array of strings) * @param ip_type string * @param cird mixed (string|array of strings) */ static public function ip__mask_match($ip, $cidr, $ip_type = 'v4', $xtet_count = 0){ if(is_array($cidr)){ foreach($cidr as $curr_mask){ if(self::ip__mask_match($ip, $curr_mask, $ip_type)){ return true; } } unset($curr_mask); return false; } if($ip_type == 'v4') $xtet_base = 8; if($ip_type == 'v6') $xtet_base = 16; // Calculate mask $exploded = explode('/', $cidr); // Exit condition $xtet_end = ceil($exploded[1] / $xtet_base); if($xtet_count == $xtet_end) return true; $mask = $exploded[1] - $xtet_base * $xtet_count >= 0 ? $xtet_base : $exploded[1] - $xtet_base * ($xtet_count - 1); $mask = 4294967295 << ($xtet_base - $mask); // Calculate first ip X-tet $ip_xtet = explode($ip_type == 'v4' ? '.' : ':', $ip); $ip_xtet = $ip_type == 'v4' ? $ip_xtet[$xtet_count] : hexdec($ip_xtet[$xtet_count]); // Calculate first net X-tet $net_xtet = explode($ip_type == 'v4' ? '.' : ':', $exploded[0]); $net_xtet = $ip_type == 'v4' ? $net_xtet[$xtet_count] : hexdec($net_xtet[$xtet_count]); $result = ($ip_xtet & $mask) == ($net_xtet & $mask); if($result) $result = self::ip__mask_match($ip, $cidr, $ip_type, $xtet_count + 1); return $result; }
Source: https://habr.com/ru/post/353716/
All Articles