Advertisement
mdelatorre

Internet Checksum in C

Feb 11th, 2016
331
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.21 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. // Type definitions
  4. typedef unsigned short w16;  // 16-bit word is a short int
  5. typedef unsigned long w32;   // 32-bit word is a long int
  6.  
  7. // Prototypes
  8. w16 checksum(w16 len, w16 buff[]);
  9.  
  10. /*
  11. *************************************************************************hi
  12. Function: checksum
  13. Description: Calculate the 16 bit Internet Checksum.
  14. ***************************************************************************
  15. */
  16.  
  17. w16 checksum(w16 len, w16 buff[])
  18. {
  19. w16 word16;
  20. w32 sum=0;
  21. w16 i;
  22.  
  23. // make 16 bit words out of every two adjacent 8 bit words in the packet
  24. // and add them up
  25.  
  26. // u16 buff[] is an array containing all the octets in the data.
  27. for (i=0;i<len;i=i+2){
  28.     word16 =((buff[i]<<8)&0xFF00)+(buff[i+1]&0xFF);
  29.     sum = sum + (w32) word16;
  30. }
  31.  
  32. // take only 16 bits out of the 32 bit sum and add up the carries
  33. while (sum>>16)
  34.       sum = (sum & 0xFFFF)+(sum >> 16);
  35.  
  36. // one's complement the result
  37. sum = ~sum;
  38.  
  39. return ((w16) sum);
  40. }
  41. int main(void)
  42. {
  43.  
  44. w16 octets = 4;
  45. w16 result;
  46.    
  47.     w16 buffer[]={0xBE,0xBE,0xC0,0xCA};
  48.     result = checksum(octets,(w16 *)buffer);
  49.  
  50. // Output the checksum
  51.   printf("checksum = %04X \n", result);
  52.    
  53.     return(0);
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement