sockets - Ip Struct C parameters -


i have started 1 adventure in raw sockets , found 1 ip header don't understand, doubt is

  • hdrlen:4

this 2 points 4 used what?

  • attribute((packed));

what attribute?

struct iphdr {     uint8_t   hdrlen:4;     uint8_t   version:4;     uint8_t   ecn:2;       // explicit congestion notification - rfc 3168     uint8_t   dscp:6;      // diffserv code point     uint16_t  length;     uint16_t  ident;     uint16_t  fragoff:13;     uint16_t  flags:3;     uint8_t   ttl;     uint8_t   protocol;     uint16_t  checksum;     uint32_t  srcip;     uint32_t  dstip;     uint32_t  options[ ];  // present if hdrlen > 5 } __attribute__((__packed__)); 

this struct represents data packet going sent on network, don't want waste single bit of space (since every bit needs sent on "wire").

the field_name:field_width syntax declares bit field, uint8_t hdrlen:4; means want 4 bits store "header length" value (but compiler make sure value copied uint8_t (one byte) when read field value).

the __attribute__((__packed__)) syntax tells compiler ignore usual alignment requirements structs. compiler required insert padding between struct fields in order ensure efficient memory access fields in struct. example, if have uint64_t right after uint8_t, compiler insert padding (garbage) between 2 fields ensure uint64_t starts on 8-byte boundary (i.e., last 3 bits of pointer address zero).

as can see, of bit-twiddling , packing done there no wasted space in struct, , every bit sent on network meaningful.


Comments

Popular posts from this blog

android - Gradle sync Error:Configuration with name 'default' not found -

java - Andrioid studio start fail: Fatal error initializing 'null' -

html - jQuery UI Sortable - Remove placeholder after item is dropped -