Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare IP address to IPv6 block

Tags:

php

ip

ipv6

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.

like image 564
Karl Jóhann Avatar asked Dec 14 '25 16:12

Karl Jóhann


1 Answers

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 :)

like image 83
Lethargy Avatar answered Dec 17 '25 12:12

Lethargy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!