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

news2025/9/6 5:15:33

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

(私信可全程指导)

部署步骤:

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

下载地址:私信获取

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

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

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

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

3、启动服务

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

源代码:


/// <summary>
/// 刷新阿里云域名解析记录
/// </summary>
private void RefreshAliRecord()
{
    string recordTypes = ConfigurationManager.AppSettings["RecordTypes"];
    if (string.IsNullOrWhiteSpace(recordTypes))
    {
        NLogHelper.WriteLog(typeof(AliDDNS), "配置文件中的“待解析的协议类型”不能为空。", NLogLevel.Warn);
        return;
    }

    string regionId = ConfigurationManager.AppSettings["RegionId"];
    string accessKeyID = ConfigurationManager.AppSettings["AccessKeyID"];
    string accessKeySecret = ConfigurationManager.AppSettings["AccessKeySecret"];
    string domainName = ConfigurationManager.AppSettings["DomainName"];
    string rR = ConfigurationManager.AppSettings["RR"];

    string[] rRTypes = rR.Split('|');

    // regionId:地区节点
    // accessKeyID:阿里云Key
    // accessKeySecret:阿里云密钥
    AlibabaCloudCredentialsProvider provider = new AccessKeyCredentialProvider(accessKeyID, accessKeySecret);
    IClientProfile profile = DefaultProfile.GetProfile(regionId);
    DefaultAcsClient client = new DefaultAcsClient(profile, provider);

    List<DescribeDomainRecordsResponse.DescribeDomainRecords_Record> recordList = DescribeDomainRecords(client, domainName);

    string[] recordTypeArray = recordTypes.Split('|');
    foreach (string recordType in recordTypeArray)
    {
        if (recordType == "A")
        {
            #region IPv4解析记录
            try
            {
                string urls = ConfigurationManager.AppSettings["GetIPFromUrl"];
                string ipv4 = CommonHelper.GetExtranetIP(urls.Split('|').ToList());
                if (string.IsNullOrWhiteSpace(ipv4))
                {
                    NLogHelper.WriteLog(typeof(AliDDNS), "未获取到外网IPv4地址!", NLogLevel.Warn);
                    return;
                }

                if (IsAddSuccessLog)
                {
                    NLogHelper.WriteLog(typeof(AliDDNS), "获取到的外网IPv4地址为:" + ipv4, NLogLevel.Info);
                }

                foreach (string rRItem in rRTypes)
                {
                    if (string.IsNullOrWhiteSpace(rRItem))
                    {
                        continue;
                    }

                    List<DescribeDomainRecordsResponse.DescribeDomainRecords_Record> ipv4Records = recordList.Where(r => r.Type == recordType && r.RR == rRItem).ToList();
                    if (ipv4Records == null || ipv4Records.Count() == 0)
                    {
                        AddDNSRecord(client, domainName, rRItem, recordType, ipv4);
                    }
                    else
                    {
                        #region 更新解析记录

                        // 非ipv4记录
                        List<DescribeDomainRecordsResponse.DescribeDomainRecords_Record> otherRecords = ipv4Records.Where(r => r._Value != ipv4).ToList();
                        // ipv4记录
                        List<DescribeDomainRecordsResponse.DescribeDomainRecords_Record> tempList = ipv4Records.Where(r => r._Value == ipv4).ToList();
                        if (tempList == null || tempList.Count == 0)
                        {
                            // 如果不存在该IPv4的记录,则删除所有记录ipv4Records,并新增记录
                            AddDNSRecord(client, domainName, rRItem, recordType, ipv4);

                            DeleteDNSRecord(client, ipv4Records);
                        }
                        else if (tempList.Count == 1)  // 如果只存在一条该IPv4记录,则记录日志,如果有其他记录则删除
                        {
                            NLogHelper.WriteLog(typeof(AliDDNS), string.Format("同类型(“{0}”类型)的解析记录(IPv4:{1})已存在,无需更新!", rRItem, ipv4), NLogLevel.Info);
                            if (ipv4Records.Count != tempList.Count)
                            {
                                // 存在其他记录,则删除其他记录otherRecords
                                DeleteDNSRecord(client, otherRecords);
                            }
                        }
                        else
                        {
                            // 如果存在多条该IPv4记录,则取第一条,其他的记录都删除
                            tempList.RemoveRange(0, 1);
                            otherRecords.AddRange(tempList);
                            DeleteDNSRecord(client, otherRecords);
                        }
                        #endregion
                    }
                }
            }
            catch (Exception ex)
            {
                NLogHelper.WriteLog(typeof(AliDDNS), "查询并更新IPv4解析记录时异常:" + ex.ToString(), NLogLevel.Warn);
            }

            #endregion
        }
        else if (recordType == "AAAA")
        {
            #region IPv6解析记录
            try
            {
                List<string> ipv6List = CommonHelper.GetLocalIPv6();
                if (ipv6List == null || ipv6List.Count() == 0)
                {
                    NLogHelper.WriteLog(typeof(AliDDNS), "未获取到本机IPv6地址!", NLogLevel.Warn);
                    return;
                }

                if (IsAddSuccessLog)
                {
                    NLogHelper.WriteLog(typeof(AliDDNS), "获取到的本地IPv6地址为:" + string.Join(",", ipv6List), NLogLevel.Info);
                }

                string defaultIPv6 = ipv6List[0];  // 默认只添加第一个IPv6地址

                foreach (string rRItem in rRTypes)
                {
                    if (string.IsNullOrWhiteSpace(rRItem))
                    {
                        continue;
                    }

                    List<DescribeDomainRecordsResponse.DescribeDomainRecords_Record> ipv6Records = recordList.Where(r => r.Type == recordType && r.RR == rRItem).ToList();
                    if (ipv6Records == null || ipv6Records.Count() == 0)
                    {
                        AddDNSRecord(client, domainName, rRItem, recordType, defaultIPv6);
                    }
                    else
                    {
                        #region 更新解析记录

                        // 非ipv6记录
                        List<DescribeDomainRecordsResponse.DescribeDomainRecords_Record> otherRecords = ipv6Records.Where(r => r._Value != defaultIPv6).ToList();
                        // ipv6记录
                        List<DescribeDomainRecordsResponse.DescribeDomainRecords_Record> tempList = ipv6Records.Where(r => r._Value == defaultIPv6).ToList();
                        if (tempList == null || tempList.Count == 0)
                        {
                            // 如果不存在该IPv6的记录,则删除所有记录ipv6Records,并新增记录
                            AddDNSRecord(client, domainName, rRItem, recordType, defaultIPv6);

                            DeleteDNSRecord(client, ipv6Records);
                        }
                        else if (tempList.Count == 1)  // 如果只存在一条该IPv6记录,则记录日志,如果有其他记录则删除
                        {
                            NLogHelper.WriteLog(typeof(AliDDNS), string.Format("同类型(“{0}”类型)的解析记录(IPv6:{1})已存在,无需更新!", rRItem, defaultIPv6), NLogLevel.Info);
                            if (ipv6Records.Count != tempList.Count)
                            {
                                // 存在其他记录,则删除其他记录otherRecords
                                DeleteDNSRecord(client, otherRecords);
                            }
                        }
                        else
                        {
                            // 如果存在多条该IPv6记录,则取第一条,其他的记录都删除
                            tempList.RemoveRange(0, 1);
                            otherRecords.AddRange(tempList);
                            DeleteDNSRecord(client, otherRecords);
                        }

                        #endregion
                    }
                }
            }
            catch (Exception ex)
            {
                NLogHelper.WriteLog(typeof(AliDDNS), "查询并更新IPv6解析记录时异常:" + ex.ToString(), NLogLevel.Warn);
            }
            #endregion
        }
    }
}

