[英]RFC 1071 - Calculating IP header checksum confusion in C
我正在嘗試通過使用RFC 1071的示例C代碼來計算適當的IP標頭校驗和,但是有一個最好用代碼來描述的問題:
設置IP標頭:
#include <linux/ip.h>
typedef struct iphdr tipheader;
int main(int argc, char **argv)
{
tipheader * iphead = (tipheader *) malloc(sizeof(tipheader));
iphead->ihl = 5;
iphead->version = 4;
iphead->tos = 0;
iphead->tot_len = 60;
....
unsigned short checksum = getChecksum((unsigned short *) iphead, 20);
}
校驗和功能:
unsigned short getChecksum(unsigned short * iphead, int count)
{
unsigned long int sum = 0;
unsigned short checksum = 0;
printf("\nStarting adress: %p\n", iphead);
while(count > 1) {
sum += * (unsigned short *) (iphead);
count -=2;
printf("a: %p, content is: %d, new sum: %ld\n", iphead, (unsigned short) *(iphead), sum);
iphead++;
}
if(count > 0) {
sum += * (unsigned short *) (iphead);
}
while(sum >> 16) {
sum = (sum & 0xffff) + (sum >> 16);
}
checksum = ~sum;
return checksum;
}
在前兩次迭代之后,使用無符號短指針遍歷iphead指向的內存將顯示以下輸出:
Starting address: 0x603090
a: 0x603090, content is: 69, new sum: 69
a: 0x603092, content is: 60, new sum: 129
因此,指針“按預期”工作,並且每次迭代都增加2。 但是,為什么前兩個字節的內容解釋為69(0x45),其中應為0x4500
Thx的澄清
前兩個字段只有4位長,因此在內存中為0x4500。
但是,由於Endian'ness,它被讀取為0x0045。
打印時,除非另有強制,否則前導0被抑制。
所以結果是0x45 = 69
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.