In Ipv4 we can use ip2long
to convert it to number,
How to convert ipv6 compressed to number in PHP?
I tried inet_pton and it’s not working.
$ip_1='2001:0db8:85a3:0000:0000:8a2e:0370:7334'; $ip_2='2001:11ff:ffff:f';//Compressed echo inet_pton($ip_1); //OUTPUT ИЃ.ps4 echo inet_pton($ip_2); //OUTPUT Warning: inet_pton(): Unrecognized address 2001:11ff:ffff:f
Advertisement
Answer
$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
$ip_2='2001::11ff:ffff:f'; $ip_2='2001:11ff::ffff:f'; $ip_2='2001:11ff:ffff::f';
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); } // $binNum is now a human readable string, but in binary. // If you have the gmp PHP extension, you can convert it to decimal return gmp_strval(gmp_init(ltrim($binNum, '0'), 2), 10); }