我的输入数据,例如:
$ip = '2001:db8::1428:54ab';
$prefix = 64; // 64 bits for addresses, 0 bits in addr ip
需要帮助!,如何通过擦除位来做这个逻辑,也许我需要使用另一个功能? thansk!
答案 0 :(得分:2)
难以理解的乱码是你要求的二进制数据: - )
以下是执行/64
的示例:
$address = '2001:db8:1234:abcd:aabb:ccdd:eeff:7711';
echo "Original: $address\n";
$address_bin = inet_pton($address);
$address_hex = bin2hex($address_bin);
echo "Address (hex): $address_hex\n";
// Getting the /64 is easy because it is on a byte boundary
$prefix_bin = substr($address_bin, 0, 8) . "\x00\x00\x00\x00\x00\x00\x00\x00";
$prefix_hex = bin2hex($prefix_bin);
echo "Prefix (hex): $prefix_hex\n";
$prefix_str = inet_ntop($prefix_bin);
echo "Prefix: $prefix_str/64\n";
这会给你:
Original: 2001:db8:1234:abcd:aabb:ccdd:eeff:7711
Address (hex): 20010db81234abcdaabbccddeeff7711
Prefix (hex): 20010db81234abcd0000000000000000
Prefix: 2001:db8:1234:abcd::/64
如果你想要任意前缀长度,那就更难了:
$address = '2001:db8:1234:abcd:aabb:ccdd:eeff:7711';
$prefix_len = 61;
echo "Original: $address\n";
$address_bin = inet_pton($address);
$address_hex = bin2hex($address_bin);
echo "Address (hex): $address_hex\n";
// If you want arbitrary prefix lengths it is more difficult
$prefix_bin = '';
$remaining_bits = $prefix_len;
for ($byte=0; $byte<16; ++$byte) {
// Get the source byte
$current_byte = ord(substr($address_bin, $byte, 1));
// Get the bit-mask based on how many bits we want to copy
$copy_bits = max(0, min(8, $remaining_bits));
$mask = 256 - pow(2, 8-$copy_bits);
// Apply the mask to the byte
$current_byte &= $mask;
// Append the byte to the prefix
$prefix_bin .= chr($current_byte);
// 1 byte = 8 bits done
$remaining_bits -= 8;
}
$prefix_hex = bin2hex($prefix_bin);
echo "Prefix (hex): $prefix_hex\n";
$prefix_str = inet_ntop($prefix_bin);
echo "Prefix: $prefix_str/$prefix_len\n";
这将显示:
Original: 2001:db8:1234:abcd:aabb:ccdd:eeff:7711
Address (hex): 20010db81234abcdaabbccddeeff7711
Prefix (hex): 20010db81234abc80000000000000000
Prefix: 2001:db8:1234:abc8::/61