jsocketpp 1.0
A cross-platform C++20 socket library.
Loading...
Searching...
No Matches

Endianness utilities for network byte order conversion. More...

Functions

uint16_t toNetwork (const uint16_t val)
 Converts a 16-bit unsigned integer from host to network byte order.
uint32_t toNetwork (const uint32_t val)
 Converts a 32-bit unsigned integer from host to network byte order.
uint16_t fromNetwork (const uint16_t val)
 Converts a 16-bit unsigned integer from network to host byte order.
uint32_t fromNetwork (const uint32_t val)
 Converts a 32-bit unsigned integer from network to host byte order.

Detailed Description

Endianness utilities for network byte order conversion.

The jsocketpp::net namespace provides a collection of lightweight, header-only functions for safely converting between host and network byte order for integral types.

Purpose

  • Ensures portable binary encoding across different CPU architectures
  • Enables interoperability with other systems that use big-endian formats
  • Matches standard socket API behavior (e.g., htons/ntohl)

Usage Example

using namespace jsocketpp::net;
uint32_t value = 123456;
uint32_t networkValue = toNetwork(value); // Host → network (big-endian)
uint32_t restored = fromNetwork(networkValue); // Network → host
Endianness utilities for network byte order conversion.
uint16_t toNetwork(const uint16_t val)
Converts a 16-bit unsigned integer from host to network byte order.
Definition common.hpp:444
uint16_t fromNetwork(const uint16_t val)
Converts a 16-bit unsigned integer from network to host byte order.
Definition common.hpp:460

These functions are wrappers over platform-native byte order macros:

  • Windows: htons, ntohl, etc. (from winsock2.h)
  • POSIX: htons, ntohl, etc. (from arpa/inet.h)

Recommended Use

  • Apply to any integral header field before transmission over the wire
  • Use in conjunction with Socket::read<T>() and Socket::writeFromAll() to ensure cross-platform safety for multi-byte fields
Note
Network byte order is always big-endian, as defined by RFC 1700.
See also
toNetwork() Host-to-network conversion
fromNetwork() Network-to-host conversion
Socket::readPrefixed() Uses these internally

Function Documentation

◆ fromNetwork() [1/2]

uint16_t jsocketpp::net::fromNetwork ( const uint16_t val)
inline

Converts a 16-bit unsigned integer from network to host byte order.

◆ fromNetwork() [2/2]

uint32_t jsocketpp::net::fromNetwork ( const uint32_t val)
inline

Converts a 32-bit unsigned integer from network to host byte order.

◆ toNetwork() [1/2]

uint16_t jsocketpp::net::toNetwork ( const uint16_t val)
inline

Converts a 16-bit unsigned integer from host to network byte order.

◆ toNetwork() [2/2]

uint32_t jsocketpp::net::toNetwork ( const uint32_t val)
inline

Converts a 32-bit unsigned integer from host to network byte order.