Example: MQTT connect

This example provides insight into the structure of packets in MQTT as well as the interaction between the client and broker. MQTT uses different packets to accomplish tasks such as connecting, subscribing, and publishing. You can use XCTU to perform a basic example of sending a broker a connect packet and receiving the response from the server, without requiring any coding. This is a good way to see how the client interacts with the broker and what a packet looks like. The following table is an example connect packet:

  Description Hex value
CONNECT packet fixed header
byte 1 Control packet type 0x10
byte 2 Remaining length 0x10
CONNECT packet variable header
Protocol name
byte 1 Length MSB (0) 0x00
byte 2 Length LSB (4) 0x04
byte 3 (M) 0x4D
byte 4 (Q) 0x51
byte 5 (T) 0x54
byte 6 (T) 0x54
Protocol level
byte 7 Level (4) 0x04
Connect flags
byte 8

CONNECT flags byte, see the table below for the bits.

0x02
Keep alive
byte 9 Keep Alive MSB (0) 0x00
byte 10 Keep Alive LSB (60) 0x3C
Client ID    
byte 11 Length MSB (0) 0x00
byte 12 Length LSB (4) 0x04
byte 13 (D) 0x44
byte 14 (I) 0x49
byte 15 (G) 0x47
byte 16 (I) 0x49

The following table describes the fields in the packet:

Field name

Description

Protocol Name

The connect packet starts with the protocol name, which is MQTT. The length of the protocol name (in bytes) is immediately before the name itself.

Protocol Level

Refers to the version of MQTT in use, in this case a value of 4 indicates MQTT version 3.1.1.

Connect Flags

Indicate certain aspects of the packet. For simplicity, this example only sets the Clean Session flag, which indicates to the client and broker to discard any previous session and start a new one.

Keep Alive

How often the client pings the broker to keep the connection alive; in this example it is set to 60 seconds.

Client ID

The length of the ID (in bytes) precedes the ID itself. Each client connecting to a broker must have a unique client ID. In the example, the ID is DIGI. When using the Paho MQTT Python libraries, a random alphanumeric ID is generated if you do not specify an ID.

The following table provides the CONNECT flag bits from byte 8, the CONNECT flags byte.

CONNECT Flag Bit(s) Bit 7 Bit 6 Bit 5 Bit 4 Bit 3 Bit 2 Bit 1 Bit 0
User name flag 0              
Password flag   0            
Will retain     0          
Will QoS       0 0      
Will flag           0    
Clean session             1  
Reserved               0