Nicolas Bontempo
Nicolas Bontempo

Reputation: 191

Ip Struct C parameters

I have started one adventure in raw sockets and I found one ip header that I don't understand, my doubt is

This two points four are used for what?

What is this 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__));

Upvotes: 3

Views: 1364

Answers (3)

DaoWen
DaoWen

Reputation: 33019

This struct represents a data packet that is going to be sent over the network, so you don't want to waste a single bit of space (since every bit needs to be sent over the "wire").

The field_name:field_width syntax declares a bit field, so uint8_t hdrlen:4; means that you actually only want 4 bits to store the "header length" value (but the compiler will make sure the value is copied into a uint8_t (one byte) when you read the field value).

The __attribute__((__packed__)) syntax tells the compiler to ignore the usual alignment requirements for structs. The compiler is sometimes required to insert padding between struct fields in order to ensure efficient memory access to the fields in the struct. For example, if you have a uint64_t right after a uint8_t, the compiler would insert padding (garbage) between the two fields to ensure that the uint64_t starts on an 8-byte boundary (i.e., the last 3 bits of the pointer address are all zero).

As you can see, all of this bit-twiddling and packing is done so that there is no wasted space in this struct, and every bit that is sent over the network is meaningful.

Upvotes: 4

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

This two points four are used for what?

This "two points four" is the way to specify bit-fielded variables. It basically asks to use that many bits (here, 4) to represent the value of the variable.

More on this : Previous answer

What is this attribute?

This is a special property, using which it is indicated that there should be no padding among the structure member variables. In general, __attribute__ is used to help the compiler to optimize certain properties of functions and/or variables.

More on this:

  1. GNU docs on Variable-attributes
  2. Structure padding

Upvotes: 0

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

There is some padding in structs that is required for alignment requirements, packed attribute removes the padding.

Upvotes: 0

Related Questions