The correct way to parse a network packet in C

(Sorry if I cannot correctly pose the question. English is not in my main language.)

I am trying to parse the SyncE ESMC package. This is a slow Ethernet protocol.

Approach 1: To parse this package, I used a byte byte approach similar to what was done here .

Approach 2: Another way of analyzing a package would be to define a structure to represent the entire package and access individual fields to get the value at a specific offset. However, in this structure of the approach to filling and aligning, an image may come (which I am not sure), but in Linux various package headers are defined in the form of a structure, for example. iphdr in ip.h. IP packets (buffer) can be injected into the iphdr type to retrieve the IP header fields, so it should work.

Which approach is better to parse a network packet in C?

Are there differences in structure and alimentation when parsing the package using approach 2? If so, how did the Linux headers overcome this problem?

+6
source share
1 answer

Approach 1 is best for portability. This allows, for example, to safely avoid incorrect access. In particular, if your machine is insignificant, this approach makes it very easy to take care of exchanging bytes.

Approach 2 is sometimes convenient and often writes code faster. If a structure is added in your path, your compiler probably provides a flag or attribute (e.g. __attribute__((__packed__)) or #pragma pack ) to get around it. However, if you have a machine with small ends, you still have to change the bytes to all places.

+1
source

All Articles