Search code examples
phpip-addressipv6

Quick way of expanding IPv6 Addresses with PHP


I am working on a project where I needed to expand IPv6 addresses. That is, given the input 2600:fc00:b0a3::34 I need to get 2600:fc00:b0a3:0000:0000:0000:0000:0034.

I found one piece of code that required the GMP extension, which I can't install. How can I fully expand an IPv6 address in PHP?


Solution

  • 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;
    }