user3111525
user3111525

Reputation: 151

IPv6 conversion by prefix in PHP

My input data, for example:

$ip = '2001:db8::1428:54ab';
$prefix = 64; // 64 bits for addresses, 0 bits in addr ip
  1. first step, i use inet_pton($ip) to convert to bin representation
  2. then i need to erase last 64 bits, how can i do this ? when i echo inet_pton($ip) i get unreadable gibberish
  3. after erasing bits, i think we need to use inet_ntop function, to get readble hex address

Need help!, how can i do this logic by erasing bits, maybe i need to use another function? thansk!

Upvotes: 0

Views: 412

Answers (1)

Sander Steffann
Sander Steffann

Reputation: 9978

The unreadable gibberish is the binary data that you requested :-)

Here is an example for doing a /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";

This will give you:

Original: 2001:db8:1234:abcd:aabb:ccdd:eeff:7711
Address (hex): 20010db81234abcdaabbccddeeff7711
Prefix (hex):  20010db81234abcd0000000000000000
Prefix: 2001:db8:1234:abcd::/64

If you want arbitrary prefix lengths it is more difficult:

$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";

This will show:

Original: 2001:db8:1234:abcd:aabb:ccdd:eeff:7711
Address (hex): 20010db81234abcdaabbccddeeff7711
Prefix (hex):  20010db81234abc80000000000000000
Prefix: 2001:db8:1234:abc8::/61

Upvotes: 2

Related Questions