# coap — 4-Byte UDP 5683 RESTful IoT Datagrams & Options (`coap`)

> **FrameAssembly v3.2.2** · Protocol 74 of 81 · Canonical URL: https://frameassembly-lang.dev/docs/protocols/coap

- **Full Protocol Name:** Constrained Application Protocol
- **Keyword:** `coap`
- **OSI Layer & Transport:** Layer 7 · UDP 5683
- **Host Endpoint Rule:** Dual-Stack IPv4/IPv6
- **Standards:** RFC 7252
- **Wireshark Display Filter:** `coap`
- **Wire Encapsulation:** `Ethernet II -> [802.1Q / QinQ / MPLS] -> IPv4 / IPv6 -> UDP 5683 -> CoAP (IoT)`

## Overview

HTTP shrunk down to a 4-byte UDP `5683` header for battery-powered sensors: just pick *either* a named method (`get`, `post`, `created`) *or* dotted `code "0.01"` (combining both on one line triggers a helpful compiler error).

Constrained Application Protocol (`coap`, RFC 7252) brings REST-like `GET`, `POST`, `PUT`, and `DELETE` semantics to low-power microcontrollers, NB-IoT meters, and Thread/6LoWPAN sensors in a compact **4-byte UDP header** on **UDP port `5683`**.

FrameAssembly encodes CoAP Version `1`, Message Type (`con` Confirmable, `non` Non-confirmable, `ack` Acknowledgment, `rst` Reset), `class.detail` Method/Response Codes (`0.01` GET, `2.05` Content, `4.04` Not Found), variable-length `token`, delta-encoded `Uri-Path` (`uripath`) and `Content-Format` (`contentformat`) options, and the `0xff` payload marker.

## Minimal Quickstart (`coap_quickstart.frasm`)

```frameassembly
host sensor_01 { ip 10.70.1.50 }
host iot_gw    { ip 10.70.1.1 }

compile {
    sensor_01 -> iot_gw coap con post msgid 101 token 0x4a1b uripath "telemetry/humidity" contentformat 50 payload "{\"rh\":48.2}" wait 3ms
    sensor_01 <- iot_gw coap ack changed msgid 101 token 0x4a1b
}
```

### Automatic Wire Calculations

- Defaults to UDP destination port `5683` and packs CoAP Version `1`, 2-bit Type, Token Length (`TKL`), 1-byte `c.dd` Code (`(class << 5) | detail`), and 16-bit `msgid`.
- Splits slash-separated `uripath` strings (`"telemetry/humidity"`) into individual delta-encoded Option `11` (`Uri-Path`) segments automatically.
- Inserts Option `12` (`Content-Format`) and the mandatory `0xff` Payload Marker byte whenever `payload` or `hexpayload` is present.

## Practical Lab Example: Confirmable CoAP Sensor GET (`2.05 Content`) & Missing Resource (`4.04`) (`coap_ipv6_sensors.frasm`)

Queries `/sensors/temp` over IPv6 receiving a piggybacked `ack` with `code "2.05"` JSON payload, then queries an unknown path returning `notfound` (`4.04`).

```frameassembly
host collector { ip 2001:db8:70::1 }
host mote_12   { ip 2001:db8:70::12 }

compile {
    // 1. Confirmable GET -> Piggybacked ACK 2.05 Content (contentformat 50 = application/json)
    collector -> mote_12 coap con get msgid 500 token 0x0102 uripath "sensors/temp" wait 4ms
    collector <- mote_12 coap ack code "2.05" msgid 500 token 0x0102 contentformat 50 payload "{\"c\":22.4}" wait 5ms
    // 2. Unknown URI -> 4.04 Not Found
    collector -> mote_12 coap con get msgid 501 token 0x0103 uripath "sensors/valve9" wait 4ms
    collector <- mote_12 coap ack notfound msgid 501 token 0x0103
}
```

```bash
# 1. Eyeball relative timestamps, ports & wire lengths in your terminal
frameassembly show coap_ipv6_sensors.frasm

# 2. Compile .frasm -> classic .pcap (tcpdump/tcpreplay/Suricata) or nanosecond .pcapng
frameassembly coap_ipv6_sensors.frasm coap_ipv6_sensors.pcap
frameassembly coap_ipv6_sensors.frasm coap_ipv6_sensors.pcapng

# 3. Round-trip .pcap <-> .frasm whenever you want to scrub or tweak an existing capture
frameassembly reverse coap_ipv6_sensors.pcap coap_ipv6_sensors_edited.frasm

# 4. Verify dissected protocol fields in tshark
tshark -r coap_ipv6_sensors.pcap
```

## All `coap` Keywords & Header Options

Packet line pattern: `src_host -> dst_host coap [con | non | ack | rst | msgtype "<text>"] [get | post | put | delete | created | changed | notfound | code "<c.dd>"] [msgid <0..65535>] [token <hex_or_num>] [uripath "<text>"] [contentformat <0..65535>]`

