使用 WireGuard 实现局域网组建
2026/2/25大约 1 分钟
一、安装 WireGuard
参考:https://www.wireguard.com/install/
Windows 版本下载地址:https://download.wireguard.com/windows-client/
Ubuntu(Debian)安装:
sudo apt update
sudo apt install wireguard二、服务端配置
- 生成服务器密钥对
sudo umask 077
wg genkey | sudo tee /etc/wireguard/privatekey | wg pubkey | sudo tee /etc/wireguard/publickey- 创建服务器配置文件
/etc/wireguard/wg0.conf
[Interface]
Address = 172.16.10.1/24
ListenPort = 5555
PrivateKey = <服务器私钥>
PostUp = iptables -I FORWARD 1 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT; iptables -I FORWARD 2 -i %i -j ACCEPT; iptables -t nat -I POSTROUTING 1 -s 172.16.10.0/24 -o eth0 -j MASQUERADE
PostDown = iptables -D FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT; iptables -D FORWARD -i %i -j ACCEPT; iptables -t nat -D POSTROUTING -s 172.16.10.0/24 -o eth0 -j MASQUERADE
[Peer]
# 这是对端VPS-A的信息
# 稍后在VPS-A上生成公钥后,填入此处
PublicKey = <客户端公钥>
# 分配给VPS-A的私有IP地址
AllowedIPs = 172.16.10.2/32- 启用IP转发:为了让服务器能转发客户端的流量,需要启用内核的IP转发功能
echo "net.ipv4.ip_forward=1" | sudo tee -a /etc/sysctl.conf- 有防火墙的话,需要配置防火墙
sudo ufw allow 51820/udp- 启动WireGuard服务
使用wg-quick工具启动刚才配置的wg0接口,并设置开机自启
sudo systemctl enable wg-quick@wg0 --now检查服务状态和接口:
sudo systemctl status wg-quick@wg0
sudo wg show三、客户端配置
- 创建客户端密钥对
wg genkey | tee client-private.key | wg pubkey > client-public.key- 在服务器配置中添加客户端(已添加),多个客户端添加多个
[Peer]
[Peer]
PublicKey = <客户端公钥>
AllowedIPs = 10.0.0.2/32- 创建客户端配置文件
[Interface]
PrivateKey = <客户端私钥>
Address = 172.16.10.2/24
DNS = 114.114.114.114
[Peer]
Endpoint = 192.168.10.13:5555
PublicKey = <服务端公钥>
AllowedIPs = 172.16.10.0/24
PersistentKeepalive = 25四、常见问题:
iptables: command not found:sudo apt install iptables
