Matching IPv6 address to a CIDR subnet

前端 未结 7 2191
长情又很酷
长情又很酷 2020-12-15 12:24

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

7条回答
  •  南方客
    南方客 (楼主)
    2020-12-15 13:16

    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');
    }
    

提交回复
热议问题