| Keyword / Option | Accepted Value | Default | Effect on Packet |
| --- | --- | --- | --- |
| `con \| non \| ack \| rst \| msgtype "<text>"` | CoAP Message Type (`0` CON, `1` NON, `2` ACK, `3` RST) | `con (Confirmable)` | Sets the 2-bit `T` field in byte 0 (`ack` and `rst` are CoAP UDP message types, not TCP flags). |
| `get \| post \| put \| delete \| created \| changed \| notfound \| code "<c.dd>"` | Shorthand keyword OR dotted code (`"0.01"`..`"5.05"`, choose one) | `get ("0.01")` | Encodes byte 1 (`(class << 5) \| detail`, e.g. `"2.05"` Content = `0x45`). |
| `msgid <0..65535> \| token <hex_or_num>` | 16-bit Message ID + Token value | `msgid 1, token omitted` | Matches `con` <-> `ack` deduplication (`msgid`) and asynchronous request/response correlation (`token`). |
| `uripath "<text>"` | Slash-separated resource path without leading slash (`"sensors/temp"`) | `Omitted unless set` | Encodes repeatable delta-encoded CoAP Option `11` (`Uri-Path`). |
| `contentformat <0..65535>` | IANA CoAP Content-Format (`0` text/plain, `40` link-format, `50` JSON, `60` CBOR) | `Omitted unless set` | Encodes CoAP Option `12` (`Content-Format`). |

## Cross-Layer Options Valid with `coap`

| Option | Range / Format | Default | Effect |
| --- | --- | --- | --- |
| `wait <number><ns\|us\|ms\|s\|m>` | Time gap (ns, us, ms, s, m) | `10ms` | Advances the packet timestamp clock after sending this packet and before the next packet (`wait 0ns` sends back-to-back). |
| `payload "<text>" \| hexpayload "<hex>"` | Quoted text or hex bytes (choose one) | `Omitted` | Appends or overrides raw payload bytes (`"deadbeef"` or `"de:ad:be:ef"`) and updates packet lengths and checksums. |
| `srcmac <mac> \| dstmac <mac> \| ethertype <0..65535>` | Colon/hyphen/Cisco MAC · EtherType u16 (e.g. 0x0800) | `Host MAC / RFC multicast MAC / auto EtherType` | Overrides the 14-byte Ethernet II source MAC, destination MAC, or 16-bit EtherType for this single packet. |
| `vlan <0..4095> [pcp <0..7>] [dei <0\|1>]` | VLAN ID 0..4095, PCP 0..7, DEI 0..1 | `Untagged` | Wraps the packet in an IEEE 802.1Q VLAN tag (`0x8100`) with optional 802.1p QoS priority. |
| `qinq <0..4095> [innervlan <0..4095>]` | Outer S-VLAN 0..4095, Inner C-VLAN 0..4095 | `Untagged (innervlan 1 when qinq is set)` | Double-tags the packet with outer IEEE 802.1ad S-Tag (`0x88a8`) plus inner IEEE 802.1Q C-Tag (`0x8100`). |
| `mpls <0..1048575> [label <0..1048575>] [exp\|tc <0..7>] [bos <0\|1>] [mplsttl <0..255>]` | Label 0..1048575, exp/tc 0..7, bos 0..1, ttl 0..255 | `Unlabeled (at most 1 mpls tag per packet)` | Inserts a 32-bit MPLS label header (`0x8847`) ahead of the Layer 3 header. |
| `ttl <0..255> [dscp <0..63>] [ecn <0..3>]` | TTL/Hop Limit 0..255, DSCP 0..63, ECN 0..3 | `ttl 64, dscp 0, ecn 0` | Sets IPv4 TTL or IPv6 Hop Limit plus DiffServ (DSCP) and ECN QoS markings. |
| `ipid <0..65535> [df] [mf] [fragoffset <0..8191>]` | IPv4 ID, DF/MF flags, fragment offset 0..8191 | `ipid 1, flags 0, fragoffset 0` | Sets IPv4 Identification, Do-Not-Fragment (`df`), More-Fragments (`mf`), and fragment offset (ignored over IPv6). |
| `flowlabel <0..1048575>` | 20-bit IPv6 Flow Label (0..1048575) | `0` | Sets the 20-bit IPv6 Flow Label for ECMP routing tests (ignored when running over IPv4 hosts). |
| `srcport <0..65535> \| dstport <0..65535>` | Port number 0..65535 | `srcport 49152 (remembered), UDP 5683` | Overrides source or destination port and remembers the port pair automatically on `<-` replies. |

## Common Mistakes & Quick Fixes

### Never Combine a Shorthand Verb (get) and code "0.01" on the Same Packet

- **Avoid:** `collector -> mote_12 coap con get code "0.01" msgid 1`
- **Valid v3.2.2 Syntax:** `collector -> mote_12 coap con get msgid 1   // OR: coap ack code "2.05" msgid 1`

Both `get` and `code "..."` set the same 1-byte CoAP Code field—pick either a bare shorthand (`get`, `post`, `changed`, `notfound`) or `code "2.05"`, never both on one line.
