当前位置:   article > 正文

C#调用阿里云接口实现动态域名解析,支持IPv6(Windows系统下载可用)_windows动态域名

windows动态域名

电信宽带一般能申请到公网IP,但是是动态的,基本上每天都要变,所以想到做一个定时任务,随系统启动,网上看了不少博文很多都支持IPv4,自己动手写了一个。

(私信可全程指导)

部署步骤:

1、下载软件包,修改配置文件

下载地址:私信获取

下载压缩包,解压后修改配置文件AliDDNS.exe.config中的阿里云帐号和自己的域名。

2、修改脚本,并运行脚本

将“安装服务.bat”和“卸载服务.bat”脚本中的可执行文件路径,改为自己的软件包所在路径,然后右键“安装服务.bat”进行安装服务。

执行脚本后会将定时服务添加到系统服务中。

3、启动服务

右键“此电脑”,点击“管理”进入计算机管理窗口,在服务列表中找到上一步新增的服务,然后启动。即可定时更新阿里云解析记录,实现动态IP的DDNS。

源代码:

  1. /// <summary>
  2. /// 刷新阿里云域名解析记录
  3. /// </summary>
  4. private void RefreshAliRecord()
  5. {
  6. string recordTypes = ConfigurationManager.AppSettings["RecordTypes"];
  7. if (string.IsNullOrWhiteSpace(recordTypes))
  8. {
  9. NLogHelper.WriteLog(typeof(AliDDNS), "配置文件中的“待解析的协议类型”不能为空。", NLogLevel.Warn);
  10. return;
  11. }
  12. string regionId = ConfigurationManager.AppSettings["RegionId"];
  13. string accessKeyID = ConfigurationManager.AppSettings["AccessKeyID"];
  14. string accessKeySecret = ConfigurationManager.AppSettings["AccessKeySecret"];
  15. string domainName = ConfigurationManager.AppSettings["DomainName"];
  16. string rR = ConfigurationManager.AppSettings["RR"];
  17. string[] rRTypes = rR.Split('|');
  18. // regionId:地区节点
  19. // accessKeyID:阿里云Key
  20. // accessKeySecret:阿里云密钥
  21. AlibabaCloudCredentialsProvider provider = new AccessKeyCredentialProvider(accessKeyID, accessKeySecret);
  22. IClientProfile profile = DefaultProfile.GetProfile(regionId);
  23. DefaultAcsClient client = new DefaultAcsClient(profile, provider);
  24. List<DescribeDomainRecordsResponse.DescribeDomainRecords_Record> recordList = DescribeDomainRecords(client, domainName);
  25. string[] recordTypeArray = recordTypes.Split('|');
  26. foreach (string recordType in recordTypeArray)
  27. {
  28. if (recordType == "A")
  29. {
  30. #region IPv4解析记录
  31. try
  32. {
  33. string urls = ConfigurationManager.AppSettings["GetIPFromUrl"];
  34. string ipv4 = CommonHelper.GetExtranetIP(urls.Split('|').ToList());
  35. if (string.IsNullOrWhiteSpace(ipv4))
  36. {
  37. NLogHelper.WriteLog(typeof(AliDDNS), "未获取到外网IPv4地址!", NLogLevel.Warn);
  38. return;
  39. }
  40. if (IsAddSuccessLog)
  41. {
  42. NLogHelper.WriteLog(typeof(AliDDNS), "获取到的外网IPv4地址为:" + ipv4, NLogLevel.Info);
  43. }
  44. foreach (string rRItem in rRTypes)
  45. {
  46. if (string.IsNullOrWhiteSpace(rRItem))
  47. {
  48. continue;
  49. }
  50. List<DescribeDomainRecordsResponse.DescribeDomainRecords_Record> ipv4Records = recordList.Where(r => r.Type == recordType && r.RR == rRItem).ToList();
  51. if (ipv4Records == null || ipv4Records.Count() == 0)
  52. {
  53. AddDNSRecord(client, domainName, rRItem, recordType, ipv4);
  54. }
  55. else
  56. {
  57. #region 更新解析记录
  58. // 非ipv4记录
  59. List<DescribeDomainRecordsResponse.DescribeDomainRecords_Record> otherRecords = ipv4Records.Where(r => r._Value != ipv4).ToList();
  60. // ipv4记录
  61. List<DescribeDomainRecordsResponse.DescribeDomainRecords_Record> tempList = ipv4Records.Where(r => r._Value == ipv4).ToList();
  62. if (tempList == null || tempList.Count == 0)
  63. {
  64. // 如果不存在该IPv4的记录,则删除所有记录ipv4Records,并新增记录
  65. AddDNSRecord(client, domainName, rRItem, recordType, ipv4);
  66. DeleteDNSRecord(client, ipv4Records);
  67. }
  68. else if (tempList.Count == 1) // 如果只存在一条该IPv4记录,则记录日志,如果有其他记录则删除
  69. {
  70. NLogHelper.WriteLog(typeof(AliDDNS), string.Format("同类型(“{0}”类型)的解析记录(IPv4:{1})已存在,无需更新!", rRItem, ipv4), NLogLevel.Info);
  71. if (ipv4Records.Count != tempList.Count)
  72. {
  73. // 存在其他记录,则删除其他记录otherRecords
  74. DeleteDNSRecord(client, otherRecords);
  75. }
  76. }
  77. else
  78. {
  79. // 如果存在多条该IPv4记录,则取第一条,其他的记录都删除
  80. tempList.RemoveRange(0, 1);
  81. otherRecords.AddRange(tempList);
  82. DeleteDNSRecord(client, otherRecords);
  83. }
  84. #endregion
  85. }
  86. }
  87. }
  88. catch (Exception ex)
  89. {
  90. NLogHelper.WriteLog(typeof(AliDDNS), "查询并更新IPv4解析记录时异常:" + ex.ToString(), NLogLevel.Warn);
  91. }
  92. #endregion
  93. }
  94. else if (recordType == "AAAA")
  95. {
  96. #region IPv6解析记录
  97. try
  98. {
  99. List<string> ipv6List = CommonHelper.GetLocalIPv6();
  100. if (ipv6List == null || ipv6List.Count() == 0)
  101. {
  102. NLogHelper.WriteLog(typeof(AliDDNS), "未获取到本机IPv6地址!", NLogLevel.Warn);
  103. return;
  104. }
  105. if (IsAddSuccessLog)
  106. {
  107. NLogHelper.WriteLog(typeof(AliDDNS), "获取到的本地IPv6地址为:" + string.Join(",", ipv6List), NLogLevel.Info);
  108. }
  109. string defaultIPv6 = ipv6List[0]; // 默认只添加第一个IPv6地址
  110. foreach (string rRItem in rRTypes)
  111. {
  112. if (string.IsNullOrWhiteSpace(rRItem))
  113. {
  114. continue;
  115. }
  116. List<DescribeDomainRecordsResponse.DescribeDomainRecords_Record> ipv6Records = recordList.Where(r => r.Type == recordType && r.RR == rRItem).ToList();
  117. if (ipv6Records == null || ipv6Records.Count() == 0)
  118. {
  119. AddDNSRecord(client, domainName, rRItem, recordType, defaultIPv6);
  120. }
  121. else
  122. {
  123. #region 更新解析记录
  124. // 非ipv6记录
  125. List<DescribeDomainRecordsResponse.DescribeDomainRecords_Record> otherRecords = ipv6Records.Where(r => r._Value != defaultIPv6).ToList();
  126. // ipv6记录
  127. List<DescribeDomainRecordsResponse.DescribeDomainRecords_Record> tempList = ipv6Records.Where(r => r._Value == defaultIPv6).ToList();
  128. if (tempList == null || tempList.Count == 0)
  129. {
  130. // 如果不存在该IPv6的记录,则删除所有记录ipv6Records,并新增记录
  131. AddDNSRecord(client, domainName, rRItem, recordType, defaultIPv6);
  132. DeleteDNSRecord(client, ipv6Records);
  133. }
  134. else if (tempList.Count == 1) // 如果只存在一条该IPv6记录,则记录日志,如果有其他记录则删除
  135. {
  136. NLogHelper.WriteLog(typeof(AliDDNS), string.Format("同类型(“{0}”类型)的解析记录(IPv6:{1})已存在,无需更新!", rRItem, defaultIPv6), NLogLevel.Info);
  137. if (ipv6Records.Count != tempList.Count)
  138. {
  139. // 存在其他记录,则删除其他记录otherRecords
  140. DeleteDNSRecord(client, otherRecords);
  141. }
  142. }
  143. else
  144. {
  145. // 如果存在多条该IPv6记录,则取第一条,其他的记录都删除
  146. tempList.RemoveRange(0, 1);
  147. otherRecords.AddRange(tempList);
  148. DeleteDNSRecord(client, otherRecords);
  149. }
  150. #endregion
  151. }
  152. }
  153. }
  154. catch (Exception ex)
  155. {
  156. NLogHelper.WriteLog(typeof(AliDDNS), "查询并更新IPv6解析记录时异常:" + ex.ToString(), NLogLevel.Warn);
  157. }
  158. #endregion
  159. }
  160. }
  161. }
  162. // 获取指定主域名的所有解析记录列表
  163. public List<DescribeDomainRecordsResponse.DescribeDomainRecords_Record> DescribeDomainRecords(DefaultAcsClient client, string domainName)
  164. {
  165. List<DescribeDomainRecordsResponse.DescribeDomainRecords_Record> records = new List<DescribeDomainRecordsResponse.DescribeDomainRecords_Record>();
  166. try
  167. {
  168. DescribeDomainRecordsRequest request = new DescribeDomainRecordsRequest();
  169. request.DomainName = domainName;
  170. 记录类型 官网支持A/CNAME/MX/AAA/TXT/NS/SRV/CAA/URL隐性(显性)转发如果有需要可将该值配置为参数传入
  171. //request.Type = recordType;
  172. try
  173. {
  174. DescribeDomainRecordsResponse response = client.GetAcsResponse(request);
  175. if (IsAddSuccessLog)
  176. {
  177. NLogHelper.WriteLog(typeof(AliDDNS), "查询到的解析记录:" + System.Text.Encoding.Default.GetString(response.HttpResponse.Content), NLogLevel.Info);
  178. }
  179. if (response.DomainRecords != null)
  180. {
  181. records = response.DomainRecords;
  182. }
  183. }
  184. catch (Exception ex)
  185. {
  186. NLogHelper.WriteLog(typeof(AliDDNS), "调用DescribeDomainRecords接口时发生异常:" + ex.ToString(), NLogLevel.Error);
  187. }
  188. }
  189. catch (Exception ex)
  190. {
  191. NLogHelper.WriteLog(typeof(AliDDNS), "创建DescribeDomainRecords接口调用对象时发生异常:" + ex.ToString(), NLogLevel.Error);
  192. }
  193. return records;
  194. }
  195. // 新增解析记录
  196. public void AddDNSRecord(DefaultAcsClient client, string domainName, string rRItem, string recordType, string ipValue)
  197. {
  198. #region 新增解析记录
  199. string recordStr = string.Format("(RR:{0},Type:{1},Value:{2})", rRItem, recordType, ipValue);
  200. try
  201. {
  202. var request = new AddDomainRecordRequest();
  203. request.DomainName = domainName;
  204. request.RR = rRItem;
  205. request.Type = recordType;
  206. request._Value = ipValue;
  207. request.TTL = 600; // 免费版,默认600秒,10分钟
  208. var response = client.GetAcsResponse(request);
  209. if (IsAddSuccessLog)
  210. {
  211. NLogHelper.WriteLog(typeof(AliDDNS), string.Format("新增解析记录{0}时接口返回内容:{1}", recordStr, Encoding.Default.GetString(response.HttpResponse.Content)), NLogLevel.Info);
  212. }
  213. }
  214. catch (Exception ex)
  215. {
  216. NLogHelper.WriteLog(typeof(AliDDNS), string.Format("新增解析记录{0}时发生异常:{1}", recordStr, ex.ToString()), NLogLevel.Error);
  217. }
  218. #endregion
  219. }
  220. // 删除解析记录
  221. public void DeleteDNSRecord(DefaultAcsClient client, List<DescribeDomainRecordsResponse.DescribeDomainRecords_Record> deleteList)
  222. {
  223. #region 删除解析记录
  224. foreach (DescribeDomainRecordsResponse.DescribeDomainRecords_Record record in deleteList)
  225. {
  226. string recordStr = string.Format("(RR:{0},Type:{1},Value:{2})", record.RR, record.Type, record._Value);
  227. try
  228. {
  229. DeleteDomainRecordRequest request = new DeleteDomainRecordRequest();
  230. request.RecordId = record.RecordId;
  231. DeleteDomainRecordResponse response = client.GetAcsResponse(request);
  232. if (IsAddSuccessLog)
  233. {
  234. NLogHelper.WriteLog(typeof(AliDDNS), string.Format("删除解析记录{0}时接口返回内容:{1}", recordStr, Encoding.Default.GetString(response.HttpResponse.Content)), NLogLevel.Info);
  235. }
  236. }
  237. catch (Exception ex)
  238. {
  239. NLogHelper.WriteLog(typeof(AliDDNS), string.Format("删除解析记录{0}时发生异常:{1}", recordStr, ex.ToString()), NLogLevel.Error);
  240. }
  241. }
  242. #endregion
  243. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/喵喵爱编程/article/detail/889254
推荐阅读
相关标签
  

闽ICP备14008679号