php判断ipv6是否在范围内,PHP5从cidr前缀计算IPv6范围?

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

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

/*

* 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值