Network byte order and htons/ntohs
What you'll learn: How to translate multi-byte numbers so different computers can speak the same language over a network.
The Language Barrier
Imagine you write the number 500 on a piece of paper. In English, we read left-to-right. But what if you sent that paper to someone who reads right-to-left? They might see a completely different value.
Computers face a similar problem called Endianness. Some CPUs (like Intel) store the "small" part of a number first (Little-Endian), while others store the "big" part first (Big-Endian). If a Little-Endian computer sends the integer 0x0001 to a Big-Endian computer without any changes, the receiver might interpret it as 0x0100. To fix this, the internet uses a standard "postal code" rule: all data traveling over a network must be in Big-Endian format, also known as Network Byte Order.
The Translators: htons and ntohs
To ensure your data isn't scrambled during transit, C provides helper functions to swap the bytes for you. You don't need to know if your own computer is Big or Little Endian; these functions are smart enough to do nothing if your computer already matches the network standard.
htons(): host to network short (converts a 16-bit number to network order).ntohs(): network to host short (converts it back so your programs can read it).
Concrete Example
When you specify a port number (like 80 for web traffic) in a socket program, you must convert it.
#include <stdio.h>
#include <arpa/inet.h> // Header for conversion functions
int main() {
unsigned short host_port = 80; // Local representation
unsigned short network_port;
// Convert to Network Byte Order before sending
network_port = htons(host_port);
printf("Host order: %d (0x%04x)\n", host_port, host_port);
printf("Network order: %d (0x%04x)\n", network_port, network_port);
// Convert back to confirm
unsigned short back_to_host = ntohs(network_port);
printf("Back to host: %d\n", back_to_host);
return 0;
}
On a standard PC, htons(80) will flip the bytes of the number. If you skip this step, the router on the other end will look for port 20480 instead of 80, and your connection will fail.
Key takeaway
Always use htons when sending data and ntohs when receiving it to ensure your numbers remain consistent across different types of hardware.