首页 > 其他 > 详细

IP checksum

时间:2020-04-23 14:47:24      阅读:68      评论:0      收藏:0      [点我收藏+]

To do an experiment, first capture an IP packet, as we can see the checksum is 0xCAD7. Then we set the checksum field to 0, and calculate the checksum, then we will get 0xCAD7. Set 0xCAD7 to the checksum field and calculate the checksum again, we will get 0 then.
技术分享图片

#include <bits/stdc++.h>
#define DBG(x) cerr << #x << " = " << x << endl

using namespace std;
typedef long long LL;

unsigned short ip_checksum(const vector<unsigned short> &v) {
    unsigned int sum = 0;
    for (int i = 0; i < v.size(); i++) {
        sum += v[i];
    }
    while (sum > 0xFFFF) {
        sum = (sum & 0xFFFF) + (sum >> 16);
    }
    return ~sum;
}

int main(int argc, char **argv) {

    vector<unsigned short> vec{0x4500, 0x0235, 0x0000, 0x4000, 0x4006, 0x0000, 0x0a01, 0xbf44, 0x8ba2, 0x1904};
    unsigned short sum = ip_checksum(vec);
    assert(sum == 0xcad7);
    printf("checksum = 0x%X\n", sum);

    vec[5] = sum;

    sum = ip_checksum(vec);
    assert(sum == 0);
    printf("%X\n", sum);
    return 0;
}

IP checksum

原文:https://www.cnblogs.com/ToRapture/p/12760541.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!