htonl(3) — host-to-network byte order conversions

Manual page — section 3 • C library functions

htonl(3) — C library manual

htonl, htons, ntohl, ntohs

NAME

htonl, htons, ntohl, ntohs — convert values between host and network byte order.

SYNOPSIS

#include <arpa/inet.h>

uint32_t htonl(uint32_t hostlong);
uint16_t htons(uint16_t hostshort);
uint32_t ntohl(uint32_t netlong);
uint16_t ntohs(uint16_t netshort);

DESCRIPTION

These functions convert 16-bit and 32-bit integers between host byte order and network byte order. Network byte order is defined as big-endian. Host byte order depends on the host architecture.

Typical usage: converting port numbers and IP addresses before sending them on the network or after receiving them.

/* Example: convert port and IPv4 address fields */
struct sockaddr_in sa;
sa.sin_port = htons(8080);
sa.sin_addr.s_addr = htonl(0x7f000001); /* 127.0.0.1 */

ATTRIBUTES

  • Thread safety: MT-Safe (safe to use in multi-threaded programs).
  • Return value: Converted value in the same integer width.
  • Headers: <arpa/inet.h> (sometimes also <netinet/in.h>).

STANDARDS

These functions are specified by POSIX and have been present since early BSD networking stacks (4.2BSD).

HISTORY

The conversion functions originate from the BSD sockets API and have been adopted across Unix-like systems and the POSIX standard.

SEE ALSO

man 7 ip, getaddrinfo(3), inet_pton(3), ntohl(3), htons(3).