虚拟网卡以及路由表

虚拟网卡以及路由表

mohuangNPC
2025-12-09 / 0 评论 / 3 阅读 / 正在检测是否收录...

最近在捣鼓Linux虚拟网卡和路由表,发现了不少坑点,在这里统一整理一下。

创建虚拟网卡

ip tuntap add mode tun dev tun0

给虚拟网卡设置IP

ip addr add 198.18.0.1/15 dev tun0

设置路由

设置路由这里有两种方法,第一种是直接给网卡设置,第二种通过路由表的方式

直接设置

ip route add x.x.x.x/x dev tun0
ip route show
#删除规则
ip route del x.x.x.x/x dev tun0

这会将所有发往x.x.x.x/x的流量全部重定向到tun0

路由规则

创建一个新的路由表

nano /etc/iproute2/rt_tables
#在文件末尾添加一行:
100 tun_table

给路由表添加路由

# 这个意思是将默认网关设置为咱们的自定义网卡
# 规则可以根据自己需要设置
ip route add default via 192.168.1.1 dev tun0 table tun_table
# 又或者让10.0.0.0/24 走eth1
ip route add 10.0.0.0/24 dev eth1 table tun_table
# 删除路由表中的规则
ip route del 10.0.0.0/24 dev eth1 table tun_table

添加路由规则

#这是说将所有流量都走tun_table 如果公网连接ssh很有可能断开
ip rule add from all lookup tun_table priority 1000
#这是说将所有流量源地址是192.168.1.0/24都走tun_table
ip rule add from 192.168.1.0/24 lookup tun_table priority 1000
#这是说将所有流量目标地址是192.168.1.0/24都走tun_table
ip rule add to 192.168.2.0/24 lookup tun_table priority 1000
#查看路由表
ip rule show
#查看特定路由表
ip rule show table tun_table
# 删除路由规则
ip rule del from all lookup tun_table

注意

这个priority 1000优先级一定要写,如果没有绝对的自信对路由比较熟悉的话,数字越小越靠前,先匹配到的就不会继续执行后面的路由了

实战

咱们设置一个路由规则,就是除了远程ssh的连接,其他流量全部走tun0

#添加一个虚拟网卡
ip tuntap add mode tun dev tun0
#设置虚拟网卡的ip
ip addr add 198.18.0.1/15 dev tun0
#启动
ip link set dev tun0 up
#添加一个默认路由给路由表tun_table
ip route add default via 198.18.0.1 dev tun0 table tun_table
#写死设置我电脑的ip走默认的mian, 防止ssh连不上
ip rule add to x.x.x.x/32 lookup main priority 1000
ip rule add to y.y.y.y/32 lookup main priority 1001
#其余的流量全部走tun_table
ip rule add to all lookup tun_table priority 2000

其中x.x.x.x/32和 y.y.y.y/32就是自己电脑的公网ip,可以找个网站查询自己的公网IP。
最好放到shell文件中统一执行。
执行完后咱们随便curl一个地址比如curl www.baidu.com.
发现已经访问不通过了(这就对了因为tun0没用),然后咱们执行:
ip route get 8.8.8.8
跟踪一下8.8.8.8流经的网卡,展示:
miychuem.png
已经成功设置了除了咱们连接ssh的流量,其他流量全部走tun0了!

0

评论 (0)

取消

Warning: file_put_contents(/var/www/html/rss.xml): failed to open stream: Permission denied in /var/www/html/usr/plugins/CustomRSS/Plugin.php on line 149