0

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?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Mike Pham
  • 437
  • 6
  • 17
  • So it's a 32-bit integer. I doubt you would receive that as a string? You should be able to just use and masks and shifts to read each piece of data. – Michael Dorgan Aug 27 '20 at 18:56
  • Bit shifting and bitmasks as is tradition. – tadman Aug 27 '20 at 18:56
  • @MichaelDorgan I can receive that header as a string from UDP sockets. I'm sending to and receiving from UDP sockets. – Mike Pham Aug 27 '20 at 18:59
  • Define "string". I'd expect it just to be a buffer of some sort without NUL termination.... – Michael Dorgan Aug 27 '20 at 19:00
  • @mkrieger1 I'm not sure how I can use that for string manipulation though. Maybe I'm missing something here. – Mike Pham Aug 27 '20 at 19:03
  • @MichaelDorgan Say, I receive a UDP packet from a socket (e.g. using recvfrom). The data of that packet contains the header fields above. How would I strip the header fields of and get the data from those fields? – Mike Pham Aug 27 '20 at 19:07
  • 1
    Sorry, my comment was referring to building such a header. If you want to do the inverse, you need to use bit masks and shifting. See for example https://stackoverflow.com/questions/26359068/mask-and-extract-bits-in-c – mkrieger1 Aug 27 '20 at 19:13
  • @mkrieger1 Ahh I get it now. So if I have a string containing the headers, say `headers`, then I can get the `Ver` field by doing something like `(headers[0] & (0b11 << 6)) >> 6`? – Mike Pham Aug 27 '20 at 19:27
  • Yes, assuming you counted the bit positions correctly. – mkrieger1 Aug 27 '20 at 19:32

0 Answers0