Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to parse network packet in C

(Excuse me if I am not able to put the question correctly. English in not my primary language.)

I am trying to parse SyncE ESMC packet. It is Ethernet slow protocol packet.

Approach 1: For parsing this packet, I used byte by byte approach similar to what has been done here.

Approach 2: Other way to parse the packet would be to define a 'structure' to represent the whole packet and access individual fields to retrieve the value at particular offset. However in this approach structure padding and alignment may come into picture(which I am not sure) but on Linux various packet headers are defined in form of structure, e.g. iphdr in ip.h. IP packets (buffer) can be type casted to 'iphdr' to retrieve ip header fields, so it must be working.

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

Does structure padding and aligment make any difference while parsing a packet via approach 2? If yes, how did Linux headers overcome this problem?

like image 837
Abhirav Avatar asked Jan 31 '13 19:01

Abhirav


1 Answers

Approach 1 is the best for portability. It allows you to safely avoid misaligned accesses, for example. In particular, if your machine is little-endian, this approach lets you take care of the byte-swapping very easily.

Approach 2 is sometimes convenient and often is faster code to write. If structure padding gets in your way, your compiler probably provides a flag or attribute (like __attribute__((__packed__)) or #pragma pack) to work around it. If you have a little-endian machine, however, you're still going to have to byteswap fields all over the place.

like image 59
Carl Norum Avatar answered Oct 31 '22 23:10

Carl Norum