我正在以这种方式读取二进制模式的文件:
fread(&pcap_header ,sizeof(pcap_hdr_t ), 1 , pFile);
fread(&pcaprec_header ,sizeof(pcaprec_hdr_t ), 1 , pFile);
fread(ðer_header ,sizeof(ethernet_hdr_t ), 1 , pFile);
fread(&ip_header ,sizeof(ip_hdr_t ), 1 , pFile);
fread(&tcp_header ,sizeof(tcp_header_t ), 1 , pFile);
fread(&modbus_header ,sizeof(modbus_header_t ), 1 , pFile);
而上面的所有变量都被定义为它旁边的'sizeof()'函数中的类型。 我正在尝试提取文件的特定部分并进行打印。这部分的大小是 16 位,定义如下:
uint16_t ip_len;
在“ip_hdr_t”类型中。我查看了 WireShark,看到了这 16 位的实际值,它是 0x0034。
我尝试了两件事:
printf("size of ip header: %hu\n", ip_header.ip_len);
打印出 13312(好像位的值是 0x3400)- 将结构划分为两个 8 位变量:
uint8_t ip_len; uint8_t ip_len2;
并单独打印:printf("ip header 的大小: %hu\n", ip_header.ip_len); printf("ip header 的大小: %hu\n", ip_header.ip_len2);
这次我收到了输出:ip header 的大小:0 (0x00) IP header 的大小:52 (0x34) 这是正确答案。
我的问题是:第一次打印出了什么问题?
谢谢
最佳答案
你有一个 endianness问题;您的平台与您使用的协议(protocol)不具有相同的字节顺序。您需要交换字节的顺序。
如果您使用的是 POSIX 兼容系统,则可以使用 ntoh
family of functions .
我不确定是否有类似的东西,例如 window 。
关于c - 打印 uint16_t 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15501238/