Pejman Moghadam / C-programming

C - TCP/IP checksum function (RFC1071)

Public domain


Computing the Internet Checksum

#include <stdio.h>

unsigned short in_cksum(unsigned short *addr, int len)
{
        /* This is from RFC1071 */
        unsigned short checksum;
        register long sum = 0;

        /* Adding all 2-byte words */
        while (len > 1) {
                sum += *addr++;
                len -= 2;
        }

        /* Add left-over byte, if any */
        if (len > 0 )
                sum += *(unsigned char*) addr;

        /* Fold 32-bit sum to 16 bits */
        while (sum >> 16)
                sum = (sum & 0xFFFF) + (sum >> 16);

        /* Inverting the result */
        checksum = ~sum;
        return checksum;
}

main()
{
        unsigned short buffer[] = {
                0x4500, 0x0052, 0xefc0, 0x0000, 0x4311,
                0xDA77, 0x42DC, 0x9e7f, 0x2598, 0xa66f
        };

        printf("Checksum: 0x%X \n", in_cksum(buffer, 20));
        return 0;
}

BY: Pejman Moghadam
TAG: checksum, tcpip, rfc
DATE: 2014-01-10 23:59:28


Pejman Moghadam / C-programming [ TXT ]