Reputation: 447
I'm reading a file in binary mode this way:
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);
while all the variables above are defined as the type in the 'sizeof()' function next to it. I'm trying to extract a specific part of the file and print it. the size of this part is 16 bit and it is defined like this:
uint16_t ip_len;
inside the type 'ip_hdr_t'. I looked at WireShark and saw the real value of this 16 bits and it is 0x0034.
I tried a two things:
printf("size of ip header: %hu\n", ip_header.ip_len);
which printed 13312 (as if the value of the bits is 0x3400)uint8_t ip_len;
uint8_t ip_len2;
and print it separately:
printf("size of ip header: %hu\n", ip_header.ip_len);
printf("size of ip header: %hu\n", ip_header.ip_len2);
this time i recieved the output: size of ip header: 0 (0x00) size of ip header: 52 (0x34) which is the right answer.
my question is: what did go wrong in the first print?
Thanks
Upvotes: 4
Views: 1858
Reputation: 272487
You have an endianness problem; your platform does not have the same endianness as the protocol you're using. You need to exchange the order of the bytes.
If you're on a POSIX-compliant system, you can use the ntoh
family of functions.
I'm not sure whether there's an equivalent for e.g. Windows.
Upvotes: 5