Su Bit padding, union e struct anonime in C

Da c11 è possibile definire struct e union anonime.
Queste, combinate con il bit padding, permettono di creare codice estremamente flessibile.

struct tcp_packet {
    int source;
    int destination;
    int sequence_number;
    int acknowledgement_number;
    struct {
        union {
            struct {
                char data_offset:4;
                char reserved:4;
                union {
                    struct {
                        char cwr:1;
                        char ece:1;
                        char urg:1;
                        char ack:1;
                        char psh:1;
                        char rst:1;
                        char syn:1;
                        char fin:1;
                    };
                    char flags;
                }
            };
            short data_reserved_and_flag;
        };
    }
    short window_size;
    short checksum;
    short urgent_pointer;
    int* data;
}

Se prendiamo questa ad esempio abbiamo una struct che rappresenta il tipico pacchetto tcp (l’unico esempio che mi veniva).
La parte riguardante i flag può sembrare un pò articolata, ma un’esempio chiarisce subito.
Supponiamo di avere struct tcp_packet my_packet e che solo i flag syn ed ack siano settati, con la struct così definita possiamo accedere ai vari flag tramite il nome, oppure a tutti contemporaneamente.
my_packet.ack accede al field ad ack e quindi avrà valore 1.
my_packet.syn accede al syn ed anche lui sarà 1.
my_packet.urg invece avrà valore 0.
È possibile anche vedere tutti i flag contemporaneamente con my_packet.flags che avrà valore 00010010.

Pretty neat huh?

2 Likes

Super interessante @antofma97 :muscle: