-
-
Notifications
You must be signed in to change notification settings - Fork 138
/
Copy pathDnsQueryExtensions.cs
778 lines (716 loc) · 38.6 KB
/
DnsQueryExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
// Copyright 2024 Michael Conrad.
// Licensed under the Apache License, Version 2.0.
// See LICENSE file for details.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
using DnsClient.Protocol;
namespace DnsClient
{
/// <summary>
/// Extension methods for the <see cref="IDnsQuery"/> contract.
/// <para>
/// The methods implement common queries which are more complex and have some business logic.
/// </para>
/// </summary>
public static class DnsQueryExtensions
{
/// <summary>
/// The <c>GetHostEntry</c> method queries a DNS server for the IP addresses and aliases associated with the <paramref name="hostNameOrAddress"/>.
/// In case <paramref name="hostNameOrAddress"/> is an <see cref="IPAddress"/>, <c>GetHostEntry</c> does a reverse lookup on that first to determine the hostname.
/// <para>
/// IP addresses found are returned in <see cref="IPHostEntry.AddressList"/>.
/// <see cref="ResourceRecordType.CNAME"/> records are used to populate the <see cref="IPHostEntry.Aliases"/>.<br/>
/// The <see cref="IPHostEntry.HostName"/> property will be set to the resolved hostname or <paramref name="hostNameOrAddress"/>.
/// </para>
/// </summary>
/// <example>
/// The following code example uses the <see cref="GetHostEntry(IDnsQuery, string)"/> method to resolve an IP address or hostname to an <see cref="IPHostEntry"/> instance.
/// <code>
/// <![CDATA[
/// public static void PrintHostEntry(string hostOrIp)
/// {
/// var lookup = new LookupClient();
/// IPHostEntry hostEntry = lookup.GetHostEntry(hostOrIp);
/// Console.WriteLine(hostEntry.HostName);
/// foreach (var ip in hostEntry.AddressList)
/// {
/// Console.WriteLine(ip);
/// }
/// foreach (var alias in hostEntry.Aliases)
/// {
/// Console.WriteLine(alias);
/// }
/// }
/// ]]>
/// </code>
/// </example>
/// <remarks>
/// The method has some logic to populate the <see cref="IPHostEntry.Aliases"/> list:
/// <list type="bullet">
/// <item>
/// <term>
/// In case of sub-domain queries or similar, there might be multiple <see cref="ResourceRecordType.CNAME"/> records for one <see cref="IPAddress"/>,
/// </term>
/// </item><item>
/// <term>
/// If only one <see cref="IPAddress"/> is in the result set, all the aliases found will be returned.
/// </term>
/// </item><item>
/// <term>
/// If more than one <see cref="IPAddress"/> is in the result set, aliases are returned only if at least one doesn't match the queried hostname.
/// </term>
/// </item>
/// </list>
/// </remarks>
/// <param name="query">The <see cref="IDnsQuery"/> instance.</param>
/// <param name="hostNameOrAddress">The <see cref="IPAddress"/> or host name to query for.</param>
/// <returns>
/// An <see cref="IPHostEntry"/> instance that contains address information about the host specified in <paramref name="hostNameOrAddress"/>.
/// In case the <paramref name="hostNameOrAddress"/> could not be resolved to a domain name, this method returns <c>null</c>,
/// unless <see cref="DnsQueryOptions.ThrowDnsErrors"/> is set to true, then it might throw a <see cref="DnsResponseException"/>.
/// </returns>
/// <exception cref="ArgumentNullException">If <paramref name="hostNameOrAddress"/> is null.</exception>
/// <exception cref="DnsResponseException">In case <see cref="DnsQueryOptions.ThrowDnsErrors"/> is set to true and a DNS error occurs.</exception>
public static IPHostEntry GetHostEntry(this IDnsQuery query, string hostNameOrAddress)
{
if (query == null)
{
throw new ArgumentNullException(nameof(query));
}
if (string.IsNullOrWhiteSpace(hostNameOrAddress))
{
throw new ArgumentNullException(nameof(hostNameOrAddress));
}
if (IPAddress.TryParse(hostNameOrAddress, out IPAddress address))
{
return query.GetHostEntry(address);
}
return GetHostEntryFromName(query, hostNameOrAddress);
}
/// <summary>
/// The <c>GetHostEntryAsync</c> method queries a DNS server for the IP addresses and aliases associated with the <paramref name="hostNameOrAddress"/>.
/// In case <paramref name="hostNameOrAddress"/> is an <see cref="IPAddress"/>, <c>GetHostEntry</c> does a reverse lookup on that first to determine the hostname.
/// <para>
/// IP addresses found are returned in <see cref="IPHostEntry.AddressList"/>.
/// <see cref="ResourceRecordType.CNAME"/> records are used to populate the <see cref="IPHostEntry.Aliases"/>.<br/>
/// The <see cref="IPHostEntry.HostName"/> property will be set to the resolved hostname or <paramref name="hostNameOrAddress"/>.
/// </para>
/// </summary>
/// <example>
/// The following code example uses the <see cref="GetHostEntryAsync(IDnsQuery, string)"/> method to resolve an IP address or hostname to an <see cref="IPHostEntry"/> instance.
/// <code>
/// <![CDATA[
/// public static async Task PrintHostEntry(string hostOrIp)
/// {
/// var lookup = new LookupClient();
/// IPHostEntry hostEntry = await lookup.GetHostEntryAsync(hostOrIp);
/// Console.WriteLine(hostEntry.HostName);
/// foreach (var ip in hostEntry.AddressList)
/// {
/// Console.WriteLine(ip);
/// }
/// foreach (var alias in hostEntry.Aliases)
/// {
/// Console.WriteLine(alias);
/// }
/// }
/// ]]>
/// </code>
/// </example>
/// <remarks>
/// The method has some logic to populate the <see cref="IPHostEntry.Aliases"/> list:
/// <list type="bullet">
/// <item>
/// <term>
/// In case of sub-domain queries or similar, there might be multiple <see cref="ResourceRecordType.CNAME"/> records for one <see cref="IPAddress"/>,
/// </term>
/// </item><item>
/// <term>
/// If only one <see cref="IPAddress"/> is in the result set, all the aliases found will be returned.
/// </term>
/// </item><item>
/// <term>
/// If more than one <see cref="IPAddress"/> is in the result set, aliases are returned only if at least one doesn't match the queried hostname.
/// </term>
/// </item>
/// </list>
/// </remarks>
/// <param name="query">The <see cref="IDnsQuery"/> instance.</param>
/// <param name="hostNameOrAddress">The <see cref="IPAddress"/> or host name to query for.</param>
/// <returns>
/// An <see cref="IPHostEntry"/> instance that contains address information about the host specified in <paramref name="hostNameOrAddress"/>.
/// In case the <paramref name="hostNameOrAddress"/> could not be resolved to a domain name, this method returns <c>null</c>,
/// unless <see cref="DnsQueryOptions.ThrowDnsErrors"/> is set to true, then it might throw a <see cref="DnsResponseException"/>.
/// </returns>
/// <exception cref="ArgumentNullException">If <paramref name="hostNameOrAddress"/> is null.</exception>
/// <exception cref="DnsResponseException">In case <see cref="DnsQueryOptions.ThrowDnsErrors"/> is set to true and a DNS error occurs.</exception>
public static Task<IPHostEntry> GetHostEntryAsync(this IDnsQuery query, string hostNameOrAddress)
{
if (query == null)
{
throw new ArgumentNullException(nameof(query));
}
if (string.IsNullOrWhiteSpace(hostNameOrAddress))
{
throw new ArgumentNullException(nameof(hostNameOrAddress));
}
if (IPAddress.TryParse(hostNameOrAddress, out IPAddress address))
{
return query.GetHostEntryAsync(address);
}
return GetHostEntryFromNameAsync(query, hostNameOrAddress);
}
/// <summary>
/// The <c>GetHostEntry</c> method does a reverse lookup on the IP <paramref name="address"/>,
/// and queries a DNS server for the IP addresses and aliases associated with the resolved hostname.
/// <para>
/// IP addresses found are returned in <see cref="IPHostEntry.AddressList"/>.
/// <see cref="ResourceRecordType.CNAME"/> records are used to populate the <see cref="IPHostEntry.Aliases"/>.<br/>
/// The <see cref="IPHostEntry.HostName"/> property will be set to the resolved hostname of the <paramref name="address"/>.
/// </para>
/// </summary>
/// <example>
/// The following code example uses the <see cref="GetHostEntry(IDnsQuery, IPAddress)"/> method to resolve an IP address to an <see cref="IPHostEntry"/> instance.
/// <code>
/// <![CDATA[
/// public static void PrintHostEntry(IPAddress address)
/// {
/// var lookup = new LookupClient();
/// IPHostEntry hostEntry = lookup.GetHostEntry(address);
/// Console.WriteLine(hostEntry.HostName);
/// foreach (var ip in hostEntry.AddressList)
/// {
/// Console.WriteLine(ip);
/// }
/// foreach (var alias in hostEntry.Aliases)
/// {
/// Console.WriteLine(alias);
/// }
/// }
/// ]]>
/// </code>
/// </example>
/// <remarks>
/// The method has some logic to populate the <see cref="IPHostEntry.Aliases"/> list:
/// <list type="bullet">
/// <item>
/// <term>
/// In case of sub-domain queries or similar, there might be multiple <see cref="ResourceRecordType.CNAME"/> records for one <see cref="IPAddress"/>,
/// </term>
/// </item><item>
/// <term>
/// If only one <see cref="IPAddress"/> is in the result set, all the aliases found will be returned.
/// </term>
/// </item><item>
/// <term>
/// If more than one <see cref="IPAddress"/> is in the result set, aliases are returned only if at least one doesn't match the queried hostname.
/// </term>
/// </item>
/// </list>
/// </remarks>
/// <param name="query">The <see cref="IDnsQuery"/> instance.</param>
/// <param name="address">The <see cref="IPAddress"/> to query for.</param>
/// <returns>
/// An <see cref="IPHostEntry"/> instance that contains address information about the host specified in <paramref name="address"/>.
/// In case the <paramref name="address"/> could not be resolved to a domain name, this method returns <c>null</c>,
/// unless <see cref="DnsQueryOptions.ThrowDnsErrors"/> is set to true, then it might throw a <see cref="DnsResponseException"/>.
/// </returns>
/// <exception cref="ArgumentNullException">If <paramref name="address"/> is null.</exception>
/// <exception cref="DnsResponseException">In case <see cref="DnsQueryOptions.ThrowDnsErrors"/> is set to true and a DNS error occurs.</exception>
public static IPHostEntry GetHostEntry(this IDnsQuery query, IPAddress address)
{
if (query == null)
{
throw new ArgumentNullException(nameof(query));
}
if (address == null)
{
throw new ArgumentNullException(nameof(address));
}
var hostName = query.GetHostName(address);
if (string.IsNullOrWhiteSpace(hostName))
{
return null;
}
return GetHostEntryFromName(query, hostName);
}
/// <summary>
/// The <c>GetHostEntryAsync</c> method does a reverse lookup on the IP <paramref name="address"/>,
/// and queries a DNS server for the IP addresses and aliases associated with the resolved hostname.
/// <para>
/// IP addresses found are returned in <see cref="IPHostEntry.AddressList"/>.
/// <see cref="ResourceRecordType.CNAME"/> records are used to populate the <see cref="IPHostEntry.Aliases"/>.<br/>
/// The <see cref="IPHostEntry.HostName"/> property will be set to the resolved hostname of the <paramref name="address"/>.
/// </para>
/// </summary>
/// <example>
/// The following code example uses the <see cref="GetHostEntryAsync(IDnsQuery, IPAddress)"/> method to resolve an IP address to an <see cref="IPHostEntry"/> instance.
/// <code>
/// <![CDATA[
/// public static async Task PrintHostEntry(IPAddress address)
/// {
/// var lookup = new LookupClient();
/// IPHostEntry hostEntry = await lookup.GetHostEntryAsync(address);
/// Console.WriteLine(hostEntry.HostName);
/// foreach (var ip in hostEntry.AddressList)
/// {
/// Console.WriteLine(ip);
/// }
/// foreach (var alias in hostEntry.Aliases)
/// {
/// Console.WriteLine(alias);
/// }
/// }
/// ]]>
/// </code>
/// </example>
/// <remarks>
/// The method has some logic to populate the <see cref="IPHostEntry.Aliases"/> list:
/// <list type="bullet">
/// <item>
/// <term>
/// In case of sub-domain queries or similar, there might be multiple <see cref="ResourceRecordType.CNAME"/> records for one <see cref="IPAddress"/>,
/// </term>
/// </item><item>
/// <term>
/// If only one <see cref="IPAddress"/> is in the result set, all the aliases found will be returned.
/// </term>
/// </item><item>
/// <term>
/// If more than one <see cref="IPAddress"/> is in the result set, aliases are returned only if at least one doesn't match the queried hostname.
/// </term>
/// </item>
/// </list>
/// </remarks>
/// <param name="query">The <see cref="IDnsQuery"/> instance.</param>
/// <param name="address">The <see cref="IPAddress"/> to query for.</param>
/// <returns>
/// An <see cref="IPHostEntry"/> instance that contains address information about the host specified in <paramref name="address"/>.
/// In case the <paramref name="address"/> could not be resolved to a domain name, this method returns <c>null</c>,
/// unless <see cref="DnsQueryOptions.ThrowDnsErrors"/> is set to true, then it might throw a <see cref="DnsResponseException"/>.
/// </returns>
/// <exception cref="ArgumentNullException">If <paramref name="address"/> is null.</exception>
/// <exception cref="DnsResponseException">In case <see cref="DnsQueryOptions.ThrowDnsErrors"/> is set to true and a DNS error occurs.</exception>
public static async Task<IPHostEntry> GetHostEntryAsync(this IDnsQuery query, IPAddress address)
{
if (query == null)
{
throw new ArgumentNullException(nameof(query));
}
if (address == null)
{
throw new ArgumentNullException(nameof(address));
}
var hostName = await query.GetHostNameAsync(address).ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(hostName))
{
return null;
}
return await GetHostEntryFromNameAsync(query, hostName).ConfigureAwait(false);
}
private static IPHostEntry GetHostEntryFromName(IDnsQuery query, string hostName)
{
if (string.IsNullOrWhiteSpace(hostName))
{
throw new ArgumentNullException(nameof(hostName));
}
var hostString = DnsString.FromResponseQueryString(hostName);
var ipv4Result = query.Query(hostString, QueryType.A);
var ipv6Result = query.Query(hostString, QueryType.AAAA);
var allRecords = ipv4Result
.Answers.Concat(ipv6Result.Answers)
.ToArray();
return GetHostEntryProcessResult(hostString, allRecords);
}
private static async Task<IPHostEntry> GetHostEntryFromNameAsync(IDnsQuery query, string hostName)
{
if (string.IsNullOrWhiteSpace(hostName))
{
throw new ArgumentNullException(nameof(hostName));
}
var hostString = DnsString.FromResponseQueryString(hostName);
var ipv4Result = query.QueryAsync(hostString, QueryType.A);
var ipv6Result = query.QueryAsync(hostString, QueryType.AAAA);
await Task.WhenAll(ipv4Result, ipv6Result).ConfigureAwait(false);
#pragma warning disable CA1849 // We did.
var allRecords = ipv4Result.Result
.Answers.Concat(ipv6Result.Result.Answers)
.ToArray();
#pragma warning restore CA1849 // Call async methods when in an async method
return GetHostEntryProcessResult(hostString, allRecords);
}
private static IPHostEntry GetHostEntryProcessResult(DnsString hostString, DnsResourceRecord[] allRecords)
{
var addressRecords = allRecords
.OfType<AddressRecord>()
.Select(p => new
{
p.Address,
Alias = DnsString.FromResponseQueryString(p.DomainName)
})
.ToArray();
var hostEntry = new IPHostEntry()
{
Aliases = new string[0],
AddressList = addressRecords
.Select(p => p.Address)
.ToArray()
};
if (addressRecords.Length > 1)
{
if (addressRecords.Any(p => !p.Alias.Equals(hostString)))
{
hostEntry.Aliases = addressRecords
.Select(p => p.Alias.ToString())
.Select(p => p.Substring(0, p.Length - 1))
.Distinct()
.ToArray();
}
}
else if (addressRecords.Length == 1)
{
if (allRecords.Any(p => !DnsString.FromResponseQueryString(p.DomainName).Equals(hostString)))
{
hostEntry.Aliases = allRecords
.Select(p => p.DomainName.ToString())
.Select(p => p.Substring(0, p.Length - 1))
.Distinct()
.ToArray();
}
}
hostEntry.HostName = hostString.Value.Substring(0, hostString.Value.Length - 1);
return hostEntry;
}
/// <summary>
/// The <c>GetHostName</c> method queries a DNS server to resolve the hostname of the <paramref name="address"/> via reverse lookup.
/// </summary>
/// <param name="query">The <see cref="IDnsQuery"/> instance.</param>
/// <param name="address">The <see cref="IPAddress"/> to resolve.</param>
/// <returns>
/// The hostname if the reverse lookup was successful or <c>null</c>, in case the host was not found.
/// If <see cref="DnsQueryOptions.ThrowDnsErrors"/> is set to <c>true</c>, this method will throw an <see cref="DnsResponseException"/> instead of returning <c>null</c>!
/// </returns>
/// <exception cref="ArgumentNullException">If <paramref name="address"/>is null.</exception>
/// <exception cref="DnsResponseException">If no host has been found and <see cref="DnsQueryOptions.ThrowDnsErrors"/> is <c>true</c>.</exception>
public static string GetHostName(this IDnsQuery query, IPAddress address)
{
if (query == null)
{
throw new ArgumentNullException(nameof(query));
}
if (address == null)
{
throw new ArgumentNullException(nameof(address));
}
var result = query.QueryReverse(address);
return GetHostNameAsyncProcessResult(result);
}
/// <summary>
/// The <c>GetHostNameAsync</c> method queries a DNS server to resolve the hostname of the <paramref name="address"/> via reverse lookup.
/// </summary>
/// <param name="query">The <see cref="IDnsQuery"/> instance.</param>
/// <param name="address">The <see cref="IPAddress"/> to resolve.</param>
/// <returns>
/// The hostname if the reverse lookup was successful or <c>null</c>, in case the host was not found.
/// If <see cref="DnsQueryOptions.ThrowDnsErrors"/> is set to <c>true</c>, this method will throw an <see cref="DnsResponseException"/> instead of returning <c>null</c>!
/// </returns>
/// <exception cref="ArgumentNullException">If <paramref name="address"/>is null.</exception>
/// <exception cref="DnsResponseException">If no host has been found and <see cref="DnsQueryOptions.ThrowDnsErrors"/> is <c>true</c>.</exception>
public static async Task<string> GetHostNameAsync(this IDnsQuery query, IPAddress address)
{
if (query == null)
{
throw new ArgumentNullException(nameof(query));
}
if (address == null)
{
throw new ArgumentNullException(nameof(address));
}
var result = await query.QueryReverseAsync(address).ConfigureAwait(false);
return GetHostNameAsyncProcessResult(result);
}
private static string GetHostNameAsyncProcessResult(IDnsQueryResponse result)
{
if (result.HasError)
{
return null;
}
var hostName = result.Answers.PtrRecords().FirstOrDefault()?.PtrDomainName;
if (string.IsNullOrWhiteSpace(hostName))
{
return null;
}
// removing the . at the end
return hostName.Value.Substring(0, hostName.Value.Length - 1);
}
/// <summary>
/// The <c>ResolveService</c> method does a <see cref="QueryType.SRV"/> lookup for <c>_{<paramref name="serviceName"/>}[._{<paramref name="protocol"/>}].{<paramref name="baseDomain"/>}</c>
/// and aggregates the result (hostname, port and list of <see cref="IPAddress"/>s) to a <see cref="ServiceHostEntry"/>.
/// <para>
/// This method expects matching A or AAAA records to populate the <see cref="IPHostEntry.AddressList"/>,
/// and/or a <see cref="ResourceRecordType.CNAME"/> record to populate the <see cref="IPHostEntry.HostName"/> property of the result.
/// </para>
/// </summary>
/// <remarks>
/// The returned list of <see cref="IPAddress"/>s and/or the hostname can be empty if no matching additional records are found.
/// </remarks>
/// <param name="query">The <see cref="IDnsQuery"/> instance.</param>
/// <param name="baseDomain">The base domain, which will be appended to the end of the query string.</param>
/// <param name="serviceName">The name of the service to look for. Must not have any <c>_</c> prefix.</param>
/// <param name="protocol">
/// The protocol of the service to query for.
/// Set it to <see cref="ProtocolType.Unknown"/> or <see cref="ProtocolType.Unspecified"/> to not pass any protocol.
/// </param>
/// <returns>A collection of <see cref="ServiceHostEntry"/>s.</returns>
/// <exception cref="ArgumentNullException">If <paramref name="baseDomain"/> or <paramref name="serviceName"/> are null.</exception>
/// <seealso href="https://tools.ietf.org/html/rfc2782">RFC 2782</seealso>
public static ServiceHostEntry[] ResolveService(this IDnsQuery query, string baseDomain, string serviceName, ProtocolType protocol)
{
if (protocol == ProtocolType.Unspecified || protocol == ProtocolType.Unknown)
{
return ResolveService(query, baseDomain, serviceName, null);
}
return ResolveService(query, baseDomain, serviceName, protocol.ToString());
}
/// <summary>
/// The <c>ResolveServiceAsync</c> method does a <see cref="QueryType.SRV"/> lookup for <c>_{<paramref name="serviceName"/>}[._{<paramref name="protocol"/>}].{<paramref name="baseDomain"/>}</c>
/// and aggregates the result (hostname, port and list of <see cref="IPAddress"/>s) to a <see cref="ServiceHostEntry"/>.
/// <para>
/// This method expects matching A or AAAA records to populate the <see cref="IPHostEntry.AddressList"/>,
/// and/or a <see cref="ResourceRecordType.CNAME"/> record to populate the <see cref="IPHostEntry.HostName"/> property of the result.
/// </para>
/// </summary>
/// <remarks>
/// The returned list of <see cref="IPAddress"/>s and/or the hostname can be empty if no matching additional records are found.
/// </remarks>
/// <param name="query">The <see cref="IDnsQuery"/> instance.</param>
/// <param name="baseDomain">The base domain, which will be appended to the end of the query string.</param>
/// <param name="serviceName">The name of the service to look for. Must not have any <c>_</c> prefix.</param>
/// <param name="protocol">
/// The protocol of the service to query for.
/// Set it to <see cref="ProtocolType.Unknown"/> or <see cref="ProtocolType.Unspecified"/> to not pass any protocol.
/// </param>
/// <returns>A collection of <see cref="ServiceHostEntry"/>s.</returns>
/// <exception cref="ArgumentNullException">If <paramref name="baseDomain"/> or <paramref name="serviceName"/> are null.</exception>
/// <seealso href="https://tools.ietf.org/html/rfc2782">RFC 2782</seealso>
public static Task<ServiceHostEntry[]> ResolveServiceAsync(this IDnsQuery query, string baseDomain, string serviceName, ProtocolType protocol)
{
if (protocol == ProtocolType.Unspecified || protocol == ProtocolType.Unknown)
{
return ResolveServiceAsync(query, baseDomain, serviceName, null);
}
return ResolveServiceAsync(query, baseDomain, serviceName, protocol.ToString());
}
/// <summary>
/// The <c>ResolveService</c> method does a <see cref="QueryType.SRV"/> lookup for <c>_{<paramref name="serviceName"/>}[._{<paramref name="tag"/>}].{<paramref name="baseDomain"/>}</c>
/// and aggregates the result (hostname, port and list of <see cref="IPAddress"/>s) to a <see cref="ServiceHostEntry"/>.
/// <para>
/// This method expects matching A or AAAA records to populate the <see cref="IPHostEntry.AddressList"/>,
/// and/or a <see cref="ResourceRecordType.CNAME"/> record to populate the <see cref="IPHostEntry.HostName"/> property of the result.
/// </para>
/// </summary>
/// <remarks>
/// The returned list of <see cref="IPAddress"/>s and/or the hostname can be empty if no matching additional records are found.
/// </remarks>
/// <param name="query">The <see cref="IDnsQuery"/> instance.</param>
/// <param name="baseDomain">The base domain, which will be appended to the end of the query string.</param>
/// <param name="serviceName">The name of the service to look for. Must not have any <c>_</c> prefix.</param>
/// <param name="tag">An optional tag. Must not have any <c>_</c> prefix.</param>
/// <returns>A collection of <see cref="ServiceHostEntry"/>s.</returns>
/// <exception cref="ArgumentNullException">If <paramref name="baseDomain"/> or <paramref name="serviceName"/> are null.</exception>
/// <seealso href="https://tools.ietf.org/html/rfc2782">RFC 2782</seealso>
public static ServiceHostEntry[] ResolveService(this IDnsQuery query, string baseDomain, string serviceName, string tag = null)
{
if (query == null)
{
throw new ArgumentNullException(nameof(query));
}
if (baseDomain == null)
{
throw new ArgumentNullException(nameof(baseDomain));
}
if (string.IsNullOrWhiteSpace(serviceName))
{
throw new ArgumentNullException(nameof(serviceName));
}
var queryString = ConcatServiceName(baseDomain, serviceName, tag);
var result = query.Query(queryString, QueryType.SRV);
return ResolveServiceProcessResult(result);
}
/// <summary>
/// The <c>ResolveService</c> method does a <see cref="QueryType.SRV"/> lookup for <c>{<paramref name="service"/>}</c>
/// and aggregates the result (hostname, port and list of <see cref="IPAddress"/>s) to a <see cref="ServiceHostEntry"/>.
/// <para>
/// This method expects matching A or AAAA records to populate the <see cref="IPHostEntry.AddressList"/>,
/// and/or a <see cref="ResourceRecordType.CNAME"/> record to populate the <see cref="IPHostEntry.HostName"/> property of the result.
/// </para>
/// </summary>
/// <remarks>
/// The returned list of <see cref="IPAddress"/>s and/or the hostname can be empty if no matching additional records are found.
/// </remarks>
/// <param name="query">The <see cref="IDnsQuery"/> instance.</param>
/// <param name="service">The name of the service to look for. Must have <c>_</c> prefix and domain and protocol.</param>
/// <returns>A collection of <see cref="ServiceHostEntry"/>s.</returns>
/// <exception cref="ArgumentNullException">If <paramref name="service"/> are null.</exception>
/// <seealso href="https://tools.ietf.org/html/rfc2782">RFC 2782</seealso>
public static ServiceHostEntry[] ResolveService(this IDnsQuery query, string service)
{
if (query == null)
{
throw new ArgumentNullException(nameof(query));
}
if (string.IsNullOrWhiteSpace(service))
{
throw new ArgumentNullException(nameof(service));
}
var result = query.Query(service, QueryType.SRV);
return ResolveServiceProcessResult(result);
}
/// <summary>
/// The <c>ResolveServiceAsync</c> method does a <see cref="QueryType.SRV"/> lookup for <c>_{<paramref name="serviceName"/>}[._{<paramref name="tag"/>}].{<paramref name="baseDomain"/>}</c>
/// and aggregates the result (hostname, port and list of <see cref="IPAddress"/>s) to a <see cref="ServiceHostEntry"/>.
/// <para>
/// This method expects matching A or AAAA records to populate the <see cref="IPHostEntry.AddressList"/>,
/// and/or a <see cref="ResourceRecordType.CNAME"/> record to populate the <see cref="IPHostEntry.HostName"/> property of the result.
/// </para>
/// </summary>
/// <remarks>
/// The returned list of <see cref="IPAddress"/>s and/or the hostname can be empty if no matching additional records are found.
/// </remarks>
/// <param name="query">The <see cref="IDnsQuery"/> instance.</param>
/// <param name="baseDomain">The base domain, which will be appended to the end of the query string.</param>
/// <param name="serviceName">The name of the service to look for. Must not have any <c>_</c> prefix.</param>
/// <param name="tag">An optional tag. Must not have any <c>_</c> prefix.</param>
/// <returns>A collection of <see cref="ServiceHostEntry"/>s.</returns>
/// <exception cref="ArgumentNullException">If <paramref name="baseDomain"/> or <paramref name="serviceName"/> are null.</exception>
/// <seealso href="https://tools.ietf.org/html/rfc2782">RFC 2782</seealso>
public static async Task<ServiceHostEntry[]> ResolveServiceAsync(this IDnsQuery query, string baseDomain, string serviceName, string tag = null)
{
if (query == null)
{
throw new ArgumentNullException(nameof(query));
}
if (baseDomain == null)
{
throw new ArgumentNullException(nameof(baseDomain));
}
if (string.IsNullOrWhiteSpace(serviceName))
{
throw new ArgumentNullException(nameof(serviceName));
}
var queryString = ConcatServiceName(baseDomain, serviceName, tag);
var result = await query.QueryAsync(queryString, QueryType.SRV).ConfigureAwait(false);
return ResolveServiceProcessResult(result);
}
/// <summary>
/// The <c>ResolveServiceAsync</c> method does a <see cref="QueryType.SRV"/> lookup for <c>{<paramref name="service"/>}</c>
/// and aggregates the result (hostname, port and list of <see cref="IPAddress"/>s) to a <see cref="ServiceHostEntry"/>.
/// <para>
/// This method expects matching A or AAAA records to populate the <see cref="IPHostEntry.AddressList"/>,
/// and/or a <see cref="ResourceRecordType.CNAME"/> record to populate the <see cref="IPHostEntry.HostName"/> property of the result.
/// </para>
/// </summary>
/// <remarks>
/// The returned list of <see cref="IPAddress"/>s and/or the hostname can be empty if no matching additional records are found.
/// </remarks>
/// <param name="query">The <see cref="IDnsQuery"/> instance.</param>
/// <param name="service">The name of the service to look for. Must have <c>_</c> prefix and domain and protocol.</param>
/// <returns>A collection of <see cref="ServiceHostEntry"/>s.</returns>
/// <exception cref="ArgumentNullException">If <paramref name="service"/> are null.</exception>
/// <seealso href="https://tools.ietf.org/html/rfc2782">RFC 2782</seealso>
public static async Task<ServiceHostEntry[]> ResolveServiceAsync(this IDnsQuery query, string service)
{
if (query == null)
{
throw new ArgumentNullException(nameof(query));
}
if (string.IsNullOrWhiteSpace(service))
{
throw new ArgumentNullException(nameof(service));
}
var result = await query.QueryAsync(service, QueryType.SRV).ConfigureAwait(false);
return ResolveServiceProcessResult(result);
}
/// <summary>
/// Constructs a DNS <see cref="QueryType.SRV"/> query string from the constituent parts.
/// </summary>
/// <param name="baseDomain">The base domain, which will be appended to the end of the query string.</param>
/// <param name="serviceName">The name of the service to look for. Must not have any <c>_</c> prefix.</param>
/// <param name="tag">An optional tag. Must not have any <c>_</c> prefix.</param>
/// <returns>A service string that can be used in a DNS service query.</returns>
public static string ConcatServiceName(string baseDomain, string serviceName, string tag = null)
{
return string.IsNullOrWhiteSpace(tag) ?
$"{serviceName}.{baseDomain}." :
$"_{serviceName}._{tag}.{baseDomain}.";
}
/// <summary>
/// Transforms a DNS query result into a collection of <see cref="ServiceHostEntry"/> objects.
/// </summary>
/// <param name="result">The DNS </param>
/// <returns>A collection of <see cref="ServiceHostEntry"/>s.</returns>
public static ServiceHostEntry[] ResolveServiceProcessResult(IDnsQueryResponse result)
{
var hosts = new List<ServiceHostEntry>();
if (result == null || result.HasError)
{
return hosts.ToArray();
}
foreach (var entry in result.Answers.SrvRecords())
{
var addresses = result.Additionals
.OfType<AddressRecord>()
.Where(p => p.DomainName.Equals(entry.Target))
.Select(p => p.Address);
var hostName = result.Additionals
.OfType<CNameRecord>()
.Where(p => p.DomainName.Equals(entry.Target))
.Select(p => p.CanonicalName).FirstOrDefault()
?? entry.Target;
hosts.Add(new ServiceHostEntry()
{
AddressList = addresses.ToArray(),
HostName = hostName,
Port = entry.Port,
Priority = entry.Priority,
Weight = entry.Weight,
});
}
return hosts.ToArray();
}
}
/// <summary>
/// Extends <see cref="IPHostEntry"/> by the <see cref="Port"/> property.
/// </summary>
/// <seealso cref="IPHostEntry" />
public class ServiceHostEntry : IPHostEntry
{
/// <summary>
/// Gets or sets the port.
/// </summary>
/// <value>
/// The port of this entry.
/// </value>
public int Port { get; set; }
/// <summary>
/// Gets or sets priority of the original <see cref="ResourceRecordType.SRV"/> record.
/// Might be zero if not provided.
/// </summary>
/// <value>
/// The priority of this entry.
/// </value>
public int Priority { get; set; }
/// <summary>
/// Gets or sets weight of the original <see cref="ResourceRecordType.SRV"/> record.
/// Might be zero if not provided.
/// </summary>
/// <value>
/// The weight of this entry.
/// </value>
public int Weight { get; set; }
}
}