Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert IPV6 to nibble format for PTR records

I need to convert a ipv6 address to its nibble format for use in creating ptr records dynamically. Here is the information I got from Wikipedia:

IPv6 reverse resolution

Reverse DNS lookups for IPv6 addresses use the special domain ip6.arpa. An IPv6 address appears as a name in this domain as a sequence of nibbles in reverse order, represented as hexadecimal digits as subdomains. For example, the pointer domain name corresponding to the IPv6 address 2001:db8::567:89ab is b.a.9.8.7.6.5.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa.

The only thing I could find regarding nibbles was in the pack function, http://www.php.net/pack. I could not find any solutions with examples from googling the issue.

Any help is greatly appreciated.

like image 299
Jason Brumwell Avatar asked Jul 08 '11 03:07

Jason Brumwell


1 Answers

Given a suitably modern version of PHP (>= 5.1.0, or 5.3+ on Windows), use the inet_pton function to parse the IPv6 address into a 16 byte array, and then use standard string ops to reverse it.

$ip = '2001:db8::567:89ab';
$addr = inet_pton($ip);
$unpack = unpack('H*hex', $addr);
$hex = $unpack['hex'];
$arpa = implode('.', array_reverse(str_split($hex))) . '.ip6.arpa';
like image 182
Alnitak Avatar answered Oct 14 '22 17:10

Alnitak