Compress and expand IPv6 in PHP

0
1738
Compress and expand IPv6 in PHP
Compress and expand IPv6 in PHP

In this post, I will share with you a script I use to compress and expand IPv6 in PHP.

To compress IPv6 address:

function ipv6_compress($addr) {
    $result = inet_ntop(inet_pton($addr));
    return $result;
}

To expand IPv6 address:

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

Let’s test it out:

function test($addr) {
    $compressed = ipv6_compress($addr);
    echo "Compressed: " . $compressed . "\n";
    echo "Expanded: ". ipv6_expand($compressed) . "\n";
}

test("FE82:0:0:0:0:1A12:1234:1A12");
test("0:0:0:0:0:0:0:1");
test("::1");
test("2001:1234:0:0:1A12:0:0:1A13");

Once executing the script, it should show this output result:

Compressed: fe82::1a12:1234:1a12
Expanded: fe82:0000:0000:0000:0000:1a12:1234:1a12
Compressed: ::1
Expanded: 0000:0000:0000:0000:0000:0000:0000:0001
Compressed: ::1
Expanded: 0000:0000:0000:0000:0000:0000:0000:0001
Compressed: 2001:1234::1a12:0:0:1a13
Expanded: 2001:1234:0000:0000:1a12:0000:0000:1a13

That’s how you compress and expand IPv6 in PHP.

Have fun!