将IPv6地址与CIDR子网匹配 [英] Matching IPv6 address to a CIDR subnet

查看:842
本文介绍了将IPv6地址与CIDR子网匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种使用CIDR表示法将IPv6地址与IPv6子网匹配的好方法?
我要找的是与此等价的IPv6:
在PHP 5中将IP匹配到CIDR掩码?

Is there a good way to match an IPv6 address to an IPv6 subnet using CIDR notation? What I am looking for is the IPv6 equivalent to this: Matching an IP to a CIDR mask in PHP 5?

由于IPv6地址是,因此无法使用上面给出的示例128位长,防止按位左移正常工作。你能想到其他任何方式吗?

The example given above can't be used since an IPv6 address is 128 bits long, preventing the bitwise left-shift from working properly. Can you think of any other way?

编辑:在答案列表中添加了我自己的解决方案。

Added my own solution to the list of answers.

推荐答案

由于您无法将IPv6地址转换为整数,因此您应该操作位,如下所示:

Since you cannot convert IPv6 addresses to integer, you should operate bits, like this:

$ip='21DA:00D3:0000:2F3B:02AC:00FF:FE28:9C5A';
$cidrnet='21DA:00D3:0000:2F3B::/64';

// converts inet_pton output to string with bits
function inet_to_bits($inet) 
{
   $unpacked = unpack('A16', $inet);
   $unpacked = str_split($unpacked[1]);
   $binaryip = '';
   foreach ($unpacked as $char) {
             $binaryip .= str_pad(decbin(ord($char)), 8, '0', STR_PAD_LEFT);
   }
   return $binaryip;
}    

$ip = inet_pton($ip);
$binaryip=inet_to_bits($ip);

list($net,$maskbits)=explode('/',$cidrnet);
$net=inet_pton($net);
$binarynet=inet_to_bits($net);

$ip_net_bits=substr($binaryip,0,$maskbits);
$net_bits   =substr($binarynet,0,$maskbits);

if($ip_net_bits!==$net_bits) echo 'Not in subnet';
else echo 'In subnet';

此外,如果您使用某个数据库来存储IP,它可能已经拥有了比较它们的所有功能。例如,Postgres有一个inet类型,可以确定IP是否包含在子网中,如下所示:

Also, if you use some database to store IPs, it may already have all the functions to compare them. For example, Postgres has an inet type and can determine, whether IP is contained within subnet like this:

SELECT 
   '21DA:00D3:0000:2F3B:02AC:00FF:FE28:9C5A'::inet << 
   '21DA:00D3:0000:2F3B::/64'::inet;

9.11。 PostgreSQL中的网络地址函数和操作符

这篇关于将IPv6地址与CIDR子网匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