Advertisement
Guest User

Untitled

a guest
Feb 25th, 2017
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.84 KB | None | 0 0
  1. uint16_t Icmp::create_checksum(uint16_t type_code) {
  2.     unsigned long checksum = 0;
  3.  
  4.     // Cast the data pointer to one that can be indexed.
  5.     unsigned char* data = raw_data.data();
  6.     size_t length = raw_data.size();
  7.  
  8.     // Initialise the accumulator.
  9.     uint32_t acc=0xffff;
  10.     acc += type_code;
  11.  
  12.     // Handle complete 16-bit blocks.
  13.     for (size_t i=0;i+1<length;i+=2) {
  14.         uint16_t word;
  15.         memcpy(&word,data+i,2);
  16.         acc+=(word);
  17.         if (acc>0xffff) {
  18.             acc-=0xffff;
  19.         }
  20.     }
  21.  
  22.     // Handle any partial block at the end of the data.
  23.     if (length&1) {
  24.         uint16_t word=0;
  25.         memcpy(&word,data+length-1,1);
  26.         acc+=(word);
  27.         if (acc>0xffff) {
  28.             acc-=0xffff;
  29.         }
  30.     }
  31.  
  32.     // Return the checksum in network byte order.
  33.     return (~acc);
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement