BigEndian, LittleEndian UDP packets

I am writing some networking code in C to run on the Pi. I send a UDP packet using sendto() and receive a packet using recvfrom(). The trouble is that when I view this using wireShark the data is littleEndian instead of bigEndian. The data packet is binary data and includes an array of structures with mixed longs integers, and characters. Is there some function I can call which automatically takes care of this so that the data is sent as bigEndian instead of littleEndian? I could write a function to do this but this will get complicated and error prone and be a processing burden. It also would be slow. How is this done properly to take care of conversion in both directions? Surly there must be some function or something which make this seamless as every littleEndian processor system has to deal with this in both directions all the time in network communication.

The functions htons and htonl convert from the host to the network endian for shorts and longs respectively. Then ntohs and ntohl convert back. Nothing will automatically understand the format of your data, so you need to manually convert any numerical values necessary. It’s one of those bummers, like imperial vs. metric, power point shape & voltage, which side of the road to drive on, etc. If only consensus was reached early on!

1 Like