将IP地址与IPv6块进行比较 [英] Compare IP address to IPv6 block
问题描述
我正在使用PHP将用户IP地址与IP块列表进行比较,其中大多数是IPv4,但其中一些是IPv6。我从用户那里得到的IP地址总是与IPv4兼容,或者我假设是这样。我该如何比较呢?
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?
这就是我现在使用的:
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;
}
编辑:举个例子我需要看看 194.144.247.254 属于 2001:067c:006c :: / 48 或 2001:1a98 :: / 32 或 217.151.176.18/32 或 217.171.208.0/20 。
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.
推荐答案
我写过用于执行此类IP地址比较的库。
$ip = IP_Address::factory($ip);
$block = IP_Network_Address::factory($cidr);
return $block->encloses_address($ip);
类层次结构有点迟钝,因为它旨在启用Kohana的透明扩展。
The class hierarchy is a bit obtuse because it's designed to enable Kohana's transparent extension.
我没有实现将IPv4地址转换为特殊的普通IPv6地址的代码,因此您可能需要在比较之前进行少量检查。
当然欢迎拉请求:)
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 :)
这篇关于将IP地址与IPv6块进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!