将IPv6地址与CIDR子网匹配

时间:2011-10-31 07:47:44

标签: php ip ipv6 cidr

是否有一种使用CIDR表示法将IPv6地址与IPv6子网匹配的好方法? 我正在寻找的是与此等价的IPv6: Matching an IP to a CIDR mask in PHP 5?

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

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

7 个答案:

答案 0 :(得分:13)

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

$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是否包含在子网中,如下所示:

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

9.11. Network Address Functions and Operators in PostgreSQL

答案 1 :(得分:5)

您还可以使用IpUtils包中的symfony/http-foundation类:

IpUtils::checkIp6('2a01:8760:2:3001::1', '2a01:8760:2:3001::1/64')

这将检查IPv6有效性和范围匹配。如果不是这样,将返回false

答案 2 :(得分:3)

我使用以下代码创建了自己的解决方案:

function iPv6MaskToByteArray($subnetMask) {
  $addr = str_repeat("f", $subnetMask / 4);
  switch ($subnetMask % 4) {
    case 0:
      break;
    case 1:
      $addr .= "8";
      break;
    case 2:
      $addr .= "c";
      break;
    case 3:
      $addr .= "e";
      break;
  }
  $addr = str_pad($addr, 32, '0');
  $addr = pack("H*" , $addr);
  return $addr;
}

function iPv6CidrMatch($address, $subnetAddress, $subnetMask) {
  $binMask = iPv6MaskToByteArray($subnetMask);
  return ($address & $binMask) == $subnetAddress;
}

请注意,$ address和$ subnetAddress是通过inet_pton运行字符串地址获得的。按如下方式调用该函数:

$subnet = inet_pton("2001:06b8::");
$mask = 32;
$addr = inet_pton("2001:06b8:0000:0000:0000:0000:1428:07ab");
$match = iPv6CidrMatch($addr, $subnet, $mask); // TRUE

答案 3 :(得分:1)

如果你的面具总是被4整除(这在ipv6中很常见)。您可以使用:

function checkIPv6WithinRange($ipv6, $range) {
    list ($net, $mask) = preg_split("/\//", $range);

    if ($mask % 4)
        throw new NotImplementedException("Only masks divisible by 4 are supported");
    $stripChars = (128-$mask)/4;

    $hexNet = bin2hex(inet_pton($net));
    $reducedNet = substr($hexNet, 0, 0 - $stripChars);

    $hexIp = bin2hex(inet_pton($ipv6));
    $reducedIp = substr($hexIp, 0, 0 - $stripChars);

    return $reducedIp === $reducedNet;
}

答案 4 :(得分:1)

以下示例通过检查IP地址与IPv4和IPv6的单个IP或CIDR列表来运行:

https://gist.github.com/lyquix-owner/2620da22d927c99d57555530aab3279b

<?php
// IP to check
$ip_check = $_SERVER['REMOTE_ADDR'];

// Array of allowed IPs and subnets, both IPv4 and IPv6
$ips_allowed = array(
    '192.30.252.0/22'
    '2620:112:3000::/44'
    '192.168.16.104'
);

// Flag for IP match allowed list
$ip_match = false;

foreach($ips_allowed as $ip_allow) {
    // If IP has / means CIDR notation
    if(strpos($ip_allow, '/') === false) {
        // Check Single IP
        if(inet_pton($ip_check) == inet_pton($ip_allow)) {
            $allow = true;
            break;
        }
    }
    else {
        // Check IP range
        list($subnet, $bits) = explode('/', $ip_allow);

        // Convert subnet to binary string of $bits length
        $subnet = unpack('H*', inet_pton($subnet)); // Subnet in Hex
        foreach($subnet as $i => $h) $subnet[$i] = base_convert($h, 16, 2); // Array of Binary
        $subnet = substr(implode('', $subnet), 0, $bits); // Subnet in Binary, only network bits

        // Convert remote IP to binary string of $bits length
        $ip = unpack('H*', inet_pton($ip_check)); // IP in Hex
        foreach($ip as $i => $h) $ip[$i] = base_convert($h, 16, 2); // Array of Binary
        $ip = substr(implode('', $ip), 0, $bits); // IP in Binary, only network bits

        // Check network bits match
        if($subnet == $ip) {
            $allow = true;
            break;
        }
    }
}
if(!$allow) {
    die('IP not allowed');
}

答案 5 :(得分:1)

PHP可以对字符串执行按位运算!

  • IPv4或IPv6
  • 无基本转化
  • 没有ASCII位字符串
  • 相当快
<?php

/**
 * Does the given IP match the CIDR prefix?
 */
function matchIp(string $ip, string $cidr): bool
{
  // Get mask bits
  list($net, $maskBits) = explode('/', $cidr);

  // Size
  $size = (strpos($ip, ':') === false) ? 4 : 16;

  // Convert to binary
  $ip = inet_pton($ip);
  $net = inet_pton($net);
  if (!$ip || !$net) {
    throw new InvalidArgumentException('Invalid IP address');
  }

  // Build mask
  $solid = floor($maskBits / 8);
  $solidBits = $solid * 8;
  $mask = str_repeat(chr(255), $solid);
  for ($i = $solidBits; $i < $maskBits; $i += 8) {
    $bits = max(0, min(8, $maskBits - $i));
    $mask .= chr((pow(2, $bits) - 1) << (8 - $bits));
  }
  $mask = str_pad($mask, $size, chr(0));

  // Compare the mask
  return ($ip & $mask) === ($net & $mask);
}

答案 6 :(得分:0)

基本上http://www.phpclasses.org/browse/file/70429.html

要使用它,只需致电

$cidr = new CIDR();
$cidr->match($ipv6, $ipv6_in_cidr);

结果是“好”&#39;