gpt4 book ai didi

c - 无法验证 TCP 校验和

转载 作者:行者123 更新时间:2023-12-03 10:01:10 25 4
gpt4 key购买 nike

我一直在使用原始套接字在 C 中创建自定义 TCP 数据包。为了验证,我将它们发送到环回接口(interface),当我使用 TCPDUMP 检查接收到的数据包时,校验和与 TCP 数据包不匹配。以下是 TCP header 中的字段:

        tcp->th_sport = temp_port;      // The TCP structure. The source port, spoofed, we accept through the command line
tcp->th_dport = atoi(argv[2]); // The destination port, we accept through command line
tcp->th_seq = htonl(random_id()%1000);
tcp->th_ack = htonl(random_id()%1000);
tcp->th_off = 5;
tcp->th_flags = TH_SYN;
tcp->th_win = 10000;
tcp->th_sum = 0;
tcp->th_urp = 0;

//pseudo header for TCP checksum calculation
p_hdr->source = t1->s_addr;
p_hdr->dest = t2->s_addr;
p_hdr->reserved = 0;
p_hdr->protocol = IPPROTO_TCP; //TCP
p_hdr->tcp_size = sizeof(struct tcphdr);
memcpy(buffer2 + sizeof(struct pseudo_tcp_header) , tcp , sizeof(struct tcphdr) );
tcp->th_sum = htons(csum((unsigned short *) (buffer2 ), sizeof(struct tcphdr) + sizeof(struct pseudo_tcp_header)));
这是 random_id 函数:
int random_id()
{
int lower = 1, upper = 65535,number;
number = (rand() % (upper - lower + 1)) + lower;
return number;
}
校验和由函数计算,
unsigned short csum(unsigned short *buf, int len)
{
unsigned long sum;
for(sum=0; len>0; len--)
sum += *buf++;
sum = (sum >> 16) + (sum &0xffff);
sum += (sum >> 16);
return (unsigned short)(~sum);
}
是否有默认函数来计算 tcpchecksum在 C 中?

最佳答案

我了解有没有计算 ip 的默认函数/tcp校验和。可以通过以下代码找到:

unsigned short csum(unsigned short *buf, int len)
{
unsigned long sum;
for(sum=0; len>0; len--)
sum += *buf++;
while (sum>>16)
sum = (sum >> 16) + (sum &0xffff);
return (unsigned short)(~sum);
}
输入, buf如果数据带有伪 header 。
仅当数据包仅遍历 localhost 时才需要此计算。 .如果是把网卡传到外网,留下 sum字段空白。网卡会自动计算头部值。

关于c - 无法验证 TCP 校验和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61475320/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com