What you will learn
- What byte order (endianness) is and why the network fixes one order.
- The four conversion functions
htons(),htonl(),ntohs(),ntohl()and exactly when to call them. - How to turn
"192.168.10.20"into binary and back withinet_pton()andinet_ntop(). - Which older functions (
inet_addr,inet_aton,inet_ntoa) to avoid and why.
Two ways to store a number
The 16-bit number 8080 is 0x1F90. It takes two bytes, 1F and 90. A computer can store them in memory in two orders:
| Order | Byte at lowest address first | Used by |
|---|---|---|
| Big-endian | 1F 90 (most significant first) | The network, many older RISC CPUs |
| Little-endian | 90 1F (least significant first) | x86, x86-64, almost all ARM systems in practice |
If a little-endian machine sends the two bytes of 8080 exactly as they sit in memory, a big-endian machine reads 0x901F, which is 36895. To avoid that, Internet protocols agree on one order for everything in packet headers: big-endian, called network byte order. The order your CPU uses is host byte order.
The conversion functions
<arpa/inet.h> gives you four functions. The names read as “host to network short”, “network to host long”, and so on. “Short” means 16 bits and “long” means 32 bits (even on 64-bit systems where long is bigger).
| Function | Converts | Typical use |
|---|---|---|
htons(x) | 16-bit host → network | Port numbers you put into a sockaddr |
htonl(x) | 32-bit host → network | IPv4 addresses held as integers, length prefixes |
ntohs(x) | 16-bit network → host | Port numbers you read out of a sockaddr |
ntohl(x) | 32-bit network → host | Length prefixes you receive |
On a big-endian CPU these do nothing; on a little-endian CPU they swap bytes. Always call them anyway: your code then works on both.
The rule of thumb: anything that goes into a socket address structure or a binary protocol header is converted on the way in and on the way out. You don’t convert strings (bytes are already in order) and you don’t convert data that only ever lives in your own process.
When you use getaddrinfo() (lesson 5) it fills the structures in network order for you, which removes most of these calls from modern code. You still need them for your own binary formats, covered in the serialization lesson.
There are no standard 64-bit or floating-point versions in POSIX. Lesson 16 shows how to encode those byte by byte.
Text to binary: inet_pton()
Humans write 192.168.10.20 or 2001:db8::42. The kernel wants a 4-byte struct in_addr or a 16-byte struct in6_addr. inet_pton() (“presentation to network”) converts:
int inet_pton(int af, const char *src, void *dst);
afisAF_INETorAF_INET6.dstpoints to anin_addrorin6_addr.- Returns 1 on success, 0 if the text is not a valid address for that family, -1 if
afis unknown.
That three-way result trips people up. if (inet_pton(...)) is wrong because -1 is true in C. Compare with == 1.
Binary to text: inet_ntop()
const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
It writes the text into your buffer and returns a pointer to it, or NULL on error. Use the size macros so the buffer is always big enough:
INET_ADDRSTRLEN(16) for IPv4INET6_ADDRSTRLEN(46) for IPv6
A complete example
This program shows the wire bytes of a port, converts an IPv4 address to a number, and lets inet_ntop() compress an IPv6 address:
/* convert.c - byte order and text <-> binary address conversion */
#include <stdio.h>
#include <stdint.h>
#include <arpa/inet.h>
#include <netinet/in.h>
int main(void)
{
uint16_t port = 8080;
uint16_t wire_port = htons(port);
const unsigned char *b = (const unsigned char *)&wire_port;
printf("port %u on the wire: %02x %02x\n", port, b[0], b[1]);
printf("back to host order: %u\n", ntohs(wire_port));
struct in_addr v4;
if (inet_pton(AF_INET, "192.168.10.20", &v4) != 1) {
fprintf(stderr, "bad IPv4 address\n");
return 1;
}
printf("as a 32-bit host-order number: %u\n", ntohl(v4.s_addr));
struct in6_addr v6;
if (inet_pton(AF_INET6, "2001:db8:0:0:0:0:0:42", &v6) != 1) {
fprintf(stderr, "bad IPv6 address\n");
return 1;
}
char text[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, &v6, text, sizeof text);
printf("compressed IPv6: %s\n", text);
return 0;
}
Output on an x86-64 machine:
port 8080 on the wire: 1f 90
back to host order: 8080
as a 32-bit host-order number: 3232238100
compressed IPv6: 2001:db8::42
Notice that inet_ntop() produced the shortest standard form (2001:db8::42) even though we passed the long form.
Old functions you will still see
Older tutorials and code bases use these. Recognise them, but don’t write new code with them:
| Function | Problem | Use instead |
|---|---|---|
inet_addr("1.2.3.4") | Returns -1 (INADDR_NONE) on error, which is also the valid address 255.255.255.255 | inet_pton() |
inet_aton() | IPv4 only | inet_pton() |
inet_ntoa(addr) | IPv4 only, returns a pointer to one static buffer, so a second call overwrites the first result and it isn’t thread-safe | inet_ntop() |
Key takeaways
- Network byte order is big-endian; your CPU is probably little-endian.
- Convert ports and binary integers with
htons/htonlbefore sending andntohs/ntohlafter receiving. inet_pton()returns 1 only on success; always compare with== 1.- Use
inet_ntop()withINET6_ADDRSTRLEN-sized buffers; avoidinet_ntoa()andinet_addr().
Exercises
- Write a function
int is_little_endian(void)without any library calls, using auint16_tand a byte pointer. - Write
parse_any(const char *text)that tries IPv4 and then IPv6 withinet_pton()and prints which family matched, or “invalid”. - Print
inet_ntoa()results for two different addresses inside oneprintf()call and explain the surprising output.
Quiz
- What does
htons(0x1234)return on a little-endian machine? - Why is
if (inet_pton(AF_INET, s, &a))a bug? - Do you need to call
htonl()on the bytes of a text message before sending it?
Show answers
0x3412. On a big-endian machine it would return0x1234unchanged.inet_pton()returns -1 for an unknown address family, and -1 is true in C, so the error would be treated as success. Compare with== 1.- No. Text is a sequence of single bytes, which have no byte order. Only multi-byte binary numbers need converting.