1 #include <stdio.h> 2 #include <string.h> 3 4 #define DATA_MAX_LEN 14 /* 最大数据长度 */ 5 6 struct data_sum 7 { 8 char data[DATA_MAX_LEN]; /* 数据 */ 9 unsigned short checksum; /* 校验和 */ 10 }; 11 12 unsigned short ip_checksum(unsigned short *buf, int buf_len) 13 { 14 unsigned long checksum = 0; 15 16 while (buf_len > 1) 17 { 18 checksum += *buf++; 19 buf_len -= sizeof(unsigned short); 20 } 21 22 if (buf_len) 23 { 24 checksum += *(unsigned char *)buf; 25 } 26 27 checksum = (checksum >> 16) + (checksum & 0xffff); 28 checksum += (checksum >> 16); 29 30 return (unsigned short)(~checksum); 31 } 32 33 int main(int argc, char **argv) 34 { 35 struct data_sum msg = { "adddddaa", 0 }; 36 int length = sizeof(msg); 37 38 printf("length = %d\n",length); 39 40 /* checksum = 0, 计算校验和 */ 41 msg.checksum = ip_checksum((unsigned short *)&msg, length); 42 printf("Calculate check sum : 0x%x\n", msg.checksum); 43 44 /* 包含 checksum 值, 验证校验和 */ 45 msg.checksum = ip_checksum((unsigned short *)&msg, length); 46 printf("Verify check sum : 0x%x\n", msg.checksum); 47 48 msg.data[0]=‘w‘; 49 /* 包含 checksum 值, 验证校验和 因为改变了其值,校验和不为0 */ 50 msg.checksum = ip_checksum((unsigned short *)&msg, length); 51 printf("Verify check sum : 0x%x\n", msg.checksum); 52 53 return 0; 54 }
时间: 2024-10-11 18:12:18