Understanding htonl() and ntohl()

As others have mentioned, both htons and ntohs reverse the byte order on a little-endian machine, and are no-ops on big-endian machines.

What wasn’t mentioned is that these functions take a 16-bit value and return a 16-bit value. If you want to convert 32-bit values, you want to use htonl and ntohl instead.

The names of these functions come from the traditional sizes of certain datatypes. The s stands for short while the l stands for long. A short is typically 16-bit while on older systems long was 32-bit.

In your code, you don’t need to call htonl on rec_addr, because that value was returned by inet_addr, and that function returns the address in network byte order.

You do however need to call htons on rec_port.

Leave a Comment