簡體   English   中英

兩種結構的TCP校驗和

[英]TCP checksum for two structures

我試圖創建一個為TCP生成校驗和的函數,但是我使用TCP的兩種結構,因為在tcp.h標頭中為Mac OS X制作的tcphdr結構不包含我制作數據包所需的所有內容。 我的數據包包含tcphdr結構和以下結構:

typedef struct tcp_option{
   u_int16_t mss_opt:8,
             mss_len:8;
   u_int16_t mss;
   u_int16_t sack_kind:8,
             sack_len:8;
   u_int16_t win_opt:8,
             win_len:8;
   u_int32_t win:8,
             win_nop:8,
             time_opt:8,
             time_len:8;
   u_int32_t time;
   u_int32_t time_echo;
} tcp_option;

因此,沒有人有想法進行校驗和以將該結構和tcphdr結構傳遞給它。

我的校驗和功能適用於IP校驗和,但不適用於其中具有兩種結構的TCP校驗和。 這是校驗和功能:

unsigned short checksum(const char *buf, unsigned size)
{
    unsigned long long sum = 0;
    const unsigned long long *b = (unsigned long long *) buf;

    unsigned t1, t2;
    unsigned short t3, t4;

    /* Main loop - 8 bytes at a time */
    while (size >= sizeof(unsigned long long))
    {
        unsigned long long s = *b++;
        sum += s;
        if (sum < s) sum++;
        size -= 8;
    }

    /* Handle tail less than 8-bytes long */
    buf = (const char *) b;
    if (size & 4)
    {
        unsigned s = *(unsigned *)buf;
        sum += s;
        if (sum < s) sum++;
        buf += 4;
    }

    if (size & 2)
    {
        unsigned short s = *(unsigned short *) buf;
        sum += s;
        if (sum < s) sum++;
        buf += 2;
    }

    if (size)
    {
        unsigned char s = *(unsigned char *) buf;
        sum += s;
        if (sum < s) sum++;
    }

    /* Fold down to 16 bits */
    t1 = sum;
    t2 = sum >> 32;
    t1 += t2;
    if (t1 < t2) t1++;
    t3 = t1;
    t4 = t1 >> 16;
    t3 += t4;
    if (t3 < t4) t3++;

    return ~t3;
}

我自己沒做,我從互聯網上偷了。

解決方案:我刪除了兩個結構並將其組合為一個結構,然后創建了一個偽頭結構,該結構用於進行校驗和!

您的結構在u_int_16_t成員之前有u_int_32_t成員的奇數,因此,為了確保32位成員正確對齊,它將在其中包含一個隱藏的16位塊,您將永遠無法通過成員引用進行設置,其內容將是不確定的。 因此,比較緩沖區中的每個16位字將包括比較該16位值。 如果您不使用某種方法來確保該空間的值始終相同,例如memset(0)結構,然后再為其成員分配值,那么您將不得不使用不同的比較過程(顯式比較成員) )

暫無
暫無

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

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