我花了一些时间尝试计算UDP校验和,但每次我在Wireshark中观察数据包时,都会说校验和不正确。 这是代码:
img
正如我所说,当我将数据包发送到网络时,Wireshark报告(在接收端)校验和不正确。任何帮助将不胜感激。
谢谢。
答案 0 :(得分:0)
因为我不知道你在做什么,所有的结构我会给你一个参考校验和实现,希望它会帮助你找出你的东西:
#include <stdint.h>
#include <netinet/in.h>
struct udp {
uint16_t u_sport; /* source port */
uint16_t u_dport; /* dest port */
uint16_t u_len; /* length */
uint16_t u_chksum; /* checksum */
} __attribute__((packed));
uint16_t udp_checksum(const void *buffer, size_t length, in_addr_t src_addr, in_addr_t dest_addr)
{
const uint16_t *buf = buffer; /* treat input as bunch of uint16_t's */
uint16_t *src_ip = (void *) &src_addr;
uint16_t *dest_ip = (void *)&dest_addr;
uint32_t sum;
size_t len = length;
sum = 0;
/* fold the carry bits for the buffer */
while (length > 1) {
sum += *buf++;
if (sum & 0x80000000)
sum = (sum & 0xFFFF) + (sum >> 16); /* fold carries */
length -= 2;
}
if(length & 1)
sum += *((uint8_t *)buf); // add the padding if packet length is odd */
/* inject checksum of the pseudo-header */
sum += *(src_ip++);
sum += *(src_ip);
sum += *(dest_ip++);
sum += *(dest_ip);
sum += htons(IPPROTO_UDP); /* protocol info */
sum += htons(len); /* original length! */
/* fold any carry bits created by adding header sums */
while(sum >> 16)
sum = (sum & 0xFFFF) + (sum >> 16);
return (uint16_t)(~sum);
}