Network Byte Order and Endianness: htons, ntohl and Friends
Understand big-endian network byte order, why x86 and ARM hosts differ, and when to call htons, htonl, ntohs and ntohl in C socket code.

When a C program fills in a socket address or reads a port out of a packet, it has to deal with a fact that has nothing to do with sockets: different computers store multi-byte numbers in different byte orders. Get it wrong and port 80 becomes port 20480, an IP address reads backwards, and nothing in the compiler warns you. This post explains what byte order is, what "network byte order" means, and exactly when to call htons, htonl, ntohs and ntohl. The examples use C17 with glibc 2.40 on Linux 6.12, and need no prior networking knowledge beyond knowing that a port is a 16-bit number.
What endianness is
A 16-bit integer occupies two bytes in memory, and a 32-bit one occupies four. The question is which byte comes first. Take the number 0x1234. Its high byte is 0x12 and its low byte is 0x34.
A big-endian machine stores the high byte at the lowest address:
12 34.A little-endian machine stores the low byte at the lowest address:
34 12.
x86-64 is little-endian. ARM processors can run either way but Linux and most phones and servers run them little-endian, and some network processors and older architectures such as PowerPC in its traditional form are big-endian. Your code cannot assume either one.
You can see your own machine's order with a short program that prints the bytes of a known value. It copies the integer into a byte array with memcpy, which is the portable way to inspect an object's representation without breaking the aliasing rules.
#include <stdint.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
uint16_t value = 0x1234;
unsigned char bytes[sizeof value];
memcpy(bytes, &value, sizeof value);
printf("value 0x%04x is stored as: %02x %02x\n", value, bytes[0], bytes[1]);
return 0;
}value 0x1234 is stored as: 34 12The output above is what an x86-64 or little-endian ARM Linux machine prints. On a big-endian host the same program prints 12 34. The value is the same, only its layout in memory differs.
What network byte order is
Protocols need one agreed order or two machines could not read each other's headers. The internet protocols chose big-endian, which RFC 791 (the IP specification) calls the order of transmission, with the most significant byte sent first. That convention is called network byte order. The port and address fields in TCP, UDP and IP headers are all in it. The order your CPU uses internally is called host byte order.
So every number you move between your program and the wire may need converting. The converting functions are declared in <arpa/inet.h>, and POSIX defines them:
| Function | Meaning | Width |
|---|---|---|
htons | host to network, short | 16 bits |
htonl | host to network, long | 32 bits |
ntohs | network to host, short | 16 bits |
ntohl | network to host, long | 32 bits |
The names are historical: "short" means 16 bits and "long" means 32 bits, regardless of what short and long are in your compiler. The functions take and return uint16_t and uint32_t.
On a big-endian host they do nothing, because host order already equals network order. On a little-endian host they swap the bytes. Because they are a no-op on one kind of machine, a missing call is a bug that only shows up on the other kind, so you should call them everywhere they apply and not rely on the machine you tested on.
#include <arpa/inet.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
static void dump(const char *label, const void *p, size_t n)
{
const unsigned char *b = p;
printf("%-14s", label);
for (size_t i = 0; i < n; i++)
printf("%02x ", b[i]);
putchar('\n');
}
int main(void)
{
uint16_t port = 8080; /* 0x1f90 */
uint16_t wire_port = htons(port);
uint32_t addr = 0xc0000201; /* 192.0.2.1 */
uint32_t wire_addr = htonl(addr);
dump("host port", &port, sizeof port);
dump("network port", &wire_port, sizeof wire_port);
dump("host addr", &addr, sizeof addr);
dump("network addr", &wire_addr, sizeof wire_addr);
printf("round trip: %u\n", ntohs(wire_port));
return 0;
}host port 90 1f
network port 1f 90
host addr 01 02 00 c0
network addr c0 00 02 01
round trip: 8080The network forms read 1f 90 and c0 00 02 01, which is exactly how the bytes appear on the wire: the address 192.0.2.1 is the four bytes c0 00 02 01 in order. That is not a coincidence. A dotted-decimal address is simply the four network-order bytes written in decimal, which is why the notation reads left to right in the same order the bytes travel.
Where you must convert
Convert at the boundary between your program's arithmetic and the wire format. In practice that means three places.
Filling a socket address. The sockaddr_in structure stores the port and address in network order, so you convert on the way in:
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
struct sockaddr_in sa;
memset(&sa, 0, sizeof sa);
sa.sin_family = AF_INET;
sa.sin_port = htons(8080);
inet_pton(AF_INET, "192.0.2.1", &sa.sin_addr);
printf("port field holds 0x%04x\n", sa.sin_port);
printf("host reads port %u\n", ntohs(sa.sin_port));
return 0;
}port field holds 0x901f
host reads port 8080On a little-endian host the raw field prints as 0x901f, because the bytes 1f 90 read as a native integer are 0x901f. That surprising number is what a debugger shows you in sin_port, and it is correct. inet_pton already writes the address in network order, so you do not call htonl on its result. Calling it twice would swap the address back.
Reading a value out of a received buffer. When a protocol field arrives in a byte array, copy it into a properly typed variable and convert. Do not cast the pointer.
Writing a value into an outgoing buffer. Convert first, then copy the result in.
Why a pointer cast is wrong
It looks shorter to write uint16_t port = *(uint16_t *)(buf + 20); to read a port out of a received packet, and you will see it in older code. It has two problems. First, the address buf + 20 may not be aligned for a 16-bit access, and on some architectures that traps. Second, reading bytes of a char array through a uint16_t pointer violates the C aliasing rules, so the compiler may reorder or drop the read. The reliable form copies the bytes out:
#include <arpa/inet.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
static uint16_t read_be16(const unsigned char *p)
{
uint16_t v;
memcpy(&v, p, sizeof v);
return ntohs(v);
}
int main(void)
{
unsigned char packet[] = { 0x1f, 0x90, 0x01, 0xbb };
printf("source port %u\n", read_be16(packet));
printf("dest port %u\n", read_be16(packet + 2));
return 0;
}source port 8080
dest port 443memcpy of two bytes compiles to a single load, so there is no cost to doing it correctly. A third option is to assemble the value from the bytes directly with shifts: (uint16_t)(p[0] << 8 | p[1]). That works on any host without calling a library function at all, and it is the form many parsers prefer because it states the wire format explicitly.
Beyond four functions
The four classic functions cover 16 and 32 bits only. For 64-bit fields and for fixed byte orders that are not the network's, glibc provides <endian.h> with htobe64, be64toh, htole32, le32toh and relatives, added in glibc 2.9. They name the target order directly, which reads better in a parser than a host-to-network pair, and they work for little-endian wire formats too, such as the fields of a pcap file header or a USB descriptor. They are Linux and BSD extensions, not POSIX, so a program that must build on other systems should keep to the four POSIX names and write its own helpers for the rest.
Single bytes have no order, so a protocol version or a flag byte never needs conversion. Only multi-byte integers do. Floating-point numbers have no standard network conversion function; protocols that carry them define their own encoding.
Common mistakes
Forgetting htons on a port is the classic one: sin_port = 8080 on a little-endian host binds to port 36895, since 0x1f90 read with its bytes swapped is 0x901f. The program runs without error and listens on the wrong port. The reverse mistake is converting twice. Calling ntohs on a value you already converted turns it back into the wrong order. When a number looks plausible but wrong, with its two bytes exchanged, suspect byte order first.


