【发布时间】:2015-06-26 04:53:28
【问题描述】:
我正在用 C 语言开发一个 Ubuntu 机器。
校验和计算代码如下:
unsigned short csum(unsigned short *buf, int nwords)
{
unsigned long sum;
for(sum=0; nwords>0; nwords=nwords-2){
sum += *buf;
//printf("%04x\n", *buf);
buf++;
}
if(nwords>0)
sum += *buf++;
while(sum >> 16)
sum = (sum >> 16) + (sum &0xffff);
/* sum += (sum >> 16);*/
return (unsigned short)(~sum);
}
不过,这对于 IP 和 ICMP 段运行良好,所以我非常怀疑这是问题所在。
为了找出问题所在,我目前正在捕获随机数据包,构建 tcp 标头部分的伪标头 + 深拷贝,然后打印出原始校验和和计算出的校验和。
struct tcphdr *tcph = (struct tcphdr *)(buffer + sizeof(struct ethhdr) + iphdrlen);
int tcphdrlen = size - sizeof(struct ethhdr) - iphdrlen;
int pseudo_len = sizeof(iph->saddr) + sizeof(iph->daddr) + 1 + sizeof(iph->protocol) + 2 + tcphdrlen;
test = (u_char *) malloc(pseudo_len);
memset(test, 0, pseudo_len);
memcpy(test, &(iph->saddr), sizeof(iph->saddr));
int pos = sizeof(iph->saddr);
memcpy(test + pos, &(iph->daddr), sizeof(iph->daddr));
pos += sizeof(iph->daddr);
memset(test + pos, 0, 1);
pos += 1;
memcpy(test + pos, &(iph->protocol), sizeof(iph->protocol));
int tcphdrlenhtons = htons(tcphdrlen);
pos += sizeof(iph->protocol);
memcpy(test + pos, &tcphdrlenhtons, 2);
pos += 2;
memcpy(test + pos, tcph, tcphdrlen);
struct tcphdr *t_tcph = (struct tcphdr *)(test + pos);
memset(&(t_tcph->check), 0, sizeof(t_tcph->check));
printf("correct tcp checksum: %d\n", ntohs(tcph->check));
printf("my tcp checksum: %d\n", ntohs((unsigned short) csum((unsigned short *)test, pseudo_len)));
在测试中,我发现计算出的校验和是正确的,但前提是数据包没有负载。
如果有人能告诉我我可能做错了什么,我将不胜感激。
【问题讨论】:
-
您可能在有效载荷校验和之前捕获数据包。将“TCP 校验和卸载”打入您最喜欢的搜索引擎。 (也可能是“TCP 分段卸载”。)
-
@David Schwartz 你是对的。谢谢。