function tcpPacket
tcpPacket(): Coder<TcpPacket>

Creates a coder for TCP segments (RFC 9293).

The returned coder reads the 20-byte fixed header, then (dataOffsetReserved.dataOffset - 5) * 4 bytes of options, then absorbs the rest of the buffer as the payload. On encode, dataOffset is written verbatim — callers must keep it consistent with options.length (i.e. dataOffset = 5 + options.length / 4).

Pair this with refineSwitch on an IPv4 host's protocol field (see @binstruct/inet) to dispatch the L4 payload into a typed segment.

Examples

Round-trip a small ACK segment with payload

import { assertEquals } from "@std/assert";
import { TCP_HEADER_MIN_SIZE, tcpPacket } from "@binstruct/tcp";

const coder = tcpPacket();
const payload = new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0x6f]);
const segment = {
  sourcePort: 49152,
  destinationPort: 443,
  sequenceNumber: 1000,
  acknowledgmentNumber: 2000,
  dataOffsetReserved: { dataOffset: 5, reserved: 0 },
  flags: { cwr: 0, ece: 0, urg: 0, ack: 1, psh: 1, rst: 0, syn: 0, fin: 0 },
  window: 8192,
  checksum: 0,
  urgentPointer: 0,
  options: new Uint8Array(0),
  payload,
};

const buffer = new Uint8Array(TCP_HEADER_MIN_SIZE + payload.length);
const written = coder.encode(segment, buffer);
const [decoded, read] = coder.decode(buffer.subarray(0, written));

assertEquals(written, TCP_HEADER_MIN_SIZE + payload.length);
assertEquals(read, written);
assertEquals(decoded.payload, payload);
assertEquals(decoded.flags.ack, 1);
assertEquals(decoded.flags.psh, 1);

Return Type

Coder<TcpPacket>

A coder for TcpPacket values.

Usage

import { tcpPacket } from ".";