UDP datagram encoding and decoding utilities (RFC 768).
A UDP datagram is an 8-byte header followed by a variable-length payload:
0 7 8 15 16 23 24 31 +--------+--------+--------+--------+ | Source | Destination | | Port | Port | +--------+--------+--------+--------+ | | | | Length | Checksum | +--------+--------+--------+--------+ | | | Payload | | | +-----------------------------------+
The length field covers the entire datagram (header + payload) measured in
octets, so the payload is always length - 8 bytes long.
The checksum field is optional in IPv4 (zero indicates "not computed") and
mandatory in IPv6. Computing it requires a layer-specific pseudo-header that
is not part of the datagram itself, so this package neither validates nor
derives it — callers are expected to provide both length and checksum.
Encode and decode a UDP datagram
Encode and decode a UDP datagram
import { assertEquals } from "@std/assert"; import { udpPacket } from "@binstruct/udp"; const coder = udpPacket(); const datagram = { srcPort: 53, dstPort: 49152, length: 8 + 4, checksum: 0, payload: new Uint8Array([0xde, 0xad, 0xbe, 0xef]), }; const buffer = new Uint8Array(64); const written = coder.encode(datagram, buffer); const [decoded, read] = coder.decode(buffer.subarray(0, written)); assertEquals(written, read); assertEquals(decoded.srcPort, datagram.srcPort); assertEquals(decoded.dstPort, datagram.dstPort); assertEquals(decoded.length, datagram.length); assertEquals(decoded.checksum, datagram.checksum); assertEquals(decoded.payload, datagram.payload);