0%

使用 Wireguard 并利用服务器中转实现无公网 IP 异地组网

情景

设备 A 与设备 B 均无公网 IP。需要 VPN 构建隧道。

实现方法

服务器端

服务器 Ubuntu 22.04

安装 wireguard

1
sudo apt install wireguard

编写 wg0.conf 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
[Interface]
ListenPort =
Address = 10.100.0.1/24
PrivateKey =

[Peer]
PublicKey =
PresharedKey =
AllowedIPs = 10.100.0.2/32
PersistentKeepalive = 25

[Peer]
PublicKey =
PresharedKey =
AllowedIPs = 10.100.0.3/32
PersistentKeepalive = 25

[Peer]
PublicKey =
PresharedKey =
AllowedIPs = 10.100.0.4/32
PersistentKeepalive = 25

在服务器防火墙放行 ListenPort 填入的端口
wg0.conf 文件放置于 /etc/wireguard 文件夹中。
编辑 /etc/sysctl.conf 文件,取消 net.ipv4.ip_forward=1 的注释开启转发。并输入下面的命令使其生效。

1
sysctl -p

之后输入下面的命令启用并启动系统服务

1
2
systemctl enable wg-quick@wg0.service
systemctl start wg-quick@wg0.service

服务器端编写完毕

客户端

安装 wireguard 之后新建隧道,并填写下面的内容

1
2
3
4
5
6
7
8
9
10
[Interface]
PrivateKey =
Address = 10.100.0.2/32

[Peer]
PublicKey =
PresharedKey =
AllowedIPs = 10.100.0.1/24
Endpoint = <这里填服务器的域名/IP:ListenPort>
PersistentKeepalive = 25

注意事项

AllowedIPs 的子网掩码为 /24

其他客户端配置完毕后即可互相 ping 查看能否连接。Windows 可能需要去高级防火墙的入站规则启用文件和打印机共享(回显请求 ICMPv4-IN)。