Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

class design on network packet parsing

I am looking for suggestions or design patterns to handle the parsing and generation of network packets (network or not by itself is not important per se). Each packet has a fixed length header and a variable length payload. The payload parsing will depend on the packet type. The straightforward way of doing this would be (assuming the input will come from a stream, console or network):

class Header {
public:
   Header(istream &);
   istream& read(istream &);
private:
   uint32_t type;
   uint32_t payload_length;
}

class PayloadTypeA {
public:
   PayloadTypeA {}
   istream& read(istream &);
private:
   uint32_t payload_1;
   uint32_t payload_2;
}

class PayloadTypeB {
 ...
}

The way I envision for the processing logic would be: read header first, then check the packet type, then decide which payload type to use to read the rest.

However, I feel this solution seems somewhat clumsy - I wonder if there is a better solution or design idioms I should follow?

thanks

Oliver

like image 268
Oliver Avatar asked Nov 21 '25 18:11

Oliver


1 Answers

Usually, your header is something like this:

Contents in brackets [ ] is header data

[Header length, Data Type,] Data

If you want, you can have a dynamic header (of variable length):

[Header Length, Number of Chunks, Size of chunk 1, Size of chunk 2, Size of chunk 3 etc, Data Type,] Data

You can create your own custom header to match whatever you're sending.

like image 147
Adrian Avatar answered Nov 23 '25 08:11

Adrian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!