C 编程 TCP 校验和 [英] C Programming TCP Checksum

查看:13
本文介绍了C 编程 TCP 校验和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我数天以来一直无法为 TCP 校验和.我查看了 Internet 上的许多资源,但我所看到的示例都没有向您展示如何进行 TCP 校验和.我还查看了 RFC 文档,但仍然遇到问题:

I have been having trouble doing the checksum for TCP for several days now. I have looked at many sources on the Internet but none of the examples that I have seen show you how to do the TCP checksum. I have also looked at the RFC document and still I am having trouble:

下面是我用来生成校验和的代码:

Below is the code I am using to generate the checksum:

unsigned short checksum(unsigned short * buffer, int bytes)
{
    unsigned long sum = 0;
    unsigned short answer = 0;
    int i = bytes;
    while(i>0)
    {
            sum+=*buffer;
            buffer+=1;
            i-=2;
    }
    sum = (sum >> 16) + (sum & htonl(0x0000ffff));
    sum += (sum >> 16);
    return ~sum;
}

此函数适用于 IP 校验和.

This function works for the IP checksum.

下面是我为我的 TCP 标头制作的结构:

Below is the struct I have made for my TCP header:

struct tcp_header
{
    unsigned short tcp_sprt;
    unsigned short tcp_dprt;
    unsigned int tcp_seq;
    unsigned int tcp_ack;
    unsigned char tcp_res:4;
    unsigned char tcp_off:4;
    unsigned char tcp_flags;
    unsigned short tcp_win;
    unsigned short tcp_csum;
    unsigned short tcp_urp;
};

我一直在使用 Wireshark 来测试这些数据包,唯一错误的是校验和.

I have been using Wireshark to test these packets and the only thing wrong is the checksum.

最后是我用 TCP 标头和来自 IP 标头的信息加载的伪标头结构:

Finally here is the pseudo header struct that I load up with the TCP header and information from the IP header:

struct pseudoTcpHeader
{
    unsigned int ip_src;
    unsigned int ip_dst;
    unsigned char zero;//always zero
    unsigned char protocol;// = 6;//for tcp
    unsigned short tcp_len;
    struct tcp_header tcph;
};

一旦我用正确的信息加载了这个结构,我就会在整个伪头结构上使用校验和函数,并将 TCP 校验和分配给该值.你看到我提供的东西有什么问题吗?如果问题不在这里,那可能是我看不到的粗心错误.

Once I load up this struct with the correct information I then use the checksum function on the entire pseudo header struct and assign the TCP checksum to that value. Do you see anything wrong with what I have provided? If the problem isn't here it may be a careless error that I can't see.

推荐答案

我在 winpcap-users 邮件列表 应该解决 Greg 关于奇数长度数据的评论,并为您提供一些与您的代码进行比较的内容.

I found a fairly good example on the winpcap-users mailing list which should address Greg's comment about odd length data and give you something to compare your code against.

USHORT CheckSum(USHORT *buffer, int size)
{
    unsigned long cksum=0;
    while(size >1)
    {
        cksum+=*buffer++;
        size -=sizeof(USHORT);
    }
    if(size)
        cksum += *(UCHAR*)buffer;

    cksum = (cksum >> 16) + (cksum & 0xffff);
    cksum += (cksum >>16);
    return (USHORT)(~cksum);
}

这篇关于C 编程 TCP 校验和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