Skip to content

TUN — Xray-core

Xray-core 在 proxy/tun 提供 TUN 入站:创建 TUN 设备、读取原始数据包, 并在分发给出站之前用一个最小化的进程内网络栈解码它们。早期版本需要你 自行设置路由、DNS 与防火墙规则;近期版本新增了可选的辅助项 —— gatewaydnsautoSystemRoutingTableautoOutboundsInterface —— 让 Xray 自动安装系统路由表条目并把出站绑定到某个物理接口。

它仍然比 sing-box / mihomo 的 TUN 栈更轻量:没有 strict-routeauto-redirect,也没有 UID / 包过滤。若需要这些能力,请用 sing-box 或 mihomo 作为 TUN 前端,再把它们的出站经 Xray 转出。

入站

"protocol": "tun"settings

字段类型默认值允许值描述
namestringxray0<interface name>TUN 设备名称。启动时创建。
mtuuint321500<bytes>设备的最大传输单元(MTU)。
gateway[]string<ip address> | …分配给 TUN 接口的网关地址。
dns[]string<ip address> | …在 TUN 接口上配置的 DNS 服务器地址。
userLeveluint320<uint32>经此入站收到的连接的默认策略等级。
autoSystemRoutingTable[]string<routing-table entry> | …设置后,Xray 会自动安装把流量引入设备的系统路由表条目。提供该列表即启用自动路由。
autoOutboundsInterface*stringauto<interface name> | auto出站连接绑定的物理接口,用于防止路由环路。设置了 autoSystemRoutingTable 时默认为 "auto"。

源码: infra/conf/tun.go:8-16 · 锚定版本 v26.6.1 (94ffd50)

示例

json
{
  "inbounds": [{
    "tag": "tun-in",
    "protocol": "tun",
    "settings": {
      "name": "xray0",
      "mtu": 9000
    }
  }]
}

若想让 Xray 自行管理路由,加上 autoSystemRoutingTable(并可选地固定 出站接口):

json
{
  "inbounds": [{
    "tag": "tun-in",
    "protocol": "tun",
    "settings": {
      "name": "xray0",
      "mtu": 1500,
      "autoSystemRoutingTable": ["main"],
      "autoOutboundsInterface": "auto"
    }
  }]
}

或者改为手动配置系统网络:

sh
# Linux 示例
ip addr add 198.18.0.1/30 dev xray0
ip link set xray0 up

# 全部走 xray0(管理子网除外)
ip route add 1/1 dev xray0
ip route add 128/1 dev xray0

# DNS 劫持
iptables -t nat -A OUTPUT -p udp --dport 53 -j REDIRECT --to-port 5353
# (再在 5353 上放一个 Xray dokodemo-door 入站)

说明

  • Xray 的 TUN 入站是底层数据包读取器。它自身不解析 TCP/IP,而是把 数据包交给一个最小化的进程内网络栈处理,再分发给出站。
  • Linux 上常见用法:搭配 dokodemo-door 入站 + 手写的 iptables 规则集来实现透明代理,或者设置 autoSystemRoutingTable 让 Xray 自行安装路由。
  • autoSystemRoutingTable 让 Xray 自动管理系统路由表条目;当它存在 而 autoOutboundsInterface 省略时,出站接口默认为 autogatewaydns 设置设备上的地址与解析器。
  • Windows / macOS 上 Xray TUN 入站会创建 wintun / utun 设备。带 autoSystemRoutingTable 时它能为你接好路由;否则需自行脚本化。 这些平台上许多用户仍倾向使用 sing-box 或 mihomo —— 它们的 TUN 功能集更丰富。

跨内核说明

  • sing-box 提供功能齐全的 TUN 入站,含 auto_routeauto_redirectstrict_routeroute_address、UID / 包过滤, 以及按平台的协议栈选择(gVisor / system / mixed)。参见 TUN — sing-box
  • mihomo 在顶层 tun: 块提供同等齐全的 TUN 入站,选项集合相同, 但字段名采用 kebab-case。参见 TUN — mihomo

源码: infra/conf/tun.go:8-16 · v26.6.1 (94ffd50)

由 Argsment 出品的 Core Tutorial