【问题标题】:PHP5 calculate IPv6 range from cidr prefix?PHP5从cidr前缀计算IPv6范围?
【发布时间】:2012-04-22 12:54:24
【问题描述】:

我可以使用来自各种在线资源的代码 sn-ps 对 IPv4 执行此操作。我想知道是否有办法用 IPv6 做到这一点。

基本上我只需要一个可以输入 IPv6 地址和前缀(例如:address/68)的表格,它会计算网络地址、第一个可用地址、最后一个可用地址和广播地址。然后只是打印到屏幕上。还不打算将其存储在数据库或任何东西中。

我该怎么做呢?

提前感谢大家!

【问题讨论】:

    标签: php ipv6 prefix cidr


    【解决方案1】:

    首先:IPv6 没有网络和广播地址。您可以在前缀中使用所有地址。第二:在 LAN 上,前缀长度总是(嗯,99.x% 的时间)a /64。路由 /68 会破坏 IPv6 功能,例如无状态自动配置。

    下面是 IPv6 前缀计算器的详细实现:

    <?php
    
    /*
     * This is definitely not the fastest way to do it!
     */
    
    // An example prefix
    $prefix = '2001:db8:abc:1400::/54';
    
    // Split in address and prefix length
    list($firstaddrstr, $prefixlen) = explode('/', $prefix);
    
    // Parse the address into a binary string
    $firstaddrbin = inet_pton($firstaddrstr);
    
    // Convert the binary string to a string with hexadecimal characters
    # unpack() can be replaced with bin2hex()
    # unpack() is used for symmetry with pack() below
    $firstaddrhex = reset(unpack('H*', $firstaddrbin));
    
    // Overwriting first address string to make sure notation is optimal
    $firstaddrstr = inet_ntop($firstaddrbin);
    
    // Calculate the number of 'flexible' bits
    $flexbits = 128 - $prefixlen;
    
    // Build the hexadecimal string of the last address
    $lastaddrhex = $firstaddrhex;
    
    // We start at the end of the string (which is always 32 characters long)
    $pos = 31;
    while ($flexbits > 0) {
      // Get the character at this position
      $orig = substr($lastaddrhex, $pos, 1);
    
      // Convert it to an integer
      $origval = hexdec($orig);
    
      // OR it with (2^flexbits)-1, with flexbits limited to 4 at a time
      $newval = $origval | (pow(2, min(4, $flexbits)) - 1);
    
      // Convert it back to a hexadecimal character
      $new = dechex($newval);
    
      // And put that character back in the string
      $lastaddrhex = substr_replace($lastaddrhex, $new, $pos, 1);
    
      // We processed one nibble, move to previous position
      $flexbits -= 4;
      $pos -= 1;
    }
    
    // Convert the hexadecimal string to a binary string
    # Using pack() here
    # Newer PHP version can use hex2bin()
    $lastaddrbin = pack('H*', $lastaddrhex);
    
    // And create an IPv6 address from the binary string
    $lastaddrstr = inet_ntop($lastaddrbin);
    
    // Report to user
    echo "Prefix: $prefix\n";
    echo "First: $firstaddrstr\n";
    echo "Last: $lastaddrstr\n";
    
    ?>
    

    它应该输出:

    Prefix: 2001:db8:abc:1400::/54
    First: 2001:db8:abc:1400::
    Last: 2001:db8:abc:17ff:ffff:ffff:ffff:ffff
    

    【讨论】:

    • 正是我需要的!!。几天来,我一直在努力解决这个问题,我目前正在学习 cisco 课程,但我们还没有达到 ipv6,所以我试图自己掌握这个概念。我一直在查看代码,如果我还想要第二个 IP 和最后一个 IP 之前的 IP,需要做多少代码更改?我一直试图弄清楚,但超出了我的 php 知识范围:(
    • 嗯,第二个地址的最后一个字符是 1 而不是 0,倒数第二个地址是 e 而不是 f。
    • 对不起,这几天一直很忙,我试图得到第二个 IP 的答案,倒数第二个大声笑......仍在学习 ipv6,但肯定从你的 cmets 学到了很多东西。再次感谢你!很抱歉我的回复延迟了。
    • 实际上您的代码完全按照我的需要工作:)。我正在寻找的变化是由于我缺乏知识:)。再次感谢!
    • 有关信息,我看到您的回答对 PhpMyAdmin 代码有贡献;)github.com/phpmyadmin/phpmyadmin/blob/…
    【解决方案2】:

    对于那些偶然发现这个问题的人,您可以使用GitHub 上的dtr_pton 和dtr_ntop 函数和dTRIP 类更有效地做到这一点。

    我们也注意到 PHP 中缺乏对 IPv6 的关注和工具,因此将这篇文章放在一起,http://www.highonphp.com/5-tips-for-working-with-ipv6-in-php,可能对其他人有所帮助。

    函数来源

    这会将 IP 转换为二进制表示:

    /**
     * dtr_pton
     *
     * Converts a printable IP into an unpacked binary string
     *
     * @author Mike Mackintosh - mike@bakeryphp.com
     * @param string $ip
     * @return string $bin
     */
    function dtr_pton( $ip ){
    
        if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)){
            return current( unpack( "A4", inet_pton( $ip ) ) );
        }
        elseif(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)){
            return current( unpack( "A16", inet_pton( $ip ) ) );
        }
    
        throw new \Exception("Please supply a valid IPv4 or IPv6 address");
    
        return false;
    }
    

    这会将二进制表示转换为可打印的 IP:

    /**
     * dtr_ntop
     *
     * Converts an unpacked binary string into a printable IP
     *
     * @author Mike Mackintosh - mike@bakeryphp.com
     * @param string $str
     * @return string $ip
     */
    function dtr_ntop( $str ){
        if( strlen( $str ) == 16 OR strlen( $str ) == 4 ){
            return inet_ntop( pack( "A".strlen( $str ) , $str ) );
        }
    
        throw new \Exception( "Please provide a 4 or 16 byte string" );
    
        return false;
    }
    

    示例

    使用dtr_pton 函数,您可以:

    $ip = dtr_pton("fe80:1:2:3:a:bad:1dea:dad");
    $mask = dtr_pton("ffff:ffff:ffff:ffff:ffff:fff0::");
    

    获取您的网络和广播:

    var_dump( dtr_ntop( $ip & $mask ) );
    var_dump( dtr_ntop( $ip | ~ $mask ) );
    

    您的输出将是:

    string(18) "fe80:1:2:3:a:ba0::"
    string(26) "fe80:1:2:3:a:baf:ffff:ffff"
    

    【讨论】:

    • IPv6 不支持广播,因此没有广播地址的概念。
    • @Steve-o 没错,但是由于广播这个词在网络中已经使用了很长时间,所以在 IPv6 中强调范围时,人们更容易理解。这类似于子网段,但许多网络远远超出该段..
    • 博客文章的链接已失效。你能更新或删除它吗?
    【解决方案3】:

    好吧,为了后代,我在这里添加我的code。同时也感谢你们帮助我解决这个问题,因为我需要它来编写 ipv6/ip2country 脚本。

    受到@mikemacintosh 和@Sander Steffann 在这里发布的代码的启发,略有改进(异想天开) em> 并返回一个很好的对象,包含您需要/不需要的所有数据:

    /**
    * This:
    * <code>
    * Ipv6_Prefix2Range('2001:43f8:10::/48');
    * </code>
    * returns this:
    * <code>
    * object(stdClass)#2 (4) {
    *   ["Prefix"]=>
    *   string(17) "2001:43f8:10::/48"
    *   ["FirstHex"]=>
    *   string(32) "200143f8001000000000000000000000"
    *   ["LastHex"]=>
    *   string(32) "200143f80010ffffffffffffffffffff"
    *   ["MaskHex"]=>
    *   string(32) "ffffffffffff00000000000000000000"
    *   // Optional bin equivalents available
    * }
    * </code>
    * 
    * Tested against:
    * @link https://www.ultratools.com/tools/ipv6CIDRToRange
    * 
    * @param string $a_Prefix
    * @param bool $a_WantBins
    * @return object
    */
    function Ipv6_Prefix2Range($a_Prefix, $a_WantBins = false){
        // Validate input superficially with a RegExp and split accordingly
        if(!preg_match('~^([0-9a-f:]+)[[:punct:]]([0-9]+)$~i', trim($a_Prefix), $v_Slices)){
            return false;
        }
        // Make sure we have a valid ipv6 address
        if(!filter_var($v_FirstAddress = $v_Slices[1], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)){
            return false;
        }
        // The /## end of the range
        $v_PrefixLength = intval($v_Slices[2]);
        if($v_PrefixLength > 128){
            return false; // kind'a stupid :)
        }
        $v_SuffixLength = 128 - $v_PrefixLength;
    
        // Convert the binary string to a hexadecimal string
        $v_FirstAddressBin = inet_pton($v_FirstAddress);
        $v_FirstAddressHex = bin2hex($v_FirstAddressBin);
    
        // Build the hexadecimal string of the network mask
        // (if the manually formed binary is too large, base_convert() chokes on it... so we split it up)
        $v_NetworkMaskHex = str_repeat('1', $v_PrefixLength) . str_repeat('0', $v_SuffixLength);
        $v_NetworkMaskHex_parts = str_split($v_NetworkMaskHex, 8);
        foreach($v_NetworkMaskHex_parts as &$v_NetworkMaskHex_part){
            $v_NetworkMaskHex_part = base_convert($v_NetworkMaskHex_part, 2, 16);
            $v_NetworkMaskHex_part = str_pad($v_NetworkMaskHex_part, 2, '0', STR_PAD_LEFT);
        }
        $v_NetworkMaskHex = implode(null, $v_NetworkMaskHex_parts);
        unset($v_NetworkMaskHex_part, $v_NetworkMaskHex_parts);
        $v_NetworkMaskBin = inet_pton(implode(':', str_split($v_NetworkMaskHex, 4)));
    
        // We have the network mask so we also apply it to First Address
        $v_FirstAddressBin &= $v_NetworkMaskBin;
        $v_FirstAddressHex = bin2hex($v_FirstAddressBin);
    
        // Convert the last address in hexadecimal
        $v_LastAddressBin = $v_FirstAddressBin | ~$v_NetworkMaskBin;
        $v_LastAddressHex =  bin2hex($v_LastAddressBin);
    
        // Return a neat object with information
        $v_Return = array(
            'Prefix'    => "{$v_FirstAddress}/{$v_PrefixLength}",
            'FirstHex'  => $v_FirstAddressHex,
            'LastHex'   => $v_LastAddressHex,
            'MaskHex'   => $v_NetworkMaskHex,
        );
        // Bins are optional...
        if($a_WantBins){
            $v_Return = array_merge($v_Return, array(
                'FirstBin'  => $v_FirstAddressBin,
                'LastBin'   => $v_LastAddressBin,
                'MaskBin'   => $v_NetworkMaskBin,
            ));
        }
        return (object)$v_Return;
    }
    

    我喜欢函数和类,不喜欢实现了可重用功能的不可重用代码。

    PS:如果您发现问题,请回复我。我远非 IPv6 专家。

    【讨论】:

    【解决方案4】:

    这是对accepted answer 的修复,它错误地假定“第一个地址”应该与输入的字符串相同。相反,它需要有它的值modified via an AND operator 来对抗它的掩码。

    为了演示这个问题,考虑这个示例输入:2001:db8:abc:1403::/54

    Expected result:

    First: 2001:db8:abc:1400::
    

    实际结果:

    First: 2001:db8:abc:1403::
    

    计算给定 4 位序列的掩码的相关数学是:

    // Calculate the subnet mask. min() prevents the comparison from being negative
    $mask = 0xf << (min(4, $flexbits));
    
    // AND the original against its mask
    $newval = $origval & $mask;
    

    完整代码

    <?php
    
    /*
     * This is definitely not the fastest way to do it!
     */
    
    // An example prefix
    $prefix = '2001:db8:abc:1403::/54';
    
    // Split in address and prefix length
    list($addr_given_str, $prefixlen) = explode('/', $prefix);
    
    // Parse the address into a binary string
    $addr_given_bin = inet_pton($addr_given_str);
    
    // Convert the binary string to a string with hexadecimal characters
    $addr_given_hex = bin2hex($addr_given_bin);
    
    // Overwriting first address string to make sure notation is optimal
    $addr_given_str = inet_ntop($addr_given_bin);
    
    // Calculate the number of 'flexible' bits
    $flexbits = 128 - $prefixlen;
    
    // Build the hexadecimal strings of the first and last addresses
    $addr_hex_first = $addr_given_hex;
    $addr_hex_last = $addr_given_hex;
    
    // We start at the end of the string (which is always 32 characters long)
    $pos = 31;
    while ($flexbits > 0) {
        // Get the characters at this position
        $orig_first = substr($addr_hex_first, $pos, 1);
        $orig_last = substr($addr_hex_last, $pos, 1);
    
        // Convert them to an integer
        $origval_first = hexdec($orig_first);
        $origval_last = hexdec($orig_last);
    
        // First address: calculate the subnet mask. min() prevents the comparison from being negative
        $mask = 0xf << (min(4, $flexbits));
    
        // AND the original against its mask
        $new_val_first = $origval_first & $mask;
    
        // Last address: OR it with (2^flexbits)-1, with flexbits limited to 4 at a time
        $new_val_last = $origval_last | (pow(2, min(4, $flexbits)) - 1);
    
        // Convert them back to hexadecimal characters
        $new_first = dechex($new_val_first);
        $new_last = dechex($new_val_last);
    
        // And put those character back in their strings
        $addr_hex_first = substr_replace($addr_hex_first, $new_first, $pos, 1);
        $addr_hex_last = substr_replace($addr_hex_last, $new_last, $pos, 1);
    
        // We processed one nibble, move to previous position
        $flexbits -= 4;
        $pos -= 1;
    }
    
    // Convert the hexadecimal strings to a binary string
    $addr_bin_first = hex2bin($addr_hex_first);
    $addr_bin_last = hex2bin($addr_hex_last);
    
    // And create an IPv6 address from the binary string
    $addr_str_first = inet_ntop($addr_bin_first);
    $addr_str_last = inet_ntop($addr_bin_last);
    
    // Report to user
    echo "Prefix: $prefix\n";
    echo "First: $addr_str_first\n";
    echo "Last: $addr_str_last\n";
    

    输出:

    Prefix: 2001:db8:abc:1403::/54
    First: 2001:db8:abc:1400::
    Last: 2001:db8:abc:17ff:ffff:ffff:ffff:ffff
    
    

    【讨论】:

      猜你喜欢
      • 2023-04-07
      • 2015-04-20
      • 2020-10-19
      • 2017-08-30
      • 2016-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多