// 获取指定主域名的所有解析记录列表
public List<DescribeDomainRecordsResponse.DescribeDomainRecords_Record> DescribeDomainRecords(DefaultAcsClient client, string domainName)
{
    List<DescribeDomainRecordsResponse.DescribeDomainRecords_Record> records = new List<DescribeDomainRecordsResponse.DescribeDomainRecords_Record>();
    try
    {
        DescribeDomainRecordsRequest request = new DescribeDomainRecordsRequest();
        request.DomainName = domainName;

        记录类型 官网支持A/CNAME/MX/AAA/TXT/NS/SRV/CAA/URL隐性(显性)转发如果有需要可将该值配置为参数传入
        //request.Type = recordType;

        try
        {
            DescribeDomainRecordsResponse response = client.GetAcsResponse(request);
            if (IsAddSuccessLog)
            {
                NLogHelper.WriteLog(typeof(AliDDNS), "查询到的解析记录:" + System.Text.Encoding.Default.GetString(response.HttpResponse.Content), NLogLevel.Info);
            }

            if (response.DomainRecords != null)
            {
                records = response.DomainRecords;
            }
        }
        catch (Exception ex)
        {
            NLogHelper.WriteLog(typeof(AliDDNS), "调用DescribeDomainRecords接口时发生异常:" + ex.ToString(), NLogLevel.Error);
        }
    }
    catch (Exception ex)
    {
        NLogHelper.WriteLog(typeof(AliDDNS), "创建DescribeDomainRecords接口调用对象时发生异常:" + ex.ToString(), NLogLevel.Error);
    }
    return records;
}

