Skip to content
Advertisement

Php convert ipv6 to number

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.

JavaScript

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

JavaScript

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):

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement