Chapters

Codes, Tokens, and Options: CoAP Messages Reference

Return to the parent chapter.

Related reference: CoAP message types.

The source material below accompanies the conceptual chapter. Its three knowledge checks are collected on the standalone check page.

Start With the Decision

A client asks a sensor for the resource /sensors/temp, an addressable item such as a reading. A reply arrives: does it acknowledge that message, answer that request, or do both? Decode its fields before treating the reply as evidence.

An endpoint is a participant identified by its network address and port. A Message ID identifies a message for duplicate detection and acknowledgment matching. A Token is a value chosen by the requester and echoed in the response to match that response to its request. A Code names the requested operation or its result. An option supplies a numbered detail, such as a path segment or payload format. The payload is the application content after those fields.

Your task is to decode an unfamiliar request and response, explain their match, and state what the reply proves. This page uses the CoAP-over-UDP layout described in RFC 7252.

Route Overview

This is part 2 of 3. Review CoAP Messages: Format Foundations for the preceding evidence.

Learning Objectives

  • Decode a request and response into header, Token, options and payload.
  • Use the Code, Message ID and Token to explain the result and match it to the request.

Chapter Roadmap

  • The CoAP Message Format
  • Minimum Viable Understanding: CoAP Message Structure
  • The 4-Byte Fixed Header
  • Message in a Bottle
  • Checkpoint: Header Decisions
  • CoAP Method Codes
  • Idempotent Methods
  • Response Codes
  • Checkpoint: Methods and Codes
  • Token: Request-Response Matching
  • Token Security Consideration
  • CoAP Options
  • CBOR vs JSON for IoT
  • Checkpoint: Tokens and Options
  • Worked Example: Parsing a CoAP Message
  • Worked Example: Decoding a GET Request
  • Worked Example: GET /sensors/temp with JSON Response
  • Putting Numbers to It
  • Knowledge Check: Matching and Sequencing

The CoAP Message Format

Minimum Viable Understanding: CoAP Message Structure

Core Concept: Bytes below use hexadecimal (base 16), with two digits per byte. Read 44 01 7D 34 A1 B2 C3 D4 B7 73 65 6E 73 6F 72 73 04 74 65 6D 70 as a worked request. The first four bytes are the fixed header. 44 selects version 1, a Confirmable message (CON), and four Token bytes. 01 requests GET, meaning retrieve a resource. 7D 34 is Message ID 0x7D34.

Why It Matters: The next four bytes, A1 B2 C3 D4, are the Token. B7 introduces option 11, Uri-Path, with seven value bytes: sensors. The next option header, 04, adds zero to option 11 and takes four bytes: temp. These repeated options name /sensors/temp. No payload marker follows, so this request has no payload.

Key Takeaway: Suppose the sensor replies with header 64 45 7D 34 and the same Token. 64 selects an Acknowledgment (ACK) with four Token bytes; 45 means 2.05 Content. The matching Message ID acknowledges the CON. The echoed Token matches the response to the request. Neither field proves the sensor reading is physically correct.

Generalize from the request: locate the fixed header, then use its Token Length (TKL) to find where the options begin. In the layout below, Ver means version. JSON (JavaScript Object Notation) is a text format for structured values; CBOR (Concise Binary Object Representation) is a binary format. Max-Age specifies a freshness lifetime, and Observe is an option for requesting notifications when a resource changes.

CoAP message layout: compact fixed header followed by optional fields

4-byte fixed header

Ver, Type, TKL, Code, Message ID

Token

0-8 bytes for request-response matching

Options

Uri-Path, Content-Format, Max-Age, Observe, and other metadata encoded with deltas

0xFF

Payload marker

Payload

Application data such as JSON, CBOR, sensor values, or firmware bytes

Header: the first four bytes establish where the Token starts.

Token: use distinct values for outstanding requests to the same endpoint.

Options: sorted numerically so each option can encode only its delta from the previous one.

Payload: present only when the message carries application content after the 0xFF marker.

Read left to right: fixed header, Token, options, then 0xFF and payload when content is present. Token Length locates the options; a marker at an option boundary locates the payload.

The 4-Byte Fixed Header

Return to 44 01 7D 34. Number bytes from zero; the four-byte header contains:

  • Byte 0: Version (2 bits), Type (2 bits), and Token Length (4 bits)
  • Byte 1: Code
  • Bytes 2-3: Message ID
FieldBitsDescription
Ver2Version (always 01 for CoAP 1.0)
T2Type: CON (00), NON (01), ACK (10), RST (11)
TKL4Token Length (0-8 bytes)
Code8Empty (0.00), request method, or response result
Message ID16For deduplication and ACK matching

Header Fields Explained

Version (Ver): Always 01 binary (value 1) for CoAP RFC 7252.

Type (T): Determines reliability and message flow:

TypeBinaryNamePurpose
CON00ConfirmableRequests acknowledgment; retransmitted if needed within retry limits
NON01Non-confirmableNo message-layer ACK; a request can still receive a response
ACK10AcknowledgmentConfirms CON receipt
RST11ResetReceiver could not process the message context

Token Length (TKL): Number of token bytes (0-8). Tokens correlate responses to requests.

Code: Split the byte into class (3 bits) and detail (5 bits), written class.detail with two detail digits. The wire byte is 32 × class + detail: GET 0.01 is 0x01; Content 2.05 is decimal 69, or 0x45. The classes used below are:

ClassRangeMeaning
00.00; 0.01-0.04Empty message; RFC 7252 methods GET, POST, PUT, DELETE
22.01-2.05Success responses
44.00-4.15Client error
55.00-5.04RFC 7252 server error codes listed below

Message ID: 16-bit identifier for:

  • Matching an ACK or RST to the message it acknowledges or rejects, using endpoint context too
  • Detecting duplicates within the applicable duplicate-detection lifetime; it is not a permanent request identifier

When to Use Each Message Type: A Decision Guide

The sensor request uses CON so the client can detect missing acknowledgment and retry within the protocol’s limits. NON omits that acknowledgment. Choose according to whether a later reading can replace a lost one and what result the application needs to verify.

IoT ScenarioRecommended TypeRationale
Periodic temperature readingNON when loss is acceptableA later reading may replace a missed one; define a stale-data rule.
Firmware update chunkCON when acknowledgment is neededDetect loss, then verify reassembly and image integrity separately.
Smoke alarm triggeredCON when acknowledgment is neededReceipt evidence helps, but retries cannot guarantee an alarm reaches a person.
Soil moisture on a constrained linkNON when loss is acceptableCheck link capacity and application requirements before adding retries.
Door lock commandCON when acknowledgment is neededAn ACK reports receipt; verify the command result and physical state separately.
Parking sensor heartbeatNON when later heartbeats sufficeDefine when missing readings make the device stale.
HVAC setpoint changeCON when acknowledgment is neededCheck the response Code for the update result; an empty ACK contains no result.

Use CON for acknowledgment and bounded retries. Use the response Code and application evidence to judge whether the requested work succeeded.

Temperature Terry says: “The bottle’s label and the reply inside answer different questions.”

  • Type: CON asks for acknowledgment; NON does not. Either kind of request can receive an application response.
  • Code: GET asks to retrieve the temperature resource.
  • Message ID: An ACK copies this number to acknowledge the message.
  • Token: The response echoes this value to identify the request it answers.

An empty ACK says the bottle arrived. It does not contain the temperature; a later response can carry that result with the same Token and a different Message ID.

Bex guides the message review.Checkpoint: Header Decisions

For the request 44 01 7D 34, predict what an empty ACK must copy before reading on.

It copies Message ID 7D 34. Its Code is 0.00 and its Token Length is zero, so it carries neither Token nor payload. This acknowledges the message while leaving the GET result pending. A NON request would not require this ACK.

CoAP Method Codes

The running request has Code 01, so the server retrieves /sensors/temp. Change that byte to 03 and the operation becomes PUT; the path alone does not determine the operation. These RFC 7252 methods use numeric codes:

CodeMethodDescriptionIdempotent
0.01GETRetrieve resourceYes
0.02POSTProcess submitted data; may create a resourceNot guaranteed
0.03PUTCreate or replace the target resource stateYes
0.04DELETERemove resourceYes
Idempotent Methods

An idempotent method has the same intended effect when an identical request is applied repeatedly as when it is applied once. This does not require identical response bytes:

  • GET /temperature requests a reading without asking to change state. Temperature may change between reads.
  • PUT /led {"on": true} requests the same final state each time.
  • DELETE /alarm/5 requests removal each time; a later response can report that the resource is already absent.

POST has no general idempotence guarantee. Separate POST /log {"event": "click"} requests may append separate entries.

A CoAP retransmission repeats the same message, including its Message ID, so duplicate detection can avoid processing it again. Starting a new request after a timeout is different. Review application duplicate handling before repeating a non-idempotent operation; idempotence does not guarantee delivery or success.

Response Codes

The running response uses 0x45: 2 × 32 + 5, or 2.05 Content. First interpret class, then detail. The HTTP columns compare meanings; they are not complete proxy translation rules.

Success (2.xx)

CodeNameHTTP analogyUse Case
2.01Created201 CreatedPOST created new resource
2.02Deleted200 OK (for DELETE)Resource removed
2.03Valid304 Not ModifiedCached response still valid
2.04Changed200 OK (for PUT)Resource updated
2.05Content200 OKGET successful with payload

Client Error (4.xx)

CodeNameHTTP analogyCause
4.00Bad Request400Malformed request
4.01Unauthorized401Missing authentication
4.03Forbidden403Access denied
4.04Not Found404Resource doesn’t exist
4.05Method Not Allowed405Wrong method for resource
4.12Precondition Failed412A request precondition was not met
4.15Unsupported Content-Format415Request payload format unsupported for this resource/method

Server Error (5.xx)

Server errors mean a server or gateway could not complete the operation. 5.00 Internal Server Error reports an unexpected server condition; 5.01 Not Implemented reports missing method capability. 5.03 Service Unavailable reports temporary unavailability. For a gateway, 5.02 Bad Gateway distinguishes an invalid upstream response from the missing timely response reported by 5.04 Gateway Timeout. These Codes locate a failure; they do not alone decide whether retrying is safe.

CodeNameHTTP analogyCause
5.00Internal Server Error500Unexpected server condition prevented completion
5.01Not Implemented501Method not supported
5.02Bad Gateway502Proxy error
5.03Service Unavailable503Server overloaded
5.04Gateway Timeout504Proxy timeout

Bex guides the message review.Checkpoint: Methods and Codes

Predict the wire Code for a successful PUT update of an existing resource. Would an empty ACK supply that result?

The result is 2.04 Changed, encoded as 2 × 32 + 4 = 68, or 0x44. An empty ACK has Code 0.00, so it cannot report that update result. Creation by PUT can instead return 2.01 Created; inspect the operation outcome before choosing the detail.

Token: Request-Response Matching

The running response echoes Token A1B2C3D4. If an empty ACK arrived first, a separate response would still echo that Token but use its own Message ID. Match the endpoint and Token to the pending request.

Transfer that rule to two outstanding requests. The replies below arrive in the opposite order:

Client sends: GET /temperature, Token=0xAB12, MsgID=0x5678
Client sends: GET /humidity, Token=0xCD34, MsgID=0x5679

Server sends: 2.05 Content, Token=0xCD34, "65%"  (humidity response)
Server sends: 2.05 Content, Token=0xAB12, "22.5" (temperature response)

Token vs. Message ID:

AspectTokenMessage ID
PurposeMatch response to requestDeduplication, ACK matching
ScopeCoAP request/response matching within endpoint contextCoAP message matching within endpoint context
Length0-8 bytes (TKL field)Fixed 16 bits
PersistenceEchoed in response; unchanged on retransmissionUnchanged on retransmission; separate response uses its own ID
Generated byClient (the requester)Sender of each new CON or NON message; an ACK or RST copies it
Token Security Consideration

A Token matches a response; it does not authenticate the sender. Avoid predictable tokens where they could help an attacker guess a pending request. Use an authenticated security mechanism, such as Datagram Transport Layer Security (DTLS), for peer authentication and message protection. Randomness alone does not provide either.

The Python snippet illustrates random byte generation. A complete implementation must also avoid collisions among outstanding request tokens; four random bytes are not a universal security guarantee.

# BAD: Sequential tokens
token = counter
counter += 1

# GOOD: Random tokens
import os
token = os.urandom(4)

Knowledge check · self-test

Knowledge check

Test your understanding.

CoAP Options

The sensor request repeats Uri-Path option 11 for sensors and temp. Its response uses Content-Format option 12 to identify payload encoding. An option has a number, a length and value bytes. Options appear in nondecreasing number order, including repeated numbers.

Common Options

Option NumberNameEncoding / lengthPurpose
3Uri-HostStringTarget host
7Uri-Port0-2 bytesTarget port
11Uri-PathStringPath segments (/sensors/temp)
12Content-Format0-2 bytesPayload media type
14Max-Age0-4 bytesFreshness lifetime in seconds
17Accept0-2 bytesAcceptable response format
35Proxy-UriStringFor proxied requests

Option Delta Encoding

Start the option-number accumulator at zero. In the sensor request, B7 has high nibble B (decimal 11) and low nibble 7. Add delta 11 to zero to obtain option 11, then read seven value bytes: sensors. The next header, 04, adds zero to option 11 and takes four bytes: temp. Both options are Uri-Path.

This is delta encoding: each option stores the increase from the previous option number. A nibble is four bits. The high nibble represents delta and the low nibble represents length:

  • Values 0–12 encode the delta or length directly.
  • Value 13 means read one extra byte and add 13.
  • Value 14 means read two extra bytes as an unsigned integer and add 269.
  • Value 15 is reserved and cannot encode an option delta or length.

Read any delta extension first, then any length extension, then the value bytes. At an option boundary, 0xFF marks the start of a nonempty payload rather than another option. An FF byte inside an option value is just value data.

For /sensors/temp, the encoding is B7 | "sensors" | 04 | "temp". It occupies (1 + 7) + (1 + 4) = 13 bytes, excluding header and Token. Stop at the datagram end when no payload follows; do not search beyond it for a marker.

Content-Format Codes

The Content-Format option tells the receiver how to decode the payload. In the sensor response, C1 32 means delta 12 from zero, length one, value hexadecimal 32 (decimal 50). Option 12 is Content-Format; value 50 identifies JSON (JavaScript Object Notation). The receiver can now choose its payload decoder. The table lists media types, the named formats associated with those numeric identifiers. Accept, option 17, instead expresses which response format the requester wants. The shown request has no Accept option; assume this resource is agreed to return JSON.

CodeMIME TypeDescription
0text/plainSimple text
40application/link-formatResource discovery
41application/xmlXML data
42application/octet-streamBinary data
47application/exiEfficient XML
50application/jsonJSON data
60application/cborCompact Binary (CBOR)
CBOR vs JSON for IoT

CBOR (Concise Binary Object Representation) encodes structured values in binary. JSON encodes them as text. Format selection changes how payload bytes must be decoded, not which request the Token matches.

For {"device":"temp42","value":23.5,"unit":"C"}, measure the complete serialized bytes in each supported format before claiming a saving. An incomplete hexadecimal prefix cannot establish a CBOR size. Choose a format both endpoints implement; use Content-Format 50 for JSON or 60 for CBOR. Development versus production alone does not decide the choice.

Bex guides the message review.Checkpoint: Tokens and Options

A response has Token A1B2C3D4 and begins its options with C1 32. Predict its request match and payload decoder.

The Token matches the pending sensor request in the same endpoint context. Starting from option number zero, delta 12 selects Content-Format, length one takes the value 32 hexadecimal, and decimal 50 selects JSON. The Token does not select a payload format; the option does.

Worked Example: Parsing a CoAP Message

Transfer the running example to an unfamiliar path and Token. Decode the following bytes before checking each step. What changes in the request, and does it carry a payload?

Worked Example: Decoding a GET Request

Raw bytes (hexadecimal):

44 01 5A F2 AB CD 00 00 B5 68 65 6C 6C 6F

Step 1: Parse fixed header (4 bytes)

Offsets below count from zero. Hexadecimal notation uses base 16; ASCII maps the displayed path bytes to text characters.

Offset 0: 0x44 = 0100 0100 binary

  • Ver = 01 = Version 1 (valid CoAP)
  • T = 00 = CON (Confirmable)
  • TKL = 0100 = 4 (4-byte token)

Offset 1: 0x01 = Code

  • Class = 0, Detail = 01 = 0.01 = GET

Offsets 2-3: 0x5AF2 = Message ID = 23282

Step 2: Parse token (TKL = 4 bytes)

Offsets 4-7: AB CD 00 00 = Token = 0xABCD0000

Step 3: Parse options

Offset 8: 0xB5 = 1011 0101

  • Option Delta = 11 (decimal) = Uri-Path
  • Option Length = 5

Offsets 9-13: 68 65 6C 6C 6F = ASCII “hello”

Decoded message:

FieldValue
Version1
TypeCON (Confirmable)
MethodGET
Message ID23282
Token0xABCD0000
Uri-Path/hello

Result: This is CON GET /hello, with no payload. If the destination is named server, the URI is coap://server/hello; that host name is context, not a field decoded from these bytes.

A separate response can answer this request using Token 0xABCD0000 and its own Message ID. Check endpoint and Token rather than rejecting it for an unequal Message ID.

Worked Example: Complete Sensor Reading – CoAP vs HTTP

Worked Example: GET /sensors/temp with JSON Response

Return to the running sensor exchange and account for its bytes. The CoAP request and response are fully specified below. The HTTP request is an illustrative serialization, not a complete performance benchmark.

Scenario: A gateway requests /sensors/temp. Assume the destination endpoint is already known, no Uri-Host is needed for routing, and the resource contract specifies JSON. The bytes do not carry the name sensor.local or an Accept option.


CoAP Request (21 bytes total):

Offset  Hex          Binary             Field
------  ---          ------             -----
 0      44           0100 0100          Ver=1, T=CON, TKL=4
 1      01           0000 0001          Code=0.01 (GET)
 2-3    7D 34        0111 1101 0011 0100  MsgID=32052
 4-7    A1 B2 C3 D4  (example bytes)     Token=0xA1B2C3D4
 8      B7           1011 0111          OptDelta=11(Uri-Path), OptLen=7
 9-15   73 65 6E 73 6F 72 73            "sensors"
16      04           0000 0100          OptDelta=0(Uri-Path), OptLen=4
17-20   74 65 6D 70                     "temp"

Total: 21 CoAP bytes = 4 header + 4 Token + 13 options. Adding the 8-byte UDP header gives 29 bytes before the IP header and link framing. No payload marker is needed.


Illustrative HTTP/1.1 Request:

GET /sensors/temp HTTP/1.1\r\n         (28 bytes)
Host: sensor.local\r\n                 (20 bytes)
Accept: application/json\r\n           (26 bytes)
Connection: keep-alive\r\n             (24 bytes)
\r\n                                   (2 bytes)

The displayed lines total 100 bytes: 28 + 20 + 26 + 24 + 2. The Connection line is optional; this is not a minimum. This HTTP request explicitly asks for JSON, while the shown CoAP request relies on the resource contract. Count transport, IP, security and link overhead separately before comparing actual exchanges.


CoAP Response (35 bytes total):

Offset  Hex          Field
------  ---          -----
 0      64           Ver=1, T=ACK, TKL=4
 1      45           Code=2.05 (Content)
 2-3    7D 34        MsgID=32052 (matches request)
 4-7    A1 B2 C3 D4  Token=0xA1B2C3D4 (matches request)
 8      C1           OptDelta=12(Content-Format), OptLen=1
 9      32           Value=50 (application/json)
10      FF           Payload marker
11-34   {"temp":22.5,"unit":"C"}       (24 bytes JSON payload)

Total: 35 bytes. The ACK + response is piggybacked — one message serves as both “I received your request” and “here is the data.”


Size Comparison Summary:

ComponentCoAPHTTP/1.1What can be concluded
Shown request21 bytes100 bytesThese requests differ in fields as well as size.
Shown response35 bytesNot specifiedNo response-size ratio can be calculated.
TransportUDPTCPAdd actual transport and IP headers from a capture.
Connection setupPlain UDP has no transport handshakeA new TCP connection needs setupReused connections and security setup change the comparison.

These counts establish message sizes only. Radio airtime and battery use require a link and device model or measurements.

Reproduce the CoAP totals before estimating any cost:

  • Request: 4 + 4 + (1 + 7) + (1 + 4) = 21 bytes.
  • Response: 4 + 4 + (1 + 1) + 1 + 24 = 35 bytes. The terms are header, Token, Content-Format, marker and JSON payload.
  • CoAP message bytes for this pair: 21 + 35 = 56 bytes. This excludes UDP, IP, security, link framing and retransmissions.

If a decoder reports a different size, check Token Length, the repeated Uri-Path option and the payload boundary. Do not turn a byte total into battery lifetime without measuring transmit, receive, idle and retry costs.

Transfer prediction: The sensor first sends an empty ACK with Message ID 0x7D34. It later sends a CON response with a different Message ID and Token 0xA1B2C3D4. Should the client discard the response because its Message ID differs?

Answer and reason: No. The empty ACK matches the original CON by Message ID. The separate response matches the request by endpoint and Token; the client acknowledges that new CON using its new Message ID. Neither acknowledgment proves the temperature is accurate.

Knowledge Check: Matching and Sequencing

Apply the running sensor trace. Match each observed field to the decision it supports, then order the decoding steps for its response.

Knowledge check · self-test

Knowledge check

Test your understanding.

The matching answers separate request correlation, acknowledgment, path reconstruction, format selection and payload location. Decoding follows field lengths: read the header to find the Token end, then options to find the marker. Recognize the marker only at an option boundary, so an option value byte cannot end the options by mistake.

A reply can acknowledge a message without completing its request. Keep endpoint, Message ID, Token, Code and decoded content together when diagnosing a capture.

A CoAP client has two in-flight requests: GET /temperature (Token=0xAA, MsgID=0x0001) and GET /humidity (Token=0xBB, MsgID=0x0002). The CON for temperature times out and is retransmitted. What values should the retransmission carry?

Token=0xAA, MsgID=0x0001 (same token and message ID)

Correct! On retransmission of a CON, both the Token AND the Message ID stay the same. The same Message ID allows the server to detect and discard the duplicate; the same Token ensures the eventual response is still matched to the correct pending request.

Two CON requests use Token 0xC1 with MID 0x1001 and Token 0xD2 with MID 0x1002. Which fields identify the empty ACK for the second request?

MID 0x1002, Code 0.00 and zero-length Token on the empty ACK.

Correct. An empty ACK matches the CON by Message ID and endpoint context; Code and Token Length are both zero, so it carries no result.

You capture a CoAP packet with first byte 0x50. What can you determine about this message?

Version 1, NON type, and a zero-length Token from header 0x50.

Correct! 0x50 = 0101 0000. Ver=01 (version 1), T=01 (NON), TKL=0000 (no token). This is a Non-confirmable message with no token.

A CoAP packet begins with byte 0x64. What does its first header byte encode?

CoAP v1 ACK with TKL=4.

Correct. 0x64 has version bits 01, type bits 10, and TKL bits 0100.

Continue to the Next Part

Carry this evidence into CoAP Messages: Parsing and Validation, which begins with Label the Diagram.

Hi, I’m Broker Bex. What do you need?

Find help

Let’s find what you need

Find a lesson or return to your module guide.

Give feedback

Help improve this chapter

Tell us what helped or what needs fixing.

Tips

Try a small next step

A few ways to get more from this chapter.

Ask AI

Continue the conversation

Take the conversation further with your preferred assistant.

AI help is available in supported modules when enabled in Settings.

No live person answers on independent study. Feedback does not promise a personal reply.

For welfare or safety concerns, follow your school’s procedures outside IoTClass.