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

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

The width comes from the type of address — 4 bytes for a number, 16 for a bigint — the same typeof dispatch stringifyAddress uses. The address is written in network order (big-endian), and the return value is always exactly the bytes written, so result.length tells you the width. When into is given the return is a view into it, never the whole of it.

Examples

The address type picks the width

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

assertEquals(addressToBytes(parseAddress("10.0.0.1").address), new Uint8Array([10, 0, 0, 1]));
assertEquals(addressToBytes(parseAddress("::1").address).length, 16);

Round-tripping a packet field

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

const field = new Uint8Array([192, 168, 1, 1]);
assertEquals(addressToBytes(addressFromBytes(field)), field);

Parameters

address: Address

The address as a number (IPv4) or bigint (IPv6)

optional
into: Uint8Array

The buffer to write into, whose size the caller owns; one of the address's wire width is allocated when omitted

optional
offset: number = 0

Where in into to start writing, defaulting to 0

Return Type

The bytes written — 4 for IPv4, 16 for IPv6

Throws

RangeError

If the address is out of range, or its width is not available at offset