FUnneR

r2

Jun 30th, 2017
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. /* IP CHECKSUM VERIFICATION */
  2. printf("Verifying IP checksum...\n");
  3. unsigned short ip_checksum = calculate_checksum((unsigned short*)ih, ih->header_length*4/2);
  4.  
  5. if(ip_checksum == 0)
  6. printf("IP checksum -> OK (0x%.2x)\n", ip_checksum);
  7. else
  8. printf("IP checksum -> BAD (0x%.2x)\n", ip_checksum);
  9.  
  10.  
  11. /* UDP CHECKSUM CALCULATION */
  12.  
  13. // Calculate size of (IP pseudo header + UDP datagram)
  14. int data_length = 12 + ntohs(uh->datagram_length); // Length of pseudo header + length of datagram
  15. data_length = data_length + data_length % 2; // Check sum have to be even number
  16.  
  17. // Dynamic allocate memory of checksum data
  18. unsigned char* checksum_data = (unsigned char*)malloc(data_length);
  19. memset(checksum_data, 0, data_length);
  20.  
  21. // Copy IP pseudo header
  22. memcpy(checksum_data, ih->src_addr, 4); // IP: Source Address (4 bytes)
  23. memcpy(checksum_data + 4, ih->dst_addr, 4); // IP: Destination Address (4 bytes)
  24. // IP: Reserved - all 0's (1 byte)
  25. checksum_data[9] = ih->next_protocol; // IP: Next Protocol (1 byte)
  26. memcpy(checksum_data + 10, &(uh->datagram_length), 2); // UDP: Datagram Length (2 bytes)
  27. // --------------------- = 12 bytes
  28. // Copy UDP datagram (header + application data)
  29. memcpy(checksum_data + 12, uh, ntohs(uh->datagram_length));
  30.  
  31. // Initialize UDP checksum
  32. memset(checksum_data + 18, 0, 2); // 18 = 12 (pseudo header) + 6 (position in udp header)
  33.  
  34. printf("Calculating UDP checksum...\n");
  35. unsigned short udp_checksum = calculate_checksum((unsigned short*)checksum_data, data_length/2);
  36. printf("UDP checksum: %.2x\n\n", udp_checksum);
  37.  
  38. // Free dynamic alocated memory
  39. free(checksum_data);
  40. }
  41.  
  42. // Calculates checksum for given data
  43. unsigned short calculate_checksum(unsigned short * data, int data_length)
  44. {
  45. unsigned int sum = 0;
  46.  
  47. // Calculate sum of 16bits values
  48. for(int i = 0; i < data_length; i++)
  49. {
  50. sum += ntohs(*(data + i));
  51. }
  52.  
  53. unsigned int carry;
  54.  
  55. // Carry will be added to the rest of the value
  56. while (carry = sum >> 16)
  57. {
  58. sum = sum & 0x0000FFFF;
  59. sum = sum + carry;
  60. }
  61.  
  62. // Flip every bit in that value, to obtain the checksum
  63. unsigned short checksum = ~(unsigned short)sum;
  64.  
  65. return checksum;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment