-1

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.

  • this guy said it better than I could: https://stackoverflow.com/questions/18070977/little-endian-bitfield-and-big-endian-bitfield hope this helps – Farkash Jan 16 '21 at 20:31
  • @Farkash Thank you for replay it means a lot. here my question is if we google IP frame format the first field is version so in case of little endian the first 4 bits should be version field right? why 'ihl' came first? in this case first 4 bits will be taken as 'ihl' not the version as in frame format. – Prasanna JS Jan 16 '21 at 20:49
  • Does this answer your question? [Why bit endianness is an issue in bitfields?](https://stackoverflow.com/questions/6043483/why-bit-endianness-is-an-issue-in-bitfields) – jwdonahue Jan 16 '21 at 21:04

1 Answers1

0

One way to understand this is by referring to the IP header, here is a link to an ip header.

ihl field is the first ever field of the IP header therefore it needs to be read first when reading the IP header:

  • Big endian: The most significant byte (which is ihl) is stored first. Thus logically the ihl field will be defined first so it can be stored first in memory
  • Little endian: The least significant byte (which is version) is stored first. Thus version field will be defined before ihl.
Kornee
  • 96
  • 5