Understanding TFTP Protocol: Packet Structure and Implementation Guide

In this section, we examine the assembly of TFTP packets, laying the groundwork for implementing the protocol in our code. The TFTP protocol consists of five different types of packets, corresponding to read requests, write requests, data blocks, acknowledgment responses (ACK), and errors. The first two packet types share the same format, with differences in certain field settings, while the remaining three packet types each have distinct formats. Regardless of the packet type, they all contain a field known as the opcode, which defines the packet type.

Let’s first look at the formats of the read request and write request packets. Initially, there is a 2-byte field representing the opcode, which indicates the type of the packet; a value of 1 signifies a read request, while 2 indicates a write request. Next is a variable-length field representing the filename to be read or uploaded, using ASCII code and terminated by a 0. The third field is called Mode, another variable-length field indicating the type of data to be transferred. If the file is a text file, the string “netascii” is used, and if the file is binary, the string “octet” is used. These strings are also terminated by a 0, as illustrated in the diagram below:

TFTP protocol

Let’s look at the corresponding Wireshark packet capture.

Next, let’s examine the data block transfer packet. Its first 2 bytes are also the opcode, and a value of 3 signifies that the packet is used for data block transfer. Following that is a 2-byte field for the block number, and finally, a variable-length Data field that carries the data block. The structure of this packet is as follows:

TFTP protocol />

We can see the corresponding Wireshark packet capture:

Then there is the acknowledgement packet, starting with a 2-byte opcode of 4, followed by a 2-byte block number of the received data block, as shown in the structure below:

The last one is the error packet. The first 2 bytes represent the opcode, with a value of 5; the following 2 bytes represent the error code: 0 for unknown error, 1 for file not found, 2 for insufficient permissions, and 3 for disk full. We will analyze specific error codes in practice. The next is a variable-length field that describes the specific error in the form of a string. The structure of this packet is as follows:

Its corresponding Wireshark packet capture is as follows:

Next, let’s look at how to implement the TFTP protocol in code.