WireGuard中连接配置了DDNS的节点

目录

  1. 1. 生成配置文件
  2. 2. 启用配置

WireGuard 在连接节点时,若 Endpoint 填入了域名,则只会将第一次解析到的 IP 作为 Endpoint IP,之后遇到 IP 变化导致断连就不会尝试重解析 DNS。因为家宽的公网 IP 都是动态公网 IP,故产生了这方面需求。于是笔者查找了一下资料,在此记录一下解决方法。

先上参考链接:

Endpoint with changing IP - Arch Linux Wiki

操作方法很简单,使用 systemd 来完成。

注意:假设有一台拥有动态公网 IP 的服务器 A,和位于内网/公网的机器 B,发起连接的方向是 B->A,那么以下步骤均于机器 B 上进行,服务器 A 上除了 DDNS 不需要额外配置。并且机器 B 需要 Linux 系统。

生成配置文件

先生成定时器配置,每半分钟更新一次 Endpoint IP

nano /etc/systemd/system/wireguard_reresolve-dns.timer #要创建的第一个文件

配置如下,复制粘贴即可。

[Unit]
Description=Periodically reresolve DNS of all WireGuard endpoints

[Timer]
OnCalendar=*:*:0/30

[Install]
WantedBy=timers.target

生成任务配置

nano /etc/systemd/system/wireguard_reresolve-dns.service

配置如下

[Unit]
Description=Reresolve DNS of all WireGuard endpoints
Wants=network-online.target
After=network-online.target

[Service]
Type=oneshot
ExecStart=/bin/sh -c 'for i in /etc/wireguard/*.conf; do /usr/share/wireguard-tools/examples/reresolve-dns/reresolve-dns.sh "$i"; done'

注:部分发行版的 reresolve-dns.sh 并不在 /usr/share/wireguard-tools/examples/reresolve-dns/ 目录下。要验证可以在终端尝试直接运行这个脚本,如果报错了,可以按照以下方法解决:

启用配置

终端输入

systemctl enable --now wireguard_reresolve-dns.timer

现在 WireGuard 的 Endpoint ip 应该可以动态更新了。