├── .gitattributes ├── .github └── workflows │ └── build-and-release.yml ├── .gitignore ├── DnsOverHttps.sln ├── DnsOverHttps ├── Constants.cs ├── DnsOverHttps.cs ├── DnsOverHttps.csproj ├── Entities.cs ├── Exceptions.cs ├── Extensions.cs ├── NuGet.md └── icon.png ├── Example ├── Example.csproj └── Program.cs ├── LICENSE.txt └── README.md /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.github/workflows/build-and-release.yml: -------------------------------------------------------------------------------- 1 | name: Build and Release 2 | 3 | env: 4 | DOTNET_VERSION: '8.x' 5 | NUGET_SOURCE_URL: 'https://api.nuget.org/v3/index.json' 6 | BUILD_DIRECTORY: '${{ github.workspace }}/build' 7 | 8 | on: 9 | push: 10 | tags: 11 | - 'v*.*.*' 12 | 13 | jobs: 14 | build-and-release: 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - name: Checkout Repository 19 | uses: actions/checkout@v2 20 | 21 | - name: Get Version 22 | id: get_version 23 | run: | 24 | echo "tag=${GITHUB_REF_NAME}" >> $GITHUB_OUTPUT 25 | echo "version=${GITHUB_REF_NAME#v}" >> $GITHUB_OUTPUT 26 | 27 | - name: Get Project Metadata 28 | id: get_project_meta 29 | run: | 30 | name=$(echo '${{ github.repository }}' | cut -d '/' -f 2) 31 | 32 | echo "name=${name}" >> $GITHUB_OUTPUT 33 | echo "path=${name}/${name}.csproj" >> $GITHUB_OUTPUT 34 | 35 | - name: Setup .NET 36 | uses: actions/setup-dotnet@v3.2.0 37 | with: 38 | dotnet-version: ${{ env.DOTNET_VERSION }} 39 | 40 | - name: Restore Packages 41 | run: dotnet restore ${{ steps.get_project_meta.outputs.path }} 42 | 43 | - name: Build Project 44 | run: dotnet build ${{ steps.get_project_meta.outputs.path }} /p:ContinuousIntegrationBuild=true --no-restore --configuration Release 45 | 46 | - name: Pack Project 47 | run: dotnet pack ${{ steps.get_project_meta.outputs.path }} --no-restore --no-build --configuration Release --include-symbols -p:PackageVersion=${{ steps.get_version.outputs.version }} --output ${{ env.BUILD_DIRECTORY }} 48 | 49 | - name: Push Package 50 | env: 51 | NUGET_AUTH_TOKEN: ${{ secrets.NUGET_AUTH_TOKEN }} 52 | run: dotnet nuget push ${{ env.BUILD_DIRECTORY }}/*.nupkg -k $NUGET_AUTH_TOKEN -s ${{ env.NUGET_SOURCE_URL }} 53 | 54 | - name: Create Release 55 | uses: softprops/action-gh-release@v1 56 | with: 57 | token: ${{ secrets.GITHUB_TOKEN }} 58 | name: ${{ steps.get_version.outputs.tag }} 59 | body: ${{ github.event.head_commit.message }} 60 | files: '${{ env.BUILD_DIRECTORY }}/*' -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Oo]ut/ 33 | [Ll]og/ 34 | [Ll]ogs/ 35 | 36 | # Visual Studio 2015/2017 cache/options directory 37 | .vs/ 38 | # Uncomment if you have tasks that create the project's static files in wwwroot 39 | #wwwroot/ 40 | 41 | # Visual Studio 2017 auto generated files 42 | Generated\ Files/ 43 | 44 | # MSTest test Results 45 | [Tt]est[Rr]esult*/ 46 | [Bb]uild[Ll]og.* 47 | 48 | # NUnit 49 | *.VisualState.xml 50 | TestResult.xml 51 | nunit-*.xml 52 | 53 | # Build Results of an ATL Project 54 | [Dd]ebugPS/ 55 | [Rr]eleasePS/ 56 | dlldata.c 57 | 58 | # Benchmark Results 59 | BenchmarkDotNet.Artifacts/ 60 | 61 | # .NET Core 62 | project.lock.json 63 | project.fragment.lock.json 64 | artifacts/ 65 | 66 | # ASP.NET Scaffolding 67 | ScaffoldingReadMe.txt 68 | 69 | # StyleCop 70 | StyleCopReport.xml 71 | 72 | # Files built by Visual Studio 73 | *_i.c 74 | *_p.c 75 | *_h.h 76 | *.ilk 77 | *.meta 78 | *.obj 79 | *.iobj 80 | *.pch 81 | *.pdb 82 | *.ipdb 83 | *.pgc 84 | *.pgd 85 | *.rsp 86 | *.sbr 87 | *.tlb 88 | *.tli 89 | *.tlh 90 | *.tmp 91 | *.tmp_proj 92 | *_wpftmp.csproj 93 | *.log 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio LightSwitch build output 298 | **/*.HTMLClient/GeneratedArtifacts 299 | **/*.DesktopClient/GeneratedArtifacts 300 | **/*.DesktopClient/ModelManifest.xml 301 | **/*.Server/GeneratedArtifacts 302 | **/*.Server/ModelManifest.xml 303 | _Pvt_Extensions 304 | 305 | # Paket dependency manager 306 | .paket/paket.exe 307 | paket-files/ 308 | 309 | # FAKE - F# Make 310 | .fake/ 311 | 312 | # CodeRush personal settings 313 | .cr/personal 314 | 315 | # Python Tools for Visual Studio (PTVS) 316 | __pycache__/ 317 | *.pyc 318 | 319 | # Cake - Uncomment if you are using it 320 | # tools/** 321 | # !tools/packages.config 322 | 323 | # Tabs Studio 324 | *.tss 325 | 326 | # Telerik's JustMock configuration file 327 | *.jmconfig 328 | 329 | # BizTalk build output 330 | *.btp.cs 331 | *.btm.cs 332 | *.odx.cs 333 | *.xsd.cs 334 | 335 | # OpenCover UI analysis results 336 | OpenCover/ 337 | 338 | # Azure Stream Analytics local run output 339 | ASALocalRun/ 340 | 341 | # MSBuild Binary and Structured Log 342 | *.binlog 343 | 344 | # NVidia Nsight GPU debugger configuration file 345 | *.nvuser 346 | 347 | # MFractors (Xamarin productivity tool) working folder 348 | .mfractor/ 349 | 350 | # Local History for Visual Studio 351 | .localhistory/ 352 | 353 | # BeatPulse healthcheck temp database 354 | healthchecksdb 355 | 356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 357 | MigrationBackup/ 358 | 359 | # Ionide (cross platform F# VS Code tools) working folder 360 | .ionide/ 361 | 362 | # Fody - auto-generated XML schema 363 | FodyWeavers.xsd -------------------------------------------------------------------------------- /DnsOverHttps.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.4.33103.184 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DnsOverHttps", "DnsOverHttps\DnsOverHttps.csproj", "{2F451FDA-A97D-43E7-9CDF-C059ED41731D}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Example", "Example\Example.csproj", "{5E47EEF8-5B54-4793-B0B8-30B5E15D463F}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {2F451FDA-A97D-43E7-9CDF-C059ED41731D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {2F451FDA-A97D-43E7-9CDF-C059ED41731D}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {2F451FDA-A97D-43E7-9CDF-C059ED41731D}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {2F451FDA-A97D-43E7-9CDF-C059ED41731D}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {5E47EEF8-5B54-4793-B0B8-30B5E15D463F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {5E47EEF8-5B54-4793-B0B8-30B5E15D463F}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {5E47EEF8-5B54-4793-B0B8-30B5E15D463F}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {5E47EEF8-5B54-4793-B0B8-30B5E15D463F}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {BDE5E3B8-D31A-40DE-A694-2B1399AB69F0} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /DnsOverHttps/Constants.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace DnsOverHttps 4 | { 5 | internal class Constants 6 | { 7 | /// 8 | /// The hostname of the Dns-over-HTTPS resolver. 9 | /// 10 | public const string Hostname = "1.1.1.1"; 11 | /// 12 | /// The base URI to send requests to. 13 | /// 14 | public static readonly Uri BaseUri = new($"https://{Hostname}/dns-query"); 15 | /// 16 | /// The preferred HTTP request version to use. 17 | /// 18 | public static readonly Version HttpVersion = new(2, 0); 19 | /// 20 | /// The User-Agent header value to send along requests. 21 | /// 22 | public const string UserAgent = "C# DnsOverHttps Client - actually-akac/DnsOverHttps"; 23 | /// 24 | /// The Accept header value to send along requests. 25 | /// 26 | public const string ContentType = "application/dns-json"; 27 | /// 28 | /// The maximum string length when displaying a preview of a response body. 29 | /// 30 | public const int PreviewMaxLength = 500; 31 | } 32 | } -------------------------------------------------------------------------------- /DnsOverHttps/DnsOverHttps.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Net; 4 | using System.Net.Http; 5 | using System.Threading.Tasks; 6 | 7 | namespace DnsOverHttps 8 | { 9 | /// 10 | /// The primary class for sending DNS over HTTPS queries. 11 | /// 12 | public class DnsOverHttpsClient 13 | { 14 | private readonly HttpClient Client = new() 15 | { 16 | BaseAddress = Constants.BaseUri, 17 | DefaultRequestVersion = Constants.HttpVersion 18 | }; 19 | 20 | /// 21 | /// Create a new instance of the DNS over HTTPS client. 22 | /// 23 | public DnsOverHttpsClient() 24 | { 25 | Client.DefaultRequestHeaders.UserAgent.ParseAdd(Constants.UserAgent); 26 | Client.DefaultRequestHeaders.Accept.ParseAdd(Constants.ContentType); 27 | } 28 | 29 | /// 30 | /// Resolve a name using Cloudflare's DNS over HTTPS. Use this method if you want full control over the output. 31 | /// 32 | /// Alternatively, and may be used for better experience. 33 | /// 34 | /// 35 | /// The FQDN to resolve. Example: foo.bar.example.com 36 | /// The DNS resource type to resolve. By default, this is the A record. 37 | /// 38 | /// Whether to request DNSSEC data in the response.
39 | /// When requested, it will be accessible under the array. 40 | /// 41 | /// Whether to validate DNSSEC data. 42 | /// 43 | /// 44 | /// 45 | public async Task Resolve(string name, ResourceRecordType type = ResourceRecordType.A, bool requestDnsSec = false, bool validateDnsSec = false) 46 | { 47 | if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name), "Name is null or empty."); 48 | 49 | string url = string.Concat( 50 | $"?name={name.UrlEncode()}", 51 | type == ResourceRecordType.A ? "" : $"&type={type.ToString().UrlEncode()}", 52 | requestDnsSec == false ? "" : $"&do=1", 53 | validateDnsSec == false ? "" : $"&cd=1"); 54 | 55 | using HttpRequestMessage req = new(HttpMethod.Get, url); 56 | using HttpResponseMessage res = await Client.SendAsync(req); 57 | 58 | Response response = await res.Deseralize(); 59 | 60 | if (res.StatusCode != HttpStatusCode.OK || !string.IsNullOrEmpty(response.Error) || response.Comments is not null) 61 | { 62 | string message = string.Concat( 63 | $"Failed to query type {type} of \"{name}\", received HTTP status code {res.StatusCode}.", 64 | string.IsNullOrEmpty(response.Error) ? "" : $"\nError: {response.Error}", 65 | response.Comments is null ? "" : $"\nComments: {string.Join(", ", response.Comments)}"); 66 | 67 | throw new DnsOverHttpsException(message, response); 68 | } 69 | 70 | return response; 71 | } 72 | 73 | /// 74 | /// Resolve multiple DNS resource types of a name in parallel using Cloudflare's DNS over HTTPS. 75 | /// 76 | /// The FQDN to resolve. Example: foo.bar.example.com 77 | /// The DNS resource record types to resolve. By default, this is the A record. 78 | /// 79 | /// Whether to request DNSSEC data in the response.
80 | /// When requested, it will be accessible under the array. 81 | /// 82 | /// Whether to validate DNSSEC data. 83 | /// 84 | /// 85 | /// 86 | public async Task Resolve(string name, ResourceRecordType[] types, bool requestDnsSec = false, bool validateDnsSec = false) 87 | { 88 | Task[] tasks = new Task[types.Length]; 89 | for (int i = 0; i < tasks.Length; i++) tasks[i] = Resolve(name, types[i], requestDnsSec, validateDnsSec); 90 | 91 | await Task.WhenAll(tasks); 92 | 93 | Response[] responses = new Response[tasks.Length]; 94 | for (int i = 0; i < tasks.Length; i++) responses[i] = await tasks[i]; 95 | 96 | return responses; 97 | } 98 | 99 | /// 100 | /// Resolve a name using Cloudflare's DNS over HTTPS. This helper method returns the first answer of a provided type. 101 | /// 102 | /// Alternatively, may be used to get full control over the response. 103 | /// 104 | /// 105 | /// The FQDN to resolve. Example: foo.bar.example.com 106 | /// The DNS resource type to resolve. By default, this is the A record. 107 | /// 108 | /// Whether to request DNSSEC data in the response.
109 | /// When requested, it will be accessible under the array. 110 | /// 111 | /// Whether to validate DNSSEC data. 112 | /// 113 | /// 114 | /// 115 | public async Task ResolveFirst(string name, ResourceRecordType type = ResourceRecordType.A, bool requestDnsSec = false, bool validateDnsSec = false) 116 | { 117 | Response res = await Resolve(name, type, requestDnsSec, validateDnsSec); 118 | 119 | return res.Answers?.FirstOrDefault(x => x.Type == type); 120 | } 121 | 122 | /// 123 | /// Resolve a name using Cloudflare's DNS over HTTPS. This helper method returns all answers of a provided type. 124 | /// 125 | /// The FQDN to resolve. Example: foo.bar.example.com 126 | /// The DNS resource type to resolve. By default, this is the A record. 127 | /// 128 | /// Whether to request DNSSEC data in the response.
129 | /// When requested, it will be accessible under the array. 130 | /// 131 | /// Whether to validate DNSSEC data. 132 | /// 133 | /// 134 | /// 135 | public async Task ResolveAll(string name, ResourceRecordType type = ResourceRecordType.A, bool requestDnsSec = false, bool validateDnsSec = false) 136 | { 137 | Response res = await Resolve(name, type, requestDnsSec, validateDnsSec); 138 | 139 | return res.Answers.Where(x => x.Type == type).ToArray(); 140 | } 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /DnsOverHttps/DnsOverHttps.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | net6.0;net7.0;net8.0 6 | DnsOverHttps 7 | DnsOverHttps 8 | akac 9 | akac 10 | An async and lightweight C# library for Cloudflare's DNS over HTTPS. 11 | dns; domain-name-system; domain; dns-over-https; doh; record; resolve; csharp; api; library 12 | icon.png 13 | NuGet.md 14 | 15 | 16 | 1.2.2 17 | 1.2.2 18 | 1.2.2 19 | 20 | 21 | https://github.com/actually-akac/DnsOverHttps 22 | https://github.com/actually-akac/DnsOverHttps 23 | git 24 | true 25 | 26 | 27 | true 28 | snupkg 29 | true 30 | 31 | 32 | MIT 33 | false 34 | en 35 | 36 | 37 | 38 | 1701;1702;1591 39 | 40 | 41 | 42 | 1701;1702;1591 43 | 44 | 45 | 46 | 47 | True 48 | \ 49 | 50 | 51 | True 52 | \ 53 | 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /DnsOverHttps/Entities.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | namespace DnsOverHttps 4 | { 5 | /// 6 | /// Indicates the status of a query (DNS RCODE). 7 | /// 8 | /// Documentation:
9 | /// RFC: , 10 | ///
11 | ///
12 | public enum ResponseCode : byte 13 | { 14 | /// 15 | /// DNS Query completed successfully. 16 | /// 17 | NoError, 18 | /// 19 | /// DNS query resulted in a format error. 20 | /// 21 | FormatError, 22 | /// 23 | /// Server failed to complete the DNS query. 24 | /// 25 | ServerFailure, 26 | /// 27 | /// Domain name does not exist. 28 | /// 29 | NXDomain, 30 | /// 31 | /// Function not implemented. 32 | /// 33 | NotImplemented, 34 | /// 35 | /// The server refused to answer to the DNS query. 36 | /// 37 | Refused, 38 | /// 39 | /// Name that should not exist, does exist. 40 | /// 41 | YXDomain, 42 | /// 43 | /// RR Set exists when it should not. 44 | /// 45 | YXRRSet, 46 | /// 47 | /// RR Set that should exist does not. 48 | /// 49 | NXRRSet, 50 | /// 51 | /// Server not authoritative for zone/Not authorized. 52 | /// 53 | NotAuth, 54 | /// 55 | /// Name not contained in zone. 56 | /// 57 | NotZone, 58 | /// 59 | /// DSO-TYPE not implemented. 60 | /// 61 | DSOTYPENotImplemented, 62 | /// 63 | /// Bad OPT version. 64 | /// 65 | BadVersion = 16, 66 | /// 67 | /// TSIG signature failure. 68 | /// 69 | BadSignature, 70 | /// 71 | /// Key not recognized. 72 | /// 73 | BadKey, 74 | /// 75 | /// Signature out of time window. 76 | /// 77 | BadTime, 78 | /// 79 | /// Bad TKEY Mode. 80 | /// 81 | BadMode, 82 | /// 83 | /// Duplicate key name. 84 | /// 85 | BadName, 86 | /// 87 | /// Algorithm not supported. 88 | /// 89 | BadAlgorithm, 90 | /// 91 | /// Bad truncation. 92 | /// 93 | BadTruncation, 94 | /// 95 | /// Bad/missing server cookie. 96 | /// 97 | BadCookie 98 | } 99 | 100 | /// 101 | /// Indicates the type of a DNS resource record. 102 | /// 103 | /// Documentation:
104 | ///
105 | ///
106 | public enum ResourceRecordType : byte 107 | { 108 | Reserved, 109 | /// 110 | /// A host address. 111 | /// 112 | A, 113 | /// 114 | /// An authoritative name server. 115 | /// 116 | NS, 117 | /// 118 | /// A mail destination (OBSOLETE - use MX). 119 | /// 120 | MD, 121 | /// 122 | /// A mail forwarder (OBSOLETE - use MX). 123 | /// 124 | MF, 125 | /// 126 | /// The canonical name for an alias. 127 | /// 128 | CNAME, 129 | /// 130 | /// Marks the start of a zone of authority. 131 | /// 132 | SOA, 133 | /// 134 | /// A mailbox domain name (EXPERIMENTAL). 135 | /// 136 | MB, 137 | /// 138 | /// A mail group member (EXPERIMENTAL). 139 | /// 140 | MG, 141 | /// 142 | /// A mail rename domain name (EXPERIMENTAL). 143 | /// 144 | MR, 145 | /// 146 | /// A null RR (EXPERIMENTAL). 147 | /// 148 | NULL, 149 | /// 150 | /// A well known service description. 151 | /// 152 | WKS, 153 | /// 154 | /// A domain name pointer. 155 | /// 156 | PTR, 157 | /// 158 | /// Host information. 159 | /// 160 | HINFO, 161 | /// 162 | /// Mailbox or mail list information. 163 | /// 164 | MINFO, 165 | /// 166 | /// Mail exchange. 167 | /// 168 | MX, 169 | /// 170 | /// Text strings. 171 | /// 172 | TXT, 173 | /// 174 | /// For responsible person. 175 | /// 176 | RP, 177 | /// 178 | /// For a security signature. 179 | /// 180 | SIG = 24, 181 | /// 182 | /// IPv6 Address. 183 | /// 184 | AAAA = 28, 185 | /// 186 | /// Location information. 187 | /// 188 | LOC = 29, 189 | /// 190 | /// Server selection. 191 | /// 192 | SRV = 33, 193 | DNAME = 39, 194 | IPSECKEY = 45, 195 | /// 196 | /// RRset Signature. 197 | /// 198 | RRSIG = 46, 199 | DNSKEY = 48, 200 | /// 201 | /// For the sender policy framework. 202 | /// 203 | SPF = 99 204 | } 205 | 206 | /// 207 | /// The result of a DNS over HTTPS query. 208 | /// 209 | public struct Response 210 | { 211 | /// 212 | /// A DNS response code. 213 | /// 214 | [JsonPropertyName("Status")] 215 | public ResponseCode Status { get; set; } 216 | 217 | /// 218 | /// TC: Whether the response is truncated due to length greater than that permitted on the transmission channel. 219 | /// 220 | [JsonPropertyName("TC")] 221 | public bool IsTruncated { get; set; } 222 | 223 | /// 224 | /// RD: Whether recursion is desired.
225 | /// This bit may be set in a query and is copied into the response. If RD is set, it directs the name server to pursue the query recursively. Recursive query support is optional. 226 | ///
227 | [JsonPropertyName("RD")] 228 | public bool IsRecursionDesired { get; set; } 229 | 230 | /// 231 | /// RA: Whether recursion is available.
232 | /// This bit is set or cleared in a response, and denotes whether recursive query support is available in the name server. 233 | ///
234 | [JsonPropertyName("RA")] 235 | public bool IsRecursionAvailable { get; set; } 236 | 237 | /// 238 | /// AD: Whether the resolver believes the responses to be authentic - that is, validated by DNSSEC. 239 | /// 240 | [JsonPropertyName("AD")] 241 | public bool AuthenticData { get; set; } 242 | 243 | /// 244 | /// CD: Whether a security-aware resolver should disable signature validation (that is, not check DNSSEC records). 245 | /// 246 | [JsonPropertyName("CD")] 247 | public bool CheckingDisabled { get; set; } 248 | 249 | /// 250 | /// A DNS question sent by the client. 251 | /// 252 | [JsonPropertyName("Question")] 253 | public Question[] Questions { get; set; } 254 | 255 | /// 256 | /// A DNS answer sent by the server. 257 | /// 258 | [JsonPropertyName("Answer")] 259 | public Answer[] Answers { get; set; } 260 | 261 | /// 262 | /// A DNS authority sent by the server. 263 | /// 264 | [JsonPropertyName("Authority")] 265 | public Answer[] Authorities { get; set; } 266 | 267 | /// 268 | /// Additional answers sent by the server. 269 | /// 270 | [JsonPropertyName("Additional")] 271 | public Answer[] Additional { get; set; } 272 | 273 | /// 274 | /// An error message describing an issue with your DNS query. This is always included in the 400 Bad Request status code. 275 | /// 276 | [JsonPropertyName("error")] 277 | public string Error { get; set; } 278 | 279 | /// 280 | /// An extended DNS error code message. 281 | /// 282 | /// Documentation: 283 | /// 284 | /// 285 | [JsonPropertyName("Comment")] 286 | public string[] Comments { get; set; } 287 | } 288 | 289 | /// 290 | /// A DNS question sent by the client. 291 | /// 292 | public struct Question 293 | { 294 | /// 295 | /// The FQDN record name requested. 296 | /// 297 | [JsonPropertyName("name")] 298 | public string Name { get; set; } 299 | 300 | /// 301 | /// The type of DNS record requested. 302 | /// 303 | [JsonPropertyName("type")] 304 | public ResourceRecordType Type { get; set; } 305 | } 306 | 307 | /// 308 | /// A DNS answer sent by the server. 309 | /// 310 | public struct Answer 311 | { 312 | /// 313 | /// The record owner. 314 | /// 315 | [JsonPropertyName("name")] 316 | public string Name { get; set; } 317 | 318 | /// 319 | /// The type of DNS record. 320 | /// 321 | [JsonPropertyName("type")] 322 | public ResourceRecordType Type { get; set; } 323 | 324 | /// 325 | /// The number of seconds the answer can be stored in cache before it is considered stale. 326 | /// 327 | [JsonPropertyName("TTL")] 328 | public int TTL { get; set; } 329 | 330 | /// 331 | /// The value of the DNS record for the given name and type. The data will be in text for standardized record types and in HEX for unknown types. 332 | /// 333 | [JsonPropertyName("data")] 334 | public string Data { get; set; } 335 | } 336 | } -------------------------------------------------------------------------------- /DnsOverHttps/Exceptions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace DnsOverHttps 4 | { 5 | /// 6 | /// An exception specific to DNS over HTTPS. You can access the exception's properties to get the context for the exception. 7 | /// 8 | public class DnsOverHttpsException : Exception 9 | { 10 | /// 11 | /// The DNS response that caused this exception. 12 | /// 13 | public Response Response { get; set; } 14 | 15 | public DnsOverHttpsException(string message) : base(message) { } 16 | public DnsOverHttpsException(string message, Response res) : base(message) 17 | { 18 | Response = res; 19 | } 20 | } 21 | } -------------------------------------------------------------------------------- /DnsOverHttps/Extensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Net; 4 | using System.Net.Http; 5 | using System.Text.Json; 6 | using System.Threading.Tasks; 7 | 8 | namespace DnsOverHttps 9 | { 10 | internal static class Extensions 11 | { 12 | public static string UrlEncode(this string value) => WebUtility.UrlEncode(value); 13 | 14 | /// 15 | /// Deserialize a JSON HTTP response into a given type. 16 | /// 17 | /// The type to deserialize into. 18 | /// The HTTP response message with JSON as a body. 19 | public static async Task Deseralize(this HttpResponseMessage res) 20 | { 21 | using Stream stream = await res.Content.ReadAsStreamAsync(); 22 | if (stream.Length == 0) throw new DnsOverHttpsException("Response content is empty, can't parse as JSON."); 23 | 24 | try 25 | { 26 | return await JsonSerializer.DeserializeAsync(stream); 27 | } 28 | catch (Exception ex) 29 | { 30 | throw new DnsOverHttpsException($"Exception while parsing JSON: {ex.GetType().Name} => {ex.Message}\nPreview: {await stream.GetPreview()}"); 31 | } 32 | } 33 | 34 | /// 35 | /// Serialize an object into a JSON HTTP Stream Content. 36 | /// 37 | /// The object to serialize as JSON. 38 | public static async Task Serialize(this object obj) 39 | { 40 | MemoryStream ms = new(); 41 | await JsonSerializer.SerializeAsync(ms, obj); 42 | ms.Position = 0; 43 | 44 | StreamContent sc = new(ms); 45 | sc.Headers.ContentType = new("application/json"); 46 | 47 | return sc; 48 | } 49 | 50 | /// 51 | /// Extract a short preview string from a HTTP response body. 52 | /// 53 | /// The HTTP response message with a body. 54 | public static async Task GetPreview(this HttpResponseMessage res) 55 | { 56 | using Stream stream = await res.Content.ReadAsStreamAsync(); 57 | if (stream.Length == 0) throw new DnsOverHttpsException("Response content is empty, can't extract body."); 58 | 59 | return await GetPreview(stream); 60 | } 61 | 62 | /// 63 | /// Extract a short preview string from a HTTP response body. 64 | /// 65 | /// The HTTP response stream. 66 | public static async Task GetPreview(this Stream stream) 67 | { 68 | stream.Position = 0; 69 | using StreamReader sr = new(stream); 70 | 71 | char[] buffer = new char[Math.Min(stream.Length, Constants.PreviewMaxLength)]; 72 | int bytesRead = await sr.ReadAsync(buffer, 0, buffer.Length); 73 | string text = new(buffer, 0, bytesRead); 74 | 75 | return text; 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /DnsOverHttps/NuGet.md: -------------------------------------------------------------------------------- 1 | # DnsOverHttps 2 | 3 | ![](https://raw.githubusercontent.com/actually-akac/DnsOverHttps/master/DnsOverHttps/icon.png) 4 | 5 | ### An async and lightweight C# library for Cloudflare's DNS over HTTPS. 6 | 7 | ## Usage 8 | This library provides an easy interface for interacting with Cloudflare's DNS over HTTPS endpoints. 9 | 10 | DoH is a protocol that enhances the privacy and security of DNS queries by encrypting them using HTTPS. This helps prevent unauthorized access or tampering of DNS data during transmission. Learn more about it [here](https://developers.cloudflare.com/1.1.1.1/encryption/dns-over-https/). 11 | 12 | To get started, import the library into your solution with either the `NuGet Package Manager` or the `dotnet` CLI. 13 | ```rust 14 | dotnet add package DnsOverHttps 15 | ``` 16 | 17 | For the primary class to become available, import the used namespace. 18 | ```csharp 19 | using DnsOverHttps; 20 | ``` 21 | 22 | Need more examples? Under the `Example` directory you can find a working demo project that implements this library. 23 | 24 | ## Properties 25 | - Built for **.NET 8**, **.NET 7** and **.NET 6** 26 | - Fully **async** 27 | - Extensive **XML documentation** 28 | - **No external dependencies** (makes use of built-in `HttpClient` and `JsonSerializer`) 29 | - **Custom exceptions** (`DnsOverHttpsException`) for easy debugging 30 | - Example project to demonstrate all capabilities of the library 31 | 32 | ## Features 33 | - Resolve one or all DNS records under a hostname 34 | - Ask for DNSSEC validation 35 | - Query in parallel 36 | - Specify advanced parameters 37 | 38 | ## Code Samples 39 | 40 | ### Initializing a new API client 41 | ```csharp 42 | DnsOverHttpsClient dns = new(); 43 | ``` 44 | 45 | ### Resolving A DNS records including DNSSEC 46 | ```csharp 47 | Response response = await dns.Resolve("discord.com", ResourceRecordType.A, true, true); 48 | ``` 49 | 50 | ### Using helper methods to return the first or all answers 51 | ```csharp 52 | Answer? nsAnswer = await dns.ResolveFirst("example.com", ResourceRecordType.NS); 53 | Answer[] aAnswers = await dns.ResolveAll("reddit.com", ResourceRecordType.A); 54 | ``` 55 | 56 | ## Resources 57 | - Cloudflare: https://cloudflare.com 58 | - 1.1.1.1: https://1.1.1.1 59 | - Introduction: https://developers.cloudflare.com/1.1.1.1/encryption/dns-over-https 60 | 61 | *This is a community-ran library. Not affiliated with Cloudflare, Inc.* 62 | 63 | *Icon made by **Freepik** at [Flaticon](https://www.flaticon.com).* -------------------------------------------------------------------------------- /DnsOverHttps/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/akacdev/DnsOverHttps/f279a1eefea51c301e7ba20fb5918d7482a75c5f/DnsOverHttps/icon.png -------------------------------------------------------------------------------- /Example/Example.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net8.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /Example/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | using DnsOverHttps; 4 | 5 | namespace Example 6 | { 7 | public static class Program 8 | { 9 | private static readonly DnsOverHttpsClient Client = new(); 10 | 11 | public static async Task Main() 12 | { 13 | Console.WriteLine($"> Resolving the first NS record on example.com"); 14 | Answer? nsAnswer = await Client.ResolveFirst("example.com", ResourceRecordType.NS); 15 | 16 | Console.WriteLine($"Result:"); 17 | PrintAnswer(nsAnswer); 18 | 19 | 20 | Console.WriteLine($"\n> Resolving all A records on reddit.com"); 21 | Answer[] aAnswers = await Client.ResolveAll("reddit.com", ResourceRecordType.A); 22 | 23 | Console.WriteLine($"Result:"); 24 | foreach (Answer answer in aAnswers) PrintAnswer(answer); 25 | Console.WriteLine(); 26 | 27 | 28 | Console.WriteLine($"\n> Resolving an invalid domain"); 29 | Answer? nxDomain = await Client.ResolveFirst("5525fe855b7366f93447cd039ab885.com", ResourceRecordType.A); 30 | Console.WriteLine($"Result is {(nxDomain is null ? "null" : $"not null: {nxDomain.Value.Data}")}"); 31 | Console.WriteLine(); 32 | 33 | 34 | Console.WriteLine($"\n> Resolving A records on discord.com with DNSSEC"); 35 | Response response = await Client.Resolve("discord.com", ResourceRecordType.A, true, true); 36 | 37 | Console.WriteLine($"Result:"); 38 | foreach (Answer answer in response.Answers) PrintAnswer(answer); 39 | 40 | 41 | Console.WriteLine($"\n> Resolving multiple records in parallel on github.com"); 42 | Response[] responses = await Client.Resolve("github.com", [ResourceRecordType.A, ResourceRecordType.MX, ResourceRecordType.NS]); 43 | 44 | foreach (Response resp in responses) 45 | foreach (Answer answer in resp.Answers) PrintAnswer(answer); 46 | 47 | 48 | Console.WriteLine("\nDemo finished"); 49 | Console.ReadKey(); 50 | } 51 | 52 | public static void PrintAnswer(Answer? answer) 53 | { 54 | Console.WriteLine($"\tType: {answer.Value.Type}; TTL: {answer.Value.TTL}; Translation: {answer.Value.Name} => {answer.Value.Data}"); 55 | } 56 | } 57 | } -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 actually-akac 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DnsOverHttps 2 | 3 |
4 | 5 |
6 | 7 |
8 | An async and lightweight C# library for Cloudflare's DNS over HTTPS. 9 |
10 | 11 | ## Usage 12 | This library provides an easy interface for interacting with Cloudflare's DNS over HTTPS endpoints. 13 | 14 | DoH is a protocol that enhances the privacy and security of DNS queries by encrypting them using HTTPS. This helps prevent unauthorized access or tampering of DNS data during transmission. Learn more about it [here](https://developers.cloudflare.com/1.1.1.1/encryption/dns-over-https/). 15 | 16 | To get started, import the library into your solution with either the `NuGet Package Manager` or the `dotnet` CLI. 17 | ```rust 18 | dotnet add package DnsOverHttps 19 | ``` 20 | 21 | For the primary class to become available, import the used namespace. 22 | ```csharp 23 | using DnsOverHttps; 24 | ``` 25 | 26 | Need more examples? Under the `Example` directory you can find a working demo project that implements this library. 27 | 28 | ## Properties 29 | - Built for **.NET 8**, **.NET 7** and **.NET 6** 30 | - Fully **async** 31 | - Extensive **XML documentation** 32 | - **No external dependencies** (makes use of built-in `HttpClient` and `JsonSerializer`) 33 | - **Custom exceptions** (`DnsOverHttpsException`) for easy debugging 34 | - Example project to demonstrate all capabilities of the library 35 | 36 | ## Features 37 | - Resolve one or all DNS records under a hostname 38 | - Ask for DNSSEC validation 39 | - Query in parallel 40 | - Specify advanced parameters 41 | 42 | ## Code Samples 43 | 44 | ### Initializing a new API client 45 | ```csharp 46 | DnsOverHttpsClient dns = new(); 47 | ``` 48 | 49 | ### Resolving A DNS records including DNSSEC 50 | ```csharp 51 | Response response = await dns.Resolve("discord.com", ResourceRecordType.A, true, true); 52 | ``` 53 | 54 | ### Using helper methods to return the first or all answers 55 | ```csharp 56 | Answer? nsAnswer = await dns.ResolveFirst("example.com", ResourceRecordType.NS); 57 | Answer[] aAnswers = await dns.ResolveAll("reddit.com", ResourceRecordType.A); 58 | ``` 59 | 60 | ## Resources 61 | - Cloudflare: https://cloudflare.com 62 | - 1.1.1.1: https://1.1.1.1 63 | - Introduction: https://developers.cloudflare.com/1.1.1.1/encryption/dns-over-https 64 | 65 | *This is a community-ran library. Not affiliated with Cloudflare, Inc.* 66 | 67 | *Icon made by **Freepik** at [Flaticon](https://www.flaticon.com).* --------------------------------------------------------------------------------