I've always been taught that if an integer is larger than a char, you must solve the byte ordering problem. Usually, I'll just wrap it in the hton[l|s] and convert it back with ntoh[l|s]. But I'm confused why this doesn't apply to single byte characters.
I'm sick of wondering why this is, and would love for a seasoned networks programmer to help me shed some light on why byte orderings only apply for multibyte integers.
Ref: https://beej.us/guide/bgnet/html/multi/htonsman.html
The htonl() function converts the unsigned integer hostlong from host byte order to network byte order. The htons() function converts the unsigned short integer hostshort from host byte order to network byte order. The ntohl() function converts the unsigned integer netlong from network byte order to host byte order.
The TCP/IP standard network byte order is big-endian. In order to participate in a TCP/IP network, little-endian systems usually bear the burden of conversion to network byte order.
Your port will simply be a number stored in an integer, and as such it must be converted into the proper form. The htons() function does just that. It takes one parameter and returns it in the expected network-byte order.
htons(), htonl(), ntohs(), ntohl() Since Intel is a "little-endian" machine, it's far more politically correct to call our preferred byte ordering "Network Byte Order". So these functions convert from your native byte order to network byte order and back again.
What you are looking for is endianness.
A big-endian architecture stores the bytes of a multibyte data type like so:
while a little-endian architecture stores them in reverse:
When data is transferred from one machine to another, the bytes of a single data type must be reordered to correspond with the endianness of the destination machine.
But when a data type only consists of one byte, there is nothing to reorder.
Your networking stack will handle the bits inside the bytes correctly, you must only concern yourself with getting the bytes in the right order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With