#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/ip6.h>
#include <netinet/tcp.h>
unsigned short calculate_tcp_checksum(struct ip6_hdr *ip6hdr, struct tcphdr *tcphdr) {
unsigned short *buf;
unsigned int length = sizeof(struct tcphdr);
unsigned int sum = 0;
buf = (unsigned short *)tcphdr;
while (length > 1) {
sum += *buf++;
length -= 2;
}
if (length == 1) {
sum += *((unsigned char *)buf);
}
buf = (unsigned short *)&ip6hdr->ip6_src;
length = sizeof(struct in6_addr) * 2;
while (length > 1) {
sum += *buf++;
length -= 2;
}
if (length == 1) {
sum += *((unsigned char *)buf);
}
buf = (unsigned short *)&ip6hdr->ip6_dst;
length = sizeof(struct in6_addr) * 2;
while (length > 1) {
sum += *buf++;
length -= 2;
}
if (length == 1) {
sum += *((unsigned char *)buf);
}
sum += htons(IPPROTO_TCP + ntohs(tcphdr->th_len));
length = (unsigned int)ntohs(tcphdr->th_sum);
sum = ~((sum & 0xffff) + (sum >> 16));
sum += length;
sum = (sum >> 16) + (sum & 0xffff);
sum += (sum >> 16);
return (unsigned short)(~sum);
}
int main() {
struct ip6_hdr ip6hdr;
struct tcphdr tcphdr;
memset(&ip6hdr, 0, sizeof(ip6hdr));
memset(&tcphdr, 0, sizeof(tcphdr)); // 填充 IPv6 头部和 TCP 头部
unsigned short checksum = calculate_tcp_checksum(&ip6hdr, &tcphdr);
printf("TCP checksum: 0x%x\n", checksum);
return 0;
}
ipv6 checksum计算
于 2023-03-12 22:22:06 首次发布