Compare IP address to IPv6 block

不打扰是莪最后的温柔 提交于 2019-12-22 10:03:25

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/8836083/compare-ip-address-to-ipv6-block

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!