目标: 整理Linux虚拟网络基础知识,包含如下内容:
1 tap
2 namespace
3 veth pair
4 Bridge
5 Router
6 tun
7 iptables
8 总结
1 tap
1.1 tap基础
tap: 二层虚拟网络设备,虚拟以太网设备,对应以太网Ethernet协议
tun: 三层虚拟网络设备
tun/tap数据结构:
struct tun_struct {
char name[8]; //设备名
unsigned long flags; //区分tun和tap设备
struct fasync_struct *fasync; //文件异步通知结构
wait_queue_head_t read_wait; //等待队列
struct net_device dev; //Linux抽象网络设备结构
struct sk_buff_head txq; //网络缓冲区队列
struct net_device_stats stats; //网卡状态信息结构
};
1.2 tap命令
Linux使用tun模块实现tun/tap
modinfo tun: 证明有tun模块
lsmod|grep tun: 查看tun是否加载
modprobe tun: 加载tun
tunctl help: tun操作工具
yum install tunctl: 安装tunctl
tunctl -t tap_chao: 创建一个tap设备
ip link list: 查看创建的tap
...
l3: tap_chao: ........
ip addr add local 192.168.100.1/24 dev tap_chao: 给tap绑定ip地址
2 namespace
2.1 namespace基础
namespace作用: 资源隔离。
namespace隔离的资源:
net_ns: 网络信息
ipc_ns: 与进程间通信(ipc)有关的信息
pid_ns: 进程id的信息
mnt_ns: 当前状态的文件系统
namespace包含:
独立的网络协议栈,含网络设备接口,ipv4,ipv6等
2.2 namespace命令
ip netns用于操作namespace
ip netns list: 查看namespace列表
ip netns add ns_chao: 创建一个名字为ns_chao的namespace
ip link set tap_chao netns ns_chao: 设置tap设备的网络命名空间为ns_chao
ip netns exec <netns_name> command: 操作namespace中的设备
ip netns exec ns_chao ip link list: 在ns_chao中执行ip link list
ip netns exec ns_chao ifconfig tap_chao 192.168.100.1/24 up: 绑定ip地址
ip netns exec ns_chao ifconfig -a: 查看ip地址
3 veth pair
3.1 veth pair基础
含义:是一对设备,连接两个虚拟以太端口。
局限: veth pair只可以连接两个namespace。多个namespace互通需要通过
Bridge/Switch
3.2 veth pair命令
# 创建veth pair
ip link add tap1 type veth peer name tap2
# 创建namespace
ip netns add ns1
ip netns add ns2
# 将两个tap分别迁移到对应namespace中
ip link set tap1 netns ns1
ip link set tap2 netns ns2
# 在namespace中给tap绑定ip地址
ip netns exec ns1 ip addr add local 192.168.50.1/24 dev tap1
ip netns exec ns2 ip addr add local 192.168.50.2/24 dev tap2
# 将tap设置为up
ip netns exec ns1 ifconfig tap1 up
up netns exec ns2 ifconfig tap2 up
# ping
ip netns exec ns1 ping 192.168.50.2
4 Bridge
4.1 Bridge基础
Bridge: 网桥
Switch: 交换机,多端口网桥
实现Bridge功能的模块: brctl
安装brctl: yum install bridge-utils
4.2 Bridge命令
brctl
4个namespace,每个namespace有一个tap与交换机上一个tap口组成veth pair。
4个namespace通过veth pair以及Bridge互联起来。
结构如下:
NS1 NS2
tap1 tap2
192.168.50.1 192.168.50.2
tap1_peer tap2_peer
vb1
tap3_peer tap4_peer
NS3 NS4
tap3 tap4
192.168.50.3 192.168.50.4
# 创建veth pair
ip link add tap1 type veth peer name tap1_peer
ip link add tap2 type veth peer name tap2_peer
ip link add tap3 type veth peer name tap3_peer
ip link add tap4 type veth peer name tap4_peer
# 创建