ICMP Checksum, calculation

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



I've wanted to make a ping 'program' in PHP, so after reading up on this, it occured to me that the only difficult thing was to calculate the ICMP checksum. So after some heavy reading I could calculate this by pen and paper. And after some hours trying to make my calculations into PHP code, I discovered this piece of code in the online doc:

(by Khaless [at] bigpond [dot] com)
http://dk2.php.net/manual/en/ref.sockets.php
<?PHP
// Computes Internet Checksum for $data
// will return a 16-bit internet checksum for $data
function inetChecksum($data)
{
   // 32-bit accumilator, 16 bits at a time, adds odd bit on at end
   for($i=0;$i<strlen($data);$i += 2)
   {
       if($data[$i+1]) $bits = unpack('n*',$data[$i].$data[$i+1]);
       else $bits = unpack('C*',$data[$i]);
       $sum += $bits[1];
   }

   // Fold 32-bit sum to 16 bits
   while ($sum>>16) $sum = ($sum & 0xffff) + ($sum >> 16);
   $checksum = pack('n1',~$sum);
   return $checksum;
}
?>


Now, after discovering the unpack function it all became a lot easier, so I've made my own checksum calculator, which works approximatly 5 times as fast (and it dosn't have the for loop limitation of data length), and all the tests I've done it gives the same result as above:

<?php
function myChecksum($data)
{
    $bit = unpack('n*', $data);
    $sum = array_sum($bit);

    if (strlen($data)%2) {
        $temp = unpack('C*',$data[strlen($data)-1]);
        $sum += $temp[1];
    }

    // The next 2 lines of code, is stolen from the
    // original ping program written in C
    // Stolen code start:
    $sum = ($sum >> 16) + ($sum & 0xffff);
    $sum += ($sum >> 16);
    // End of stolen code

    return pack('n*', ~$sum);
}
?>

Can anyone tell me, if there will be any example, where the 2 functions wont give the same output? The piece of code I think could be the most trouble is the piece I've stolen, in the other function there's a while loop, so if I a very long data input, it wouldn't be the same output, but I've tried with large strings and they still give the same.


So to sum up, will the 2 functions always calculate the same.


--
Philip Birk-Jensen
URL:  http://birk-jensen.dk
ICQ:  14789099

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux