xkcptun 基于kcp和libevent2库,用c语言实现的kcptun
August 26, 2026 · View on GitHub

xkcptun 基于kcp和libevent2库,用c语言实现的kcptun
xkcptun主要应用于LEDE,openwrt中,其原理如图:
Compile
xkcptun依赖libevent2
干净 Ubuntu/Debian 上建议先装编译工具链:
sudo apt-get install -y build-essential cmake
cmake 默认会检测 pkg-config 和 libevent;若缺失,会尝试用 apt 自动安装 pkg-config、libevent-dev(需要 root,或当前用户可用 sudo 且无需交互输密码)。关闭自动安装:cmake -DAUTO_INSTALL_DEPS=OFF ..
也可手动安装依赖:sudo apt-get install -y pkg-config libevent-dev
git clone https://github.com/liudf0716/xkcptun.git
cd xkcptun
mkdir build && cd build
cmake ..
make
生成xkcp_client, xkcp_server, xkcp_spy
参考文档
OpenWrt
编译及安装请参考 openwrt-xkcptun
QuickStart
为方便理解和使用,我们将使用场景放在同一台pc上,pc使用ubuntu系统,我们通过xkcptun来访问本机的http server
假设pc的 eth0 ip 为 192.168.199.18, http server的监听端口为80端口,xkcptun的server和client配置分别如下:
server.json 如下:
{
"localinterface": "eth0",
"localport": 9089,
"remoteaddr": "192.168.199.18",
"remoteport": 80,
"key": "14789632a",
"crypt": "none",
"mode": "fast3",
"mtu": 1350,
"sndwnd": 1024,
"rcvwnd": 1024,
"datashard": 10,
"parityshard": 3,
"dscp": 0,
"nocomp": true,
"acknodelay": false,
"nodelay": 0,
"interval": 20,
"resend": 2,
"nc": 1,
"sockbuf": 4194304,
"keepalive": 10
}
client.json如下:
{
"localinterface": "eth0",
"localport": 9088,
"remoteaddr": "192.168.199.18",
"remoteport": 9089,
"key": "14789632a",
"crypt": "none",
"mode": "fast3",
"mtu": 1350,
"sndwnd": 1024,
"rcvwnd": 1024,
"datashard": 10,
"parityshard": 3,
"dscp": 0,
"nocomp": true,
"acknodelay": false,
"nodelay": 0,
"interval": 20,
"resend": 2,
"nc": 1,
"sockbuf": 4194304,
"keepalive": 10
}
注意:mode 字段(fast3/fast2/fast/normal)会覆盖 nodelay、interval、resend、nc 四个字段的值(与 kcptun 行为一致)。如需精细调优,请直接设置这四个字段并删除 mode。
FEC 前向纠错(实验性)
在两端配置中增加布尔字段 fec 即可启用前向纠错:
"fec": 1
- 启用后,每个 UDP 报文会带上 8 字节自描述帧头,并按
datashard/parityshard分组生成 Reed-Solomon 校验包;接收端只要收到组内任意datashard个分片即可还原全部数据,无需重传。 - FEC 只在持续满速传输时提供保护:未攒满一组的零散包会立即裸发,不增加任何延迟。
- 启用 FEC 时 KCP 的 MTU 会自动下调 8 字节以容纳帧头,无需手工调整
mtu。 - 两端必须同时启用或同时关闭,且
datashard/parityshard取值一致,否则无法互通。取值范围:datashard164,64。链路较差时可增大parityshard0parityshard(带宽开销约为parityshard/(datashard+parityshard));好链路建议直接关闭以省流量。
分别运行:
xkcp_server -c server.json -f -d 7
xkcp_client -c client.json -f -d 7
[注] 以上命令都是运行在debug和前台运行模式,正式部署的时候要把 -f 去掉, -d 0 如: xkcp_server -c server.json -d 0
curl http://192.168.199.18:9088
其执行效果与curl http://192.168.199.18 等同
xkcp_spy -h 192.168.199.18 -s -t status
查看服务器端的情况
xkcp_spy -h 192.168.199.18 -c -t status
查看客户端的情况
Todo
Compatible with kcptun 
How to contribute our project(给本项目做贡献)
欢迎大家给本项目提供意见和贡献,提供意见的方法可以在本项目的Issues提,更加欢迎给项目提PULL REQUEST,具体提交PR的方法请参考CONTRIBUTING
Contact me
QQ群 : 331230369