I'm implementing a custom network protocol that stays between the application and transport layer (UDP). The protocol split the application layer data to smaller chunks (packets) and encapsulates them with some header fields. The headers of the protocol look like this (let's just ignore what each field means for now):
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|Ver| Opt Len |O|C| Rsvd. | Protocol Type |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Ver
is 2 bits, Opt Len
is 6 bits, O
and C
are 1 bit each, Rsvd
is 6 bits and Protocol Type
is 16 bits. Let's say I have the values needed for each field.
How would I go about building this header string in C? I'm thinking of using bit shifting operators but I'm not sure how to go about it.
Also, if I received a packet of this protocol (with these header fields) as a string. How would I decapsulate that packet and get all the values of the header fields?