6

I was working on a project where I needed to expand IPv6 addresses. There are not many functions out there created by other users, and the ones that exist are ugly. Some of them included multiple foreach's and gmp_init, which added a lot of overhead and harder to maintain code. I need a simple, non-taxing script to expand IPv6.

Posting this for the community.

Mike Mackintosh
  • 13,917
  • 6
  • 60
  • 87

2 Answers2

32

The following is a two liner, where $ip is a condensed IPv6 address. Returns expanded $ip.

Example:

$ip = "fe80:01::af0";
echo expand($ip); // fe80:0001:0000:0000:0000:0000:0000:0af0

Function:

function expand($ip){
    $hex = unpack("H*hex", inet_pton($ip));         
    $ip = substr(preg_replace("/([A-f0-9]{4})/", "$1:", $hex['hex']), 0, -1);

    return $ip;
}
Mike Mackintosh
  • 13,917
  • 6
  • 60
  • 87
  • 1
    Could you add an example of `$ip`, like `echo expand($ip);` ? – j0k Aug 23 '12 at 16:14
  • Great ! Much interesting with an example :) – j0k Aug 23 '12 at 16:36
  • 2
    In all my years as a PHP developer, this is the best solution to functionality missing from the PHP core that I have ever seen (as are your dtr_pton / dtr_ntop functions). Beautifully simple and elegant. – zanbaldwin Aug 16 '13 at 06:23
  • 3
    Thank you, very elegant solution. I would suggest to write the second line as `return implode(':', str_split($hex['hex'], 4));`. Improves readability, avoid having to sanitise the extra colon with `substr` and avoid unecesssary use of regexp. – Yann Milin Dec 07 '17 at 09:38
3

With the help from Mike Mackintosh and Yann Milin I came up with this function:

function expandIPv6($ip) {
    $hex = bin2hex(inet_pton($ip));
    return implode(':', str_split($hex, 4));
}

Below a more universal function witch will also extract IPv4 from an IPv4-mapped IPv6 addresses:

function expandIPv6($ip) {
    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4))
        return $ip;
    elseif (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
        $hex = bin2hex(inet_pton($ip));
        if (substr($hex, 0, 24) == '00000000000000000000ffff') // IPv4-mapped IPv6 addresses
            return long2ip(hexdec(substr($hex, -8)));
        return implode(':', str_split($hex, 4));
    }
    return false;
}