// 新增解析记录
public void AddDNSRecord(DefaultAcsClient client, string domainName, string rRItem, string recordType, string ipValue)
{
    #region 新增解析记录

    string recordStr = string.Format("(RR:{0},Type:{1},Value:{2})", rRItem, recordType, ipValue);
    try
    {
        var request = new AddDomainRecordRequest();
        request.DomainName = domainName;
        request.RR = rRItem;
        request.Type = recordType;
        request._Value = ipValue;
        request.TTL = 600;  // 免费版,默认600秒,10分钟

        var response = client.GetAcsResponse(request);
        if (IsAddSuccessLog)
        {
            NLogHelper.WriteLog(typeof(AliDDNS), string.Format("新增解析记录{0}时接口返回内容:{1}", recordStr, Encoding.Default.GetString(response.HttpResponse.Content)), NLogLevel.Info);
        }
    }
    catch (Exception ex)
    {
        NLogHelper.WriteLog(typeof(AliDDNS), string.Format("新增解析记录{0}时发生异常:{1}", recordStr, ex.ToString()), NLogLevel.Error);
    }
    #endregion
}

// 删除解析记录
public void DeleteDNSRecord(DefaultAcsClient client, List<DescribeDomainRecordsResponse.DescribeDomainRecords_Record> deleteList)
{
    #region 删除解析记录

    foreach (DescribeDomainRecordsResponse.DescribeDomainRecords_Record record in deleteList)
    {
        string recordStr = string.Format("(RR:{0},Type:{1},Value:{2})", record.RR, record.Type, record._Value);
        try
        {
            DeleteDomainRecordRequest request = new DeleteDomainRecordRequest();
            request.RecordId = record.RecordId;

            DeleteDomainRecordResponse response = client.GetAcsResponse(request);
            if (IsAddSuccessLog)
            {
                NLogHelper.WriteLog(typeof(AliDDNS), string.Format("删除解析记录{0}时接口返回内容:{1}", recordStr, Encoding.Default.GetString(response.HttpResponse.Content)), NLogLevel.Info);
            }
        }
        catch (Exception ex)
        {
            NLogHelper.WriteLog(typeof(AliDDNS), string.Format("删除解析记录{0}时发生异常:{1}", recordStr, ex.ToString()), NLogLevel.Error);
        }
    }

    #endregion
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1322191.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

原生JS实现组件切换(不刷新页面)

这是通过原生Es6实现的组件切换&#xff0c;代码很简单&#xff0c;原理和各种框架原理大致相同。 创建文件 ├── component&#xff1a;存放组件 │ ├── home1.js&#xff1a;组件1 │ ├── home2.js&#xff1a;组件2 ├── index.html ├── index.js初始化ht…

台湾虾皮本土店铺:如何在台湾虾皮本土店铺开展电商业务

在台湾地区&#xff0c;虾皮&#xff08;Shopee&#xff09;是一款备受欢迎的电商平台。虾皮拥有强大的技术团队、丰富的电商经验和对市场的深刻理解。虾皮本土店铺凭借其在出售、物流、回款、售后、仓储等方面的一条龙服务&#xff0c;为广大卖家提供了全方位的保障和支持。如…

VSCode报错插件Error lens

1.点击左侧扩展图标→搜索“error lens”→点击“安装” 2.安装成功页面如下&#xff1a; 3.代码测试一下&#xff1a;书写代码的过程中会出现红色提醒或红色报错 4.另外推荐小伙伴们安装中文插件&#xff0c;学习过程中会比较实用方便&#xff0c;需要安装中文插件的小伙伴请点…

【性能测试】资深老鸟带你,一篇打通负载与压力测试的区别...

目录&#xff1a;导读 前言一、Python编程入门到精通二、接口自动化项目实战三、Web自动化项目实战四、App自动化项目实战五、一线大厂简历六、测试开发DevOps体系七、常用自动化测试工具八、JMeter性能测试九、总结&#xff08;尾部小惊喜&#xff09; 前言 负载测试 是通过…

【lesson17】MySQL表的基本操作--表去重、聚合函数和group by

文章目录 MySQL表的基本操作介绍插入结果查询&#xff08;表去重&#xff09;建表插入数据操作 聚合函数建表插入数据操作 group by&#xff08;分组&#xff09;建表插入数据操作 MySQL表的基本操作介绍 CRUD : Create(创建), Retrieve(读取)&#xff0c;Update(更新)&#x…

2.vue学习(8-7)

文章目录 8.数据绑定9.el与data的2种写法 8.数据绑定 单向数据绑定就是我们学的v-bind的方式&#xff0c;vue对象变了&#xff0c;页面才变。但是页面变了&#xff0c;vue对象不会变。 双向数据绑定需要用v-model&#xff0c;就能实现双向的改变。 注意&#xff1a;不是所有的…

我的4096创作纪念日

机缘 岁月如梭&#xff0c;时光一晃已经在CSDN扎根4096天了。第一次注册CSDN好像还是在2012年&#xff0c;那会还没大学毕业。初入CSDN&#xff0c;只是把他当作自己编程时遇到问题的在线笔记记录而已&#xff0c;没想到无意间还帮助了其他遇到同样问题困扰的同学。而在这4096…

简析555电压检测电路

555定时器的简介 555定时器是一种多用途的数字——模拟混合集成电路&#xff0c;利用它能极方便地构成施密特触发器、单稳态触发器和多谐振荡器。由于使用灵活、方便&#xff0c;所以555定时器在波形的产生与交换、测量与控制、家用电器、电子玩具等许多领域中都得到了广泛应用…

idea添加外部jar包

在日常开发中在lib包的里面添加了外部的jar&#xff0c;如何将外部的包添加到java类库中&#xff0c;这样项目就可以引用相应的jar包&#xff0c;操作如下&#xff1a; 1.先将需要的jar复制到lib包如下&#xff0c;如下截图&#xff0c;图标前面没有箭头&#xff0c;表示还未添…

echart饼状图文字大小位置颜色调整属性

echart饼状图文字大小位置颜色调整属性 文字位置对应属性代码效果图 文字位置对应属性 1.图中‘1’的文字大小调整在‘legend’对象下的‘textStyle’属性里 2.图中‘2’的文字大小调整在‘tooltip’对象下的‘textStyle’属性里 3.图中‘3’的文字大小调整在‘series’对象下的…

flink 读取 apache paimon表,查看source的延迟时间 消费堆积情况

paimon source查看消费的数据延迟了多久 如果没有延迟 则显示0 官方文档 Metrics | Apache Paimon

什么是证券RPA?证券RPA解决什么问题?证券RPA实施难点在哪里?

RPA智能机器人&#xff0c;也称为“机器人流程自动化”、“软件机器人”&#xff0c;使用智能自动化技术来执行人类工人的重复性办公室任务。它结合API和用户界面(UI)交互来集成和执行企业和生产力应用程序之间的重复性任务。只要预先设计好使用规则&#xff0c;RPA就可以模拟人…

.NET 自定义中间件 判断是否存在 AllowAnonymousAttribute 特性 来判断是否需要身份验证

public Task InvokeAsync(HttpContext context){// 获取终点路由特性var endpointFeature context.Features.Get<IEndpointFeature>();// 获取是否定义了特性var attribute endpointFeature?.Endpoint?.Metadata?.GetMetadata<AllowAnonymousAttribute>();if …

项目中webpack优化配置(持续更新)

项目中webpack优化配置 1. 开发效率&#xff0c; 体验 DLL&#xff08;开发过程中减少构建时间和增加应用程序的性能&#xff09; 使用 DllPlugin 进行分包&#xff0c;使用 DllReferencePlugin(索引链接) 对 manifest.json 引用&#xff0c;让一些基本不会改动的代码先打包…

JVM调优排错专题

JVM调优排错专题 1 打开MAT报错 1 打开MAT报错 下载了linux版本的 MAT 软件&#xff0c;1.15.0版本。 下载地址&#xff1a;https://eclipse.dev/mat/downloads.php 运行时报错了。 错误截图 报错日志 wittasus:/usr/develop/mat$ ./MemoryAnalyzer Unrecognized option:…

【PHD申请文书】motivation letter|不限字数|Medical Imaging and Application

本文目录 APPLICATION ESSAYCriticism思考 Ref: https://essayforum.com/letters/tryst-technology-motivation-erasmus-degree-85383/ APPLICATION ESSAY My tryst with technology - motivation letter for Erasmus Degree in Medical Imaging and Application 原文机翻My…

视频素材网站全新上线,海量高清视频等你来探索~

亲爱的视频制作爱好者们&#xff0c;好消息来啦&#xff01;我们的视频素材网站全新上线啦&#xff01;这次我们为大家带来了海量的高清视频素材&#xff0c;无论是风景、城市、人物、动物还是各种特效、背景等&#xff0c;应有尽有&#xff0c;满足您在视频制作过程中的各种需…

WebMvcConfigurer接口详解及使用方式(Spring-WebMvc)

简介 如下图所示WebMvcConfigurer是spring-webmvc jar包下的一个接口&#xff0c;spring-webmvc jar包又来源于spring-boot-starter-web&#xff0c;所以要使用WebMvcConfigurer要引入spring-boot-starter-web依赖。WebMvcConfigurer接口提供了常用的web应用拦截方法。通过实现…

使用iframe后,鼠标点击位置和实际点击位置不一致

结论&#xff1a; 因为iframe域名和父页面域名不一致导致的 在本地启动项目的时候&#xff0c;鼠标指定的元素在iframe上&#xff0c;发现点击事件不起作用了 点击iframe里面的元素&#xff0c;发现也错位了&#xff0c; 上线之后&#xff0c;父页面部署的域名和iframe中src的…

WebCamTexture报错

使用WebCamTexture把相机的画面显示到 RawImage 上 using UnityEngine; using UnityEngine.UI;public class WebCamTextureTest : MonoBehaviour {public RawImage RawImage;private WebCamTexture _webCamTexture;private Color32[] _colorBuff;private Texture2D _texture2D…