Question

I can't find a clear-cut answer on best practices and alternatives for manipulating 128-bit binary (IPv6 IPs) and mixed IPv4/IPv6 in PHP.

I'm looking for clear information so I don't accidentally write subtle bugs into my code, which functions to use when (of the many functions I've seen discussed), and what (not) to rely on, in an IPv6 context. For example:

IPv6 can be manipulated via inet_pton() and the Net_IPv6 library (_bin2Ip, _Ip2bin). I've seen them cast explicitly as binary (pre PHP 5.4) (binary)inet_ntop() but no idea if that's important, manipulated using pack/unpack, and manipulated via normal bitwise operations ($ip | ~ $mask) and extended math (GMP bitwise handling). Some of these apply to IPv4 (eg inet_pton).

I've RTFM'ed but cannot find definitive tips and info on the subtleties of IPv6 IP handling.

  • Which conversion function or handling might one use in different circumstances?
  • Which of these functions are effectively the same?
  • Which are guaranteed to produce data that can be compared with > == < or not overflow PHP_INT_MAX?
  • Does inet_pton() have a guaranteed byte ordering (big/little endian) to allow IP ><= comparisons? (If not what's the best way - convert both to binary strings?)
  • I've also seen IPv4 manipulated using both ip2long($ip) and (int)sprintf('%u', ip2long($ip)) but unclear why one would work and the other not (context more likely x32 not x64)

I am trying to extend IPv4 handling code to IPv4/IPv6 (handling both equally) and this kind of info to write my code seems to be largely missing or unclear online.

So many similar functions, what are the differences and nuances between them?!

Help?

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top