Networking in C · beginner · ~8 min

htons(), htonl(), inet_pton() — network byte order

Convert numbers and addresses between host byte order and network byte order.

Lesson

Endianness: why byte order matters

A multi-byte integer can be stored in memory in more than one order. This ordering is called endianness.

  • Big-endian: the most significant byte comes first.
  • Little-endian: the least significant byte comes first.

Different CPUs make different choices. The same number can sit in memory in different byte orders on different machines.

Network byte order

To keep networking portable across machines, the standard fixes one order for the wire. Every multi-byte field in a network packet is stored in network byte order, which is big-endian (most significant byte first).

Before you send a number, convert it from your machine's order (the host order) to network order. After you receive one, convert it back.

The conversion functions

  • htons(x)host to network short — for 16-bit values, such as a port.
  • htonl(x)host to network long — for 32-bit values, such as an IPv4 address.
  • ntohs, ntohl — the reverse direction (network to host).

Parsing an IP address

inet_pton(family, "127.0.0.1", &addr) parses a dotted-decimal string into an in_addr structure. It is the modern function and is preferred over the deprecated inet_addr.

Code examples

#include <arpa/inet.h>
#include <stdio.h>

int main(void) {
    /* port 8080 in network byte order */
    unsigned short p = htons(8080);
    printf("port bytes: %02x %02x\n", ((unsigned char*)&p)[0], ((unsigned char*)&p)[1]);

    struct in_addr a;
    inet_pton(AF_INET, "127.0.0.1", &a);
    printf("addr bytes: %08x (network order)\n", a.s_addr);
    return 0;
}

Common mistakes

  • Storing a port in host byte order. sin_port = 8080; is wrong. You need sin_port = htons(8080);.
  • Using inet_addr. It returns INADDR_NONE in an ambiguous way: that value is also the legitimate result for the string 255.255.255.255, so you cannot tell success from failure. Use inet_pton instead.

Summary

  • Network byte order is big-endian (most significant byte first).
  • Use htons/htonl for fields you write into a network packet, and ntohs/ntohl to read them back.
  • Use inet_pton to parse IP address strings; avoid the deprecated inet_addr.

Practice with these exercises