Conversion between IPv4 addresses and their network-order wire bytes.
This module reads an address straight out of a packet buffer and writes it
straight back into one, with no string round-trip. It is the byte-form
counterpart of the ipv4 submodule: addressv4FromBytes is to
parseAddressv4 what addressv4ToBytes is to stringifyAddressv4.
Addresses keep the numeric representation of the rest of the package — a
number holding a 32-bit unsigned integer. Bytes are a conversion, not a
second representation.
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.
Widths and offsets
Both functions are fixed at 4 bytes, and offset selects where in the
buffer that span sits, never how wide it is. A span that runs past the end
of the buffer throws a RangeError rather than reading undefined and
quietly decoding as 0.0.0.0.
For IPv6 see bytesv6; for the
version-detecting pair see bytes.
Decode both addresses out of an IPv4 header
Decode both addresses out of an IPv4 header
import { assertEquals } from "@std/assert"; import { addressv4FromBytes } from "@hertzg/ip/bytesv4"; import { stringifyAddressv4 } from "@hertzg/ip/addressv4"; // deno-fmt-ignore const packet = new Uint8Array([ 0x45, 0x00, 0x00, 0x54, 0x1c, 0x46, 0x40, 0x00, 0x40, 0x06, 0x00, 0x00, 10, 0, 0, 1, 192, 168, 1, 1, ]); assertEquals(stringifyAddressv4(addressv4FromBytes(packet, 12)), "10.0.0.1"); assertEquals(stringifyAddressv4(addressv4FromBytes(packet, 16)), "192.168.1.1");
Assemble an IPv4 header in place
Assemble an IPv4 header in place
import { assertEquals } from "@std/assert"; import { addressv4ToBytes } from "@hertzg/ip/bytesv4"; import { parseAddressv4 } from "@hertzg/ip/addressv4"; const frame = new Uint8Array(20); addressv4ToBytes(parseAddressv4("10.0.0.1").address, frame, 12); addressv4ToBytes(parseAddressv4("192.168.1.1").address, frame, 16); assertEquals(frame.slice(12), new Uint8Array([10, 0, 0, 1, 192, 168, 1, 1]));
Reads a 4-byte IPv4 address from a buffer.
Writes a 4-byte IPv4 address, either into a fresh buffer or into one you supply.
Usage
import * as mod from "bytesv4.ts";