Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* IP CHECKSUM VERIFICATION */
- printf("Verifying IP checksum...\n");
- unsigned short ip_checksum = calculate_checksum((unsigned short*)ih, ih->header_length*4/2);
- if(ip_checksum == 0)
- printf("IP checksum -> OK (0x%.2x)\n", ip_checksum);
- else
- printf("IP checksum -> BAD (0x%.2x)\n", ip_checksum);
- /* UDP CHECKSUM CALCULATION */
- // Calculate size of (IP pseudo header + UDP datagram)
- int data_length = 12 + ntohs(uh->datagram_length); // Length of pseudo header + length of datagram
- data_length = data_length + data_length % 2; // Check sum have to be even number
- // Dynamic allocate memory of checksum data
- unsigned char* checksum_data = (unsigned char*)malloc(data_length);
- memset(checksum_data, 0, data_length);
- // Copy IP pseudo header
- memcpy(checksum_data, ih->src_addr, 4); // IP: Source Address (4 bytes)
- memcpy(checksum_data + 4, ih->dst_addr, 4); // IP: Destination Address (4 bytes)
- // IP: Reserved - all 0's (1 byte)
- checksum_data[9] = ih->next_protocol; // IP: Next Protocol (1 byte)
- memcpy(checksum_data + 10, &(uh->datagram_length), 2); // UDP: Datagram Length (2 bytes)
- // --------------------- = 12 bytes
- // Copy UDP datagram (header + application data)
- memcpy(checksum_data + 12, uh, ntohs(uh->datagram_length));
- // Initialize UDP checksum
- memset(checksum_data + 18, 0, 2); // 18 = 12 (pseudo header) + 6 (position in udp header)
- printf("Calculating UDP checksum...\n");
- unsigned short udp_checksum = calculate_checksum((unsigned short*)checksum_data, data_length/2);
- printf("UDP checksum: %.2x\n\n", udp_checksum);
- // Free dynamic alocated memory
- free(checksum_data);
- }
- // Calculates checksum for given data
- unsigned short calculate_checksum(unsigned short * data, int data_length)
- {
- unsigned int sum = 0;
- // Calculate sum of 16bits values
- for(int i = 0; i < data_length; i++)
- {
- sum += ntohs(*(data + i));
- }
- unsigned int carry;
- // Carry will be added to the rest of the value
- while (carry = sum >> 16)
- {
- sum = sum & 0x0000FFFF;
- sum = sum + carry;
- }
- // Flip every bit in that value, to obtain the checksum
- unsigned short checksum = ~(unsigned short)sum;
- return checksum;
- }
Advertisement
Add Comment
Please, Sign In to add comment