While I was experimenting on structure concept in C, I was checking how IP header was implemented so i just found in the internet the below declaration.
struct iphdr {
#if defined(__LITTLE_ENDIAN_BITFIELD)
__u8 ihl:4,
version:4;
#elif defined (__BIG_ENDIAN_BITFIELD)
__u8 version:4,
ihl:4;
#else
#error "Please fix <asm/byteorder.h>"
#endif
__u8 tos;
__u16 tot_len;
__u16 id;
__u16 frag_off;
__u8 ttl;
__u8 protocol;
__u16 check;
__u32 saddr;
__u32 daddr;
/*The options start here. */
};
I just want to know in case of little endian why ihl comes before version. w.r.t little endian the least significant bits will be stored at lower memory location in that case version could be defined first why it is defined after ihl.
I have done below expt please help me to understand.
#include<stdio.h>
struct my_iphdr {
unsigned char ver:4;
unsigned char ihl:4;
};
int main(void)
{
struct my_iphdr ip;
ip.ver = 0;
ip.ihl = 15;
char * ptr = &ip;
printf("%d\n", (unsigned char)*ptr);
return 0;
}
I am using little endian machine
Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Byte Order: Little Endian
CPU(s): 12
I have got the o/p 240 i.e 11110000 in that case the ver stored in lower bits and after de-reference I am able to see proper value then why ihl comes before ver.