PHP中的IPv6前缀转换
我的输入数据,例如:PHP中的IPv6前缀转换,php,ipv6,Php,Ipv6,我的输入数据,例如: $ip = '2001:db8::1428:54ab'; $prefix = 64; // 64 bits for addresses, 0 bits in addr ip 第一步,我使用inet\u pton($ip)转换为bin表示 然后我需要擦除最后的64位,我该怎么做?当我回显inet\u pton($ip)时,我会听到无法阅读的胡言乱语 在擦除位之后,我认为我们需要使用inet_ntop函数来获得可读的十六进制地址 需要帮助!,我如何通过擦除位来实现这个逻辑,也
$ip = '2001:db8::1428:54ab';
$prefix = 64; // 64 bits for addresses, 0 bits in addr ip
需要帮助!,我如何通过擦除位来实现这个逻辑,也许我需要使用另一个函数?坦斯克 无法读取的乱码是您请求的二进制数据:-) 下面是执行
/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