I'm using PHP to compare the user IP address to a list of IP blocks, most of which are IPv4 but some of them are IPv6. The IP address I get from the user is always IPv4 compatible, or so I'm assuming. How would I go about comparing this?
This is what I'm using now:
function ip_check($ip, $cidr) {
list($net, $mask) = split("/", $cidr);
$ip_address = decbin(ip2long($ip));
$ip_net = decbin(ip2long($net));
if (substr($ip_net, 0, $mask) == substr($ip_address, 0, $mask)) {
return TRUE;
}
return FALSE;
}
Edit: As an example I need to see if 194.144.247.254 belongs to 2001:067c:006c::/48 or 2001:1a98::/32 or 217.151.176.18/32 or 217.171.208.0/20.
I've written a library to do this sort of IP address comparison.
$ip = IP_Address::factory($ip);
$block = IP_Network_Address::factory($cidr);
return $block->encloses_address($ip);
The class hierarchy is a bit obtuse because it's designed to enable Kohana's transparent extension.
I've not implemented the code to convert an IPv4 address to a special previxed IPv6 address, so you may have to do a small amount of checking before the comparison.
Pull requests are of course welcomed :)
As an example I need to see if 194.144.247.254 belongs to
2001:067c:006c::/48 or 2001:1a98::/32 or 217.151.176.18/32 or
217.171.208.0/20.
How can a IPv4 address belong to a IPv6 range? You can only compare the same kind of addresses this way. The other thing makes no sense.