实现一个简单的TFTP文件服务器

陪她去流浪 桃子 阅读次数:237

TFTP(Trivial File Transfer Protocol)是一个非常早期的基于UDP协议的可靠文件传输协议。其可靠性基于最简单的停等协议实现(即:Stop-and-WAIT ARQ协议),和TCP的三次握手阶段一样,必须等到对方回复后才会继续发送下一个数据包。可见其性能非常一般。

但是由于它是基于UDP的,甚至可以直接构造IP包,所以可以离谱到裸机都可以跑,完全不需要操作系统或复杂的网络栈,实现也非常简单。所以,它能在嵌入式设备上“发光发热”就不足为奇了。

由于不知道具体的协议,硬是给我如何给我的Cudy TR3000路由器恢复原厂固件带来了麻烦。我甚至搞不懂为什么要给电脑设置手动IP地址。更好奇的是 U-Boot 如何能“塞”进去一个网络栈以下载固件?

看了4️⃣篇RFCs文档才知道了协议的具体细节。加上在一头雾水的情况了试用了几个别人写的,真是一言难尽。所以就决定自己写个最简能用的就行。我为什么不用系统的/自己安装?

  1. MacOS上好像是自带的,但是要启动为一个后台服务,甚至还要launchctl来启动,太抽象了

  2. Linux作为嵌入式开发主力设备,居然不自带,虽然前几天用过一次并成功了,还是觉得麻烦

  3. Windows上有一个比较常见的,但是实在丑拒,另外,我没有 Windows 系统。

其实最大的问题是:不能跨平台使用。除了 Windows 开发,谁现在还用 Windows 开发啊?

我的项目地址在这里:movsb/tts: A tiny/trivial² TFTP server that just works.

零依赖,零配置,开箱应用,用完即弃。

我的目的明明是为了救砖,你们为什么搞那么复杂?


服务器运行示例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
Downloads → sudo ~/code/tts/tts
2025/12/29 22:46:52 192.168.10.230:59750 ReadFile: 2.docx [{tsize 0} {blksize 1024} {rollover 0}]
2025/12/29 22:46:52 192.168.10.230:59750 Ignored unsupported option: {tsize 0}
2025/12/29 22:46:52 192.168.10.230:59750 Ignored unsupported option: {rollover 0}
2025/12/29 22:46:53 192.168.10.230:59750 Sent block: 1/14 (7%)
2025/12/29 22:46:53 192.168.10.230:59750 Sent block: 2/14 (14%)
2025/12/29 22:46:53 192.168.10.230:59750 Sent block: 3/14 (21%)
2025/12/29 22:46:53 192.168.10.230:59750 Sent block: 4/14 (28%)
2025/12/29 22:46:53 192.168.10.230:59750 Sent block: 5/14 (35%)
2025/12/29 22:46:53 192.168.10.230:59750 Sent block: 6/14 (42%)
2025/12/29 22:46:53 192.168.10.230:59750 Sent block: 7/14 (50%)
2025/12/29 22:46:53 192.168.10.230:59750 Sent block: 8/14 (57%)
2025/12/29 22:46:53 192.168.10.230:59750 Sent block: 9/14 (64%)
2025/12/29 22:46:53 192.168.10.230:59750 Sent block: 10/14 (71%)
2025/12/29 22:46:53 192.168.10.230:59750 Sent block: 11/14 (78%)
2025/12/29 22:46:53 192.168.10.230:59750 Sent block: 12/14 (85%)
2025/12/29 22:46:53 192.168.10.230:59750 Sent block: 13/14 (92%)
2025/12/29 22:46:53 192.168.10.230:59750 Sent block: 14/14 (100%)
2025/12/29 22:46:53 192.168.10.230:59750 Sent completed successfully.
2025/12/29 22:46:53 192.168.10.230:59750 Connection closed.

客户端运行示例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
tmp → tftp 192.168.10.230 69
tftp> options on
Support for RFC2347 style options are now enabled.
Support for non-RFC defined options are now enabled.

The following options are available:
	options on	: enable support for RFC2347 style options
	options off	: disable support for RFC2347 style options
	options extra	: toggle support for non-RFC defined options
tftp> blocksize 1024
Blocksize is now 1024 bytes.
tftp> get 2.docx
Received 14328 bytes during 1.0 seconds in 14 blocks
tftp>