Calculating the difference between two IPv6 addresses.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
kaisellgren
DevNet Resident
Posts: 1675
Joined: Sat Jan 07, 2006 5:52 am
Location: Lahti, Finland.

Calculating the difference between two IPv6 addresses.

Post by kaisellgren »

Hi,

I am trying to calculate the difference between two IPv6 addresses.

Here is what I have done so far:

Code: Select all

function diff($ip,$ip2)
 {
  $parts = explode(':',$ip);
  $value = 0;
  for ($a = 7;$a > 0;$a--)
   $value += hexdec($parts[$a]) * (pow(0xFFFF,7-$a));
  $parts = explode(':',$ip);
  $value2 = 0;
  for ($a = 7;$a > 0;$a--)
   $value2 += hexdec($parts[$a]) * (pow(0xFFFF,7-$a));
  return (abs($value-$value2));
 }
 
$ip = '2001:0db8:0000:0000:0000:0000:1420:57ab';
$ip2 = '2001:0db8:0000:0000:0000:0000:1420:57ac';
echo diff($ip,$ip2);
These two IPv6 addresses are same except for the last character - so the difference should be 1 in this case, but the script outputs 0. I think this is a rounding issue?
Post Reply