简体   繁体   English

无法验证 TCP 校验和

[英]Unable to verify TCP checksum

I have been using raw sockets to create custom TCP packets in C.我一直在使用原始 sockets 在 C 中创建自定义 TCP 数据包。 To verify, I sent them to the loopback interface, and when I checked the received packets using TCPDUMP, the checksum did not match for the TCP packet.为了验证,我将它们发送到环回接口,当我使用 TCPDUMP 检查接收到的数据包时,校验和与 TCP 数据包不匹配。 Here are the fields in the TCP header:以下是 TCP header 中的字段:

        tcp->th_sport = temp_port;      // The TCP structure. The source port, spoofed, we accept through the command line
        tcp->th_dport = atoi(argv[2]);  // The destination port, we accept through command line
        tcp->th_seq = htonl(random_id()%1000);
        tcp->th_ack = htonl(random_id()%1000);
        tcp->th_off = 5;
        tcp->th_flags = TH_SYN;
        tcp->th_win = 10000;
        tcp->th_sum = 0;
        tcp->th_urp = 0;
        
        //pseudo header for TCP checksum calculation
        p_hdr->source = t1->s_addr;
        p_hdr->dest = t2->s_addr;
        p_hdr->reserved = 0;
        p_hdr->protocol = IPPROTO_TCP;  //TCP
        p_hdr->tcp_size = sizeof(struct tcphdr);
        memcpy(buffer2 + sizeof(struct pseudo_tcp_header) , tcp , sizeof(struct tcphdr) );
        tcp->th_sum = htons(csum((unsigned short *) (buffer2 ), sizeof(struct tcphdr) + sizeof(struct pseudo_tcp_header)));

This is the random_id function:这是 random_id function:

int random_id()
{
    int lower = 1, upper = 65535,number;
    number = (rand() % (upper - lower + 1)) + lower;
    return number;
}

And the checksum is computed by the function,校验和由 function 计算,

unsigned short csum(unsigned short *buf, int len)
{
    unsigned long sum;
    for(sum=0; len>0; len--)
        sum += *buf++;
    sum = (sum >> 16) + (sum &0xffff);
    sum += (sum >> 16);
    return (unsigned short)(~sum);
}

Is there a default function to compute the tcpchecksum in C?是否有默认的 function 来计算tcpchecksum中的 tcpchecksum?

I understand that there is no default function for calculating the ip / tcp checksum.我知道没有默认的 function 用于计算ip / tcp校验和。 It can be found by the following code:可以通过以下代码找到:

unsigned short csum(unsigned short *buf, int len)
{
    unsigned long sum;
    for(sum=0; len>0; len--)
        sum += *buf++;
    while (sum>>16)
        sum = (sum >> 16) + (sum &0xffff);
    return (unsigned short)(~sum);
}

Where the input, buf if the data with the pseudo header.其中输入, buf如果数据用伪header。

This calculation is only required if the data packet only traverses through the localhost .仅当数据包仅通过localhost时才需要此计算。 If it passes the network card to an external network, leave the sum field blank.如果它将网卡传递到外部网络,请将sum字段留空。 The network card will automatically compute the header value.网卡会自动计算 header 值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM