Universal conversion between IP addresses and their network-order wire bytes.

This module provides addressFromBytes and addressToBytes, which pick the IP version from the shape of their argument and delegate to the version-specific function. Addresses keep the numeric representation of the rest of the package — number for IPv4, bigint for IPv6. Bytes are a conversion, not a third representation.

For version-specific functions, see:

Byte order

Always network order (big-endian), on both the read and the write side. There is no option, because an IP address has exactly one wire order.

Picking the version

addressFromBytes reads the version off the length of the buffer, which must be exactly 4 or 16 bytes; anything else throws rather than guessing. It takes no offset — an offset would let the amount of trailing data decide the version, so pass exact bytes (packet.subarray(12, 16), a view rather than a copy). addressToBytes reads the version off the type of the address, the same typeof dispatch stringifyAddress uses, and does take into and offset, since its width comes from the address rather than from the buffer.

Decoders that already know the version and the field offset want the version-specific functions, where the width is fixed by the function rather than inferred from the buffer.

Examples

Read and write without knowing the version up front

import { assertEquals } from "@std/assert";
import { addressFromBytes, addressToBytes } from "@hertzg/ip/bytes";
import { stringifyAddress } from "@hertzg/ip/address";

const field = new Uint8Array([10, 0, 0, 1]);
assertEquals(stringifyAddress(addressFromBytes(field)), "10.0.0.1");

// The width comes back out unchanged
assertEquals(addressToBytes(addressFromBytes(field)), field);

Functions

f
addressFromBytes(bytes: Uint8Array): Address

Reads an IPv4 or IPv6 address from a buffer, picking the version from its length.

f
addressToBytes(
address: Address,
into?: Uint8Array,
offset?: number
): Uint8Array

Writes an IPv4 or IPv6 address, either into a fresh buffer or into one you supply.