让我们用 Node.js 写自己的 DDNS 动态域名程序
让我们用 Node.js 写自己的 DDNS 动态域名程序
死月胖子你为何这么屌。
当然可以!以下是一个详细的指南,教你如何使用 Node.js 编写一个简单的 DDNS(动态域名解析)程序。DDNS 可以让你通过动态的 IP 地址访问你的服务器或设备。
让我们用 Node.js 写自己的 DDNS 动态域名程序
1. 环境准备
首先,确保你已经安装了 Node.js 和 npm(Node 包管理器)。你可以从 Node.js 官网 下载并安装。
2. 创建项目
创建一个新的文件夹,并初始化一个新的 Node.js 项目:
mkdir my-ddns
cd my-ddns
npm init -y
3. 安装依赖
我们需要 axios
来发送 HTTP 请求,以及 dns-over-https
来进行 DNS 查询。运行以下命令安装这些包:
npm install axios dns-over-https
4. 编写代码
创建一个名为 ddns.js
的文件,并编写以下代码:
const axios = require('axios');
const dns = require('dns-over-https');
// 配置你的域名和 API 密钥
const DOMAIN = 'yourdomain.com';
const API_KEY = 'your-api-key';
// 获取当前 IP 地址
async function getCurrentIP() {
const response = await axios.get('https://api.ipify.org?format=json');
return response.data.ip;
}
// 更新 DNS 记录
async function updateDNSRecord(ip) {
const url = `https://api.your-dns-provider.com/update?hostname=${DOMAIN}&myip=${ip}`;
const headers = {
'X-Api-Key': API_KEY,
'Content-Type': 'application/json'
};
try {
const response = await axios.post(url, {}, { headers });
console.log(`DNS updated successfully: ${response.status}`);
} catch (error) {
console.error('Failed to update DNS:', error.message);
}
}
// 主函数
async function main() {
const currentIP = await getCurrentIP();
console.log(`Current IP: ${currentIP}`);
// 检查当前 DNS 记录是否与当前 IP 匹配
dns.resolve4(DOMAIN, (err, addresses) => {
if (err) {
console.error('Failed to resolve domain:', err.message);
return;
}
const dnsIP = addresses[0];
console.log(`DNS IP: ${dnsIP}`);
if (dnsIP !== currentIP) {
updateDNSRecord(currentIP);
} else {
console.log('No need to update DNS record.');
}
});
}
main();
5. 运行程序
确保你已经替换了 DOMAIN
和 API_KEY
为你自己的域名和 API 密钥。然后运行以下命令来启动程序:
node ddns.js
这个程序会检查你的当前 IP 地址,并与 DNS 记录中的 IP 地址进行比较。如果不同,它会更新 DNS 记录以指向新的 IP 地址。
6. 自动化
为了自动化这个过程,你可以将这个脚本设置为定时任务。例如,使用 cron
在 Linux 上设置每小时运行一次:
crontab -e
添加以下行:
0 * * * * /usr/bin/node /path/to/my-ddns/ddns.js
这样,每次运行时都会自动更新你的 DNS 记录。
希望这个教程对你有帮助!如果你有任何问题,请随时提问。
楼主跳槽不?来份简历啊!
你为何这么屌
不错不错,以前用过DNSPod,所以就顺便看了下,它api下面的第三方也列举了几个nodejs的client
对于每个子域名,都判断其当前记录 IP 是否等于当前刚探测的 IP。 是:修改该子域名的记录值为刚探测的 IP。 否:不作任何操作。
这里是不是写反了?
吊炸天啊,学习了。!!
现在学生都这么屌我们这些老帮菜以后还怎么混哪……
好的,让我们来讨论如何使用 Node.js 编写一个简单的 DDNS(动态域名解析)程序。DDNS 程序的主要作用是自动更新你的 DNS 记录,以便在 IP 地址发生变化时,仍然能够通过域名访问到你的服务器。
前提条件
- 你需要有一个域名。
- 你需要一个支持 API 的 DNS 服务提供商(例如 Cloudflare、DNSPod 等)。
示例代码
我们将使用 Cloudflare 作为 DNS 服务提供商,并使用 node-fetch
库来发送 HTTP 请求。
步骤 1: 安装依赖
首先,安装 node-fetch
库:
npm install node-fetch
步骤 2: 创建 DDNS 脚本
创建一个名为 ddns.js
的文件,并添加以下代码:
const fetch = require('node-fetch');
// 你的 Cloudflare API Token 和 Zone ID
const CF_TOKEN = 'your_cloudflare_api_token';
const CF_ZONE_ID = 'your_cloudflare_zone_id';
// 你的 DNS 记录 ID 和域名
const DNS_RECORD_ID = 'your_dns_record_id';
const DOMAIN_NAME = 'yourdomain.com';
// 获取当前的公网 IP 地址
async function getPublicIP() {
const response = await fetch('https://api.ipify.org?format=json');
const data = await response.json();
return data.ip;
}
// 更新 DNS 记录
async function updateDNSRecord(ip) {
const url = `https://api.cloudflare.com/client/v4/zones/${CF_ZONE_ID}/dns_records/${DNS_RECORD_ID}`;
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${CF_TOKEN}`
};
const data = {
type: 'A',
name: DOMAIN_NAME,
content: ip,
ttl: 120,
proxied: false
};
try {
const response = await fetch(url, {
method: 'PUT',
headers: headers,
body: JSON.stringify(data)
});
if (response.ok) {
console.log(`DNS record updated successfully to IP: ${ip}`);
} else {
console.error(`Failed to update DNS record: ${response.statusText}`);
}
} catch (error) {
console.error(`Error updating DNS record: ${error.message}`);
}
}
// 主函数
async function main() {
const currentIP = await getPublicIP();
console.log(`Current public IP: ${currentIP}`);
// 检查当前记录是否已经是最新的
const response = await fetch(`https://api.cloudflare.com/client/v4/zones/${CF_ZONE_ID}/dns_records?type=A&name=${DOMAIN_NAME}`, {
headers: { 'Authorization': `Bearer ${CF_TOKEN}` }
});
const records = await response.json();
if (records.success && records.result.length > 0) {
const existingIP = records.result[0].content;
if (existingIP !== currentIP) {
await updateDNSRecord(currentIP);
} else {
console.log(`IP is already up-to-date: ${currentIP}`);
}
} else {
console.error('Failed to fetch existing DNS records');
}
}
main();
解释
- 获取公网 IP:我们使用
api.ipify.org
来获取当前的公网 IP 地址。 - 更新 DNS 记录:使用 Cloudflare 的 API 来更新 DNS 记录。你需要替换
CF_TOKEN
、CF_ZONE_ID
和DNS_RECORD_ID
为你的实际值。 - 检查现有记录:在更新之前,先检查现有的 DNS 记录是否已经是最新,避免不必要的更新操作。
运行脚本
运行脚本:
node ddns.js
这样,每次运行脚本时,它都会检查并更新你的 DNS 记录,以确保你的域名总是指向正确的 IP 地址。