一般宽带用户的IP都是动态IP,重连之后IP可能会发生变化。
如果想在其他地方连接家里的设备,或者在家中搭建服务器,就会受到影响。
现在提供一种动态解析域名的方式,只要检测到IP的变化,那么就调用阿里云的开放api,更新域名解析
github(欢迎star):https://github.com/liuyinglong/aliyun;
npm(aliCloudClient):https://www.npmjs.com/package/aliyun-apisign
说明
每分钟获取一次公网 IP,如果检测到公网IP发生了变化,则调用aliyun的开放接口进行更新
let AliCloudClient = require("../aliCloudClient");
let Req = require("../request");
let request = new Req();
let schedule = require("node-schedule");
let aliClient = new AliCloudClient({
AccessKeyId: "your AccessKeyId",
AccessKeySecret: "your AccessKeySecret",
serverUrl: "http://alidns.aliyuncs.com"
});
let domainNameValue = "www";
let recordId, //记录ID
ip;
function getMyIp() {
return request.post("http://ip.taobao.com/service/getIpInfo2.php", {
ip: "myip"
}).then(function (data) {
return data.body.data.ip;
}).catch(function (err) {
return Promise.reject(err);
})
}
function getDomainRecords() {
return aliClient.get("/", {
Action: "DescribeSubDomainRecords",
SubDomain: "www.yourDomain.cn"
}).then(function (data) {
let body = data.body;
let record = body.DomainRecords.Record[0];
recordId = record.RecordId;
return record.Value;
}).catch(function (err) {
return Promise.reject(err);
})
}
function upDateRecords() {
return aliClient.get("/", {
Action: "UpdateDomainRecord",
RecordId: recordId,
RR: domainNameValue,
Type: "A",
Value: ip
}).then(function (data) {
console.log(new Date() + ip + " 修改成功");
}).catch(function (err) {
console.log(err)
})
}
function watchIpChange() {
return getMyIp().then(function (tempIp) {
if (ip === tempIp) {
return;
}
if (!ip) {
return;
}
console.log(new Date()+ ip + "=>"+ tempIp);
ip = tempIp;
upDateRecords();
}).catch(function(err){
console.log(err);
})
}
Promise.all([getMyIp(), getDomainRecords()]).then(function (result) {
ip = result[0];
let domainValue = result[1];
if (ip !== domainValue) {
upDateRecords();
}
});
schedule.scheduleJob("0 * * * * *", function () {
watchIpChange();
});