Ручное вычисление контрольной суммы TCP в C ++ - PullRequest
0 голосов
/ 04 марта 2020

Я использую pcap для захвата пакетов и теперь хочу вычислить контрольную сумму IP вручную.

struct sniff_ip {
    u_char  ip_vhl;                 /* version << 4 | header length >> 2 */
    u_char  ip_tos;                 /* type of service */
    u_short ip_len;                 /* total length */
    u_short ip_id;                  /* identification */
    u_short ip_off;                 /* fragment offset field */
    #define IP_RF 0x8000            /* reserved fragment flag */
    #define IP_DF 0x4000            /* dont fragment flag */
    #define IP_MF 0x2000            /* more fragments flag */
    #define IP_OFFMASK 0x1fff       /* mask for fragmenting bits */
    u_char  ip_ttl;                 /* time to live */
    u_char  ip_p;                   /* protocol */
    u_short ip_sum;                 /* checksum */
    struct  in_addr ip_src,ip_dst;  /* source and dest address */
};



 struct sniff_ip_16bit {
    u_short a;
    u_short b;
    u_short c;
    u_short d;
    u_short e;
    u_short f;
    u_short g;
    u_short h;
    u_short i;
    u_short j;

};

Я должен разделить заголовок IP на 16 бит, один дополняет их, а один дополняет результат .

Я сделал следующее, чтобы привести их к 16-битным фрагментам, и, наконец, просто сложил все эти элементы.

   ip->ip_sum = 0;
    sniff_ip_16bit* ip_crc = reinterpret_cast<sniff_ip_16bit*>(&ip);
    u_short ip_crc_calculated = ip_crc->a+ip_crc->b+ip_crc->c+ip_crc->d+ip_crc->e+ip_crc->f+ip_crc->g+ip_crc->h+ip_crc->i+ip_crc->j;
    std::cout << "MNL CRC:" << std::bitset<16>(~ip_crc_calculated) << std::endl;

Но все же я получаю неправильные результаты CR C, последние две строки.

    Packet number 4:
IP Header length : 20
       From: 127.0.0.1
         To: 127.0.0.1
   Protocol: TCP
Len : 66 CLen: 66
Seq: 3415166211
Ack: 458071927
   Src port: 45878
   Dst port: 8080
Payload empty
CRC TCP: 0010100011111110
IP ID: 55139
CRC IP: 1110101011011000 //original
MNL CRC:0100011001111000
...