Okay I hate to ask this question … but here goes. I am writing some code in C on an x86 machine. I want to send a struct over the network and and I want to convert the struct to Network Byte Order … I understand all the drama about packing and the the gcc packing pragmas … what I want to know is HOW do I convert a struct (or an array or any such arbitrary memory blob) to network byte order.
Is there a standard (Unix/Linux/Posix) function call I can use or must I roll my own.
x
In principle, you can go through the struct and call
htonlorhtonson eachuint32_toruint16_tfield, respectively, assigning the results back or to a copy of the struct. However, I would not recommend this sort of approach. It’s very fragile and subject to struct alignment issues, etc.Unless transmitting and receiving data is extremely performance-critical, I would simply implement proper serialize and deserialize methods for your structures. You can write numeric values out one byte at a time in binary format, choosing whether you want to write to least significant or most significant part first. But really, I would recommend choosing a modern text-based serialization format like json or (uhg, I hate to say this) xml. The cost of serializing and deserializing text is quite small, and the advantages in terms of debugging ease and extensibility are significant.
Finally, if you want to use text but find json or xml too distasteful, too heavy, or too much of a learning curve, you can always just use
printfandscanfformatting to read and write structures as text in a fixed order. Writing all numeric values, including floats, in hex rather than decimal will probably improve performance a bit and ensure round-trip accuracy of floating point values. If you don’t have C99, another option for floats could be to decompose them to mantissa/exponent form and recompose them usingfrexpandldexp.