Search code examples
phpipv6

How can I check in PHP if 2 IPv6-Adresses are equal?


I want to check if an IP is whitelisted, but IPv6-Adresses can have different representations:

For example 2001:0DB8:0:0:1::1 is the short form of 2001:0db8:0000:0000:0001:0000:0000:0001.

Thus, string comparison doesn't work. How can I know two adresses are equal?


Solution

  • Use inet_pton.

    function is_ip_equal($ip1, $ip2) {
        return inet_pton($ip1) == inet_pton($ip2);
    }
    

    (However, this will only work if PHP was not compiled with --disable-ipv6 option. You can check this by using if (!defined('AF_INET6')) echo "IPv6 support was disabled";).