Is there a pre-existing function or code I can use to compute a TCP segment checksum in a POSIX program

北城以北 提交于 2019-12-24 21:44:02

问题


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 ?


回答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);
}


来源:https://stackoverflow.com/questions/9803201/is-there-a-pre-existing-function-or-code-i-can-use-to-compute-a-tcp-segment-chec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!