You can just about automate this with a macro (you need to macro out the structure fields and use them both for the structure declaration and the field expansion), but the extra function call there gives you an opportunity to be defensive about e.g. buffer sizes, never blows up alignment, and isn't appreciably slower.
Comments
Won't this leave all multi-byte values in network endianness?
Yes, but so do the OS socket data structures, which is why htons() and htonl() are in the first chapter of any book on network programming.
The bigger problem with this scheme is alignment, although we appear to have outgrown architectures that will blow up when you get this wrong.
You do have to be careful, it can be annoying on ARM chips certainly. If you're using GCC, __attribute__ ((packed)) fixes alignment issues.
This method is so much less error prone than pulling stuff out a byte at a time. Plus you can use unions for network addresses, etc.
It's a simplified example to show what you can do.
It's a good trick, but I disagree that it's the right way to do it. My preferred idiom looks something like:
You can just about automate this with a macro (you need to macro out the structure fields and use them both for the structure declaration and the field expansion), but the extra function call there gives you an opportunity to be defensive about e.g. buffer sizes, never blows up alignment, and isn't appreciably slower.If you're willing to use packed structs, here's a neat one when you're dealing with e.g., the entry controls in VMX.
From my virtual machine work: