簡體   English   中英

無法驗證 TCP 校驗和

[英]Unable to verify TCP checksum

我一直在使用原始 sockets 在 C 中創建自定義 TCP 數據包。 為了驗證,我將它們發送到環回接口,當我使用 TCPDUMP 檢查接收到的數據包時,校驗和與 TCP 數據包不匹配。 以下是 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)));

這是 random_id function:

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

校驗和由 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);
}

是否有默認的 function 來計算tcpchecksum中的 tcpchecksum?

我知道沒有默認的 function 用於計算ip / tcp校驗和。 可以通過以下代碼找到:

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

其中輸入, buf如果數據用偽header。

僅當數據包僅通過localhost時才需要此計算。 如果它將網卡傳遞到外部網絡,請將sum字段留空。 網卡會自動計算 header 值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM