前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >tcp/ip校验和计算

tcp/ip校验和计算

作者头像
战神伽罗
发布2019-09-03 20:08:36
1.2K0
发布2019-09-03 20:08:36
举报
文章被收录于专栏:Eureka的技术时光轴
代码语言:javascript
复制
#include <cassert>
#include <cstdlib>

#include "network.h"

unsigned short ChecksumTcpUdp(unsigned int saddr, unsigned int daddr,
        unsigned short len, unsigned char proto, const unsigned char *data)
{
    assert(NULL != data);

    const sniff_tcp *tcpHeader = (const sniff_tcp *)data;

    unsigned char protoStr[2] = { 0x00, proto };
    long sum = (saddr & 0xffff) + (saddr >> 16) + (daddr & 0xffff)
        + (daddr >> 16) + len + *(unsigned short *)protoStr;
 
    int count = ntohs(len);
 
    while (count > 1) {
        sum += *(unsigned short *)data;
        data += 2;
        count -= 2;
    }
    if (count > 0) {
        sum += *(unsigned char *)data;
    }
 
    /* Remove the existing checksum from result.
     */
    sum -= tcpHeader->th_sum;
 
    while (sum >> 16) {
        sum = (sum & 0xffff) + (sum >> 16);
    }
 
    return ~sum;
}
 
unsigned short ChecksumIp(const unsigned char *addr, int count)
{
    assert(NULL != addr);

    const sniff_ip *ipHeader = (const sniff_ip *)addr;

    long sum = 0;
    while (count > 1) {
        sum += *(unsigned short *)addr;
        addr += 2;
        count -= 2;
    }
    if (count > 0) {
        sum += *(unsigned char *)addr;
    }

    /* Remove the existing checksum from result.
     */
    sum -= ipHeader->ip_sum;

    while (sum >> 16) {
        sum = (sum & 0xffff) + (sum >> 16);
    }

    return ~sum;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档