0

I am writing a little POSIX program and I need to compute the checksum of a TCP segment, I would like use an existing function in order to avoid to writing one myself.

Something like (pseudocode) :

char *data = ....
u16_integer = computeChecksum(data);

I searched on the web but I did not find a right answer, any suggestion ?

Shane Wealti
  • 2,252
  • 3
  • 19
  • 33
pedr0
  • 2,941
  • 6
  • 32
  • 46
  • What are you trying to do? What do you mean by "the checksum"? You just want to be able to check if two large char arrays are equal with comparing them directly? – BoBTFish Mar 21 '12 at 11:09
  • No I don't. I have to fill the checksum field of an TCP segment – pedr0 Mar 21 '12 at 11:39
  • 1
    Possibly relevant? http://stackoverflow.com/questions/8845178/c-programming-tcp-checksum Doesn't avoid writing your own, but may show you how. – BoBTFish Mar 21 '12 at 11:43

1 Answers1

1

Here, it's taken more or less directly from the RFC:

uint16_t ip_calc_csum(int len, uint16_t * ptr)
{

        int sum = 0;
        unsigned short answer = 0;
        unsigned short *w = ptr;
        int nleft = len;

        while (nleft > 1) {
                sum += *w++;
                nleft -= 2;
        }

        sum = (sum >> 16) + (sum & 0xFFFF);
        sum += (sum >> 16);
        answer = ~sum;
        return (answer);
}
gby
  • 14,900
  • 40
  • 57