Ben Ben - 1 year ago 249
PHP Question

Php convert ipv6 to number

In Ipv4 we can use

to convert it to number,

How to convert ipv6 compressed to number in PHP?

I tried inet_pton and it's not working.

echo inet_pton($ip_1);
echo inet_pton($ip_2);
//OUTPUT Warning: inet_pton(): Unrecognized address 2001:11ff:ffff:f

Answer Source

$ip_2 is not a valid IPv6 address. You need "::" somewhere in there, to indicate the zero omission point.

If you have it as one of


then inet_pton() should work fine.

As already hinted, PHP doesn't have a 128 integer type, so the best you can get is a numeric string out of the binary string inet_pton() gives you... yes, that's what it is, and that's why it looks weird. If you look at the bits of that strings, you'll see they're exactly what you'd expect.

Here's how to expand the binary string into a numeric string (argument "0" was missing from str_pad() originally):

 * @param string $ip A human readable IPv4 or IPv6 address.
 * @return string Decimal number, written out as a string due to limits on the size of int and float.
function ipv6_numeric($ip) {
    $binNum = '';
    foreach (unpack('C*', inet_pton($ip)) as $byte) {
        $binNum .= str_pad(decbin($byte), 8, "0", STR_PAD_LEFT);
    return base_convert(ltrim($binNum, '0'), 2, 10);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download