---
title: 其他网络主题
url: https://doc.liz6.com/linux-kernel/06-network-subsystem/04-other-network-topics
locale: zh
area: linux-kernel
tags:
- linux-kernel
- 网络子系统
date: 2026-06-30
modified: 2026-06-30
description: '覆盖: VLAN/bridge/bonding → tunneling (GRE/VXLAN/IPIP) → routing (FIB/FIB rules) → QoS (tc qdisc) → network namespace → TUN/TAP 内核版本: 2.6 ~ 6.x'
---

# 其他网络主题

> 覆盖: VLAN/bridge/bonding → tunneling (GRE/VXLAN/IPIP) → routing (FIB/FIB rules) → QoS (tc qdisc) → network namespace → TUN/TAP
> 内核版本: 2.6 ~ 6.x

## 虚拟网络设备

### bridge: 软件交换机

```c
// net/bridge/
// Linux bridge = 虚拟 L2 交换机
// 功能: MAC learning, STP (可选), VLAN filtering
// 典型用途: VM/容器之间的 L2 连通, 配合 veth pair

brctl addbr br0
brctl addif br0 eth0  // 物理口加入 bridge
ip link add veth0 type veth peer name veth1  // virtual ethernet pair
brctl addif br0 veth0  // 一头接 bridge, 另一头放容器 namespace
```

### bonding: 链路聚合

```
bonding mode:
  balance-rr:   轮询 (TX 负载均衡)
  active-backup: 一主一备 (故障转移)
  balance-xor:  按 MAC hash
  802.3ad:      LACP 动态聚合
```

### VLAN: 802.1Q

```bash
ip link add link eth0 name eth0.100 type vlan id 100
# → eth0.100: VLAN-tagged 子接口
# 内核自动加/剥 VLAN tag
```

## 隧道

| 隧道类型 | 封装 | 用途 |
|---------|------|------|
| GRE | IP-in-IP (GRE header) | 站点互连 |
| VXLAN | L2 over UDP | 数据中心 overlay |
| IPIP | IP-in-IP (无 GRE 头) | 轻量隧道 |
| WireGuard | UDP + Noise + ChaCha20 | VPN |

```bash
# VXLAN 示例
ip link add vxlan0 type vxlan id 100 remote 10.0.0.2 dstport 4789 dev eth0
```

## 路由

```c
// net/ipv4/fib_trie.c (FIB = Forwarding Information Base)
// Linux 路由是 FIB + FIB rules 两层结构:

// FIB rules (策略路由):
//   ip rule: 根据 src IP, fwmark, iif 选择路由表
//   默认: local (表 255) → main (表 254) → default (表 253)

// FIB (转发表):
//   LC-trie 实现 (最長前綴匹配, O(log n))
//   表项: prefix → nexthop + device
```

## QoS: Traffic Control (tc)

```c
// net/sched/
// tc 的排队规则 (qdisc) 栈:
//   root qdisc: 出站包的入口 (可能有子 class)
//   ingress qdisc: 入站入口 (少见)

// 常见 qdisc:
//   fq_codel: 公平队列 + 主动队列管理 (减少 bufferbloat, 默认)
//   cake:    家庭网关优化 (带宽整形 + 公平)
//   htb:     分层令牌桶 (带宽限制)
//   pfifo_fast: 简单的 FIFO (旧默认)

// BPF 也集成在 tc: 可挂 BPF 程序作为 classifier/action
```

## Network Namespace

```c
// net/core/net_namespace.c
// 每个 netns 有独立的:
//   - 网卡列表
//   - 路由表
//   - netfilter 规则
//   - socket 绑定

// 容器的基础: 
//   CLONE_NEWNET → 新 netns
//   veth pair 连接 host 和 container netns
//   bridge 把多个 container 连在一起
```

## TUN/TAP

```c
// drivers/net/tun.c
// TUN: L3 隧道 (IP 包, /dev/net/tun)
// TAP: L2 隧道 (Ethernet frame)

// 用户空间程序打开 /dev/net/tun → 读写 IP 包
//   → VPN (OpenVPN, WireGuard), VM (QEMU, Firecracker)
```

## 参考

- **源码**: `net/bridge/`, `net/core/rtnetlink.c`, `net/sched/`, `drivers/net/tun.c`, `net/core/net_namespace.c`
- **内核文档**: `Documentation/networking/bridge.rst`, `Documentation/networking/ip-sysctl.rst`

*关键词: bridge, VLAN, VXLAN, tc, qdisc, network namespace, TUN/TAP*
