Lesson 3 of 18 Foundations

Byte Order and inet_pton/inet_ntop

Big-endian vs little-endian, htons/htonl/ntohs/ntohl, and converting IP address text to binary with inet_pton and inet_ntop for IPv4 and IPv6.

30-40 min beginner 0/18 lessons done
Course contents Lesson 3 of 18 · 0 done
On this page (10 sections)
  1. What you will learn
  2. Two ways to store a number
  3. The conversion functions
  4. Text to binary: inet_pton()
  5. Binary to text: inet_ntop()
  6. A complete example
  7. Old functions you will still see
  8. Key takeaways
  9. Exercises
  10. Quiz

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 with inet_pton() and inet_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:

OrderByte at lowest address firstUsed by
Big-endian1F 90 (most significant first)The network, many older RISC CPUs
Little-endian90 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).

FunctionConvertsTypical use
htons(x)16-bit host → networkPort numbers you put into a sockaddr
htonl(x)32-bit host → networkIPv4 addresses held as integers, length prefixes
ntohs(x)16-bit network → hostPort numbers you read out of a sockaddr
ntohl(x)32-bit network → hostLength 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);
  • af is AF_INET or AF_INET6.
  • dst points to an in_addr or in6_addr.
  • Returns 1 on success, 0 if the text is not a valid address for that family, -1 if af is 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 IPv4
  • INET6_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:

FunctionProblemUse instead
inet_addr("1.2.3.4")Returns -1 (INADDR_NONE) on error, which is also the valid address 255.255.255.255inet_pton()
inet_aton()IPv4 onlyinet_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-safeinet_ntop()

Key takeaways

  • Network byte order is big-endian; your CPU is probably little-endian.
  • Convert ports and binary integers with htons/htonl before sending and ntohs/ntohl after receiving.
  • inet_pton() returns 1 only on success; always compare with == 1.
  • Use inet_ntop() with INET6_ADDRSTRLEN-sized buffers; avoid inet_ntoa() and inet_addr().

Exercises

  1. Write a function int is_little_endian(void) without any library calls, using a uint16_t and a byte pointer.
  2. Write parse_any(const char *text) that tries IPv4 and then IPv6 with inet_pton() and prints which family matched, or “invalid”.
  3. Print inet_ntoa() results for two different addresses inside one printf() call and explain the surprising output.

Quiz

  1. What does htons(0x1234) return on a little-endian machine?
  2. Why is if (inet_pton(AF_INET, s, &a)) a bug?
  3. Do you need to call htonl() on the bytes of a text message before sending it?
Show answers
  1. 0x3412. On a big-endian machine it would return 0x1234 unchanged.
  2. 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.
  3. No. Text is a sequence of single bytes, which have no byte order. Only multi-byte binary numbers need converting.

Finished this lesson?

Mark it complete to track your progress (saved in this browser).