|
1 | | -using System.Threading.Tasks; |
| 1 | +using System.Linq; |
| 2 | +using System.Net.NetworkInformation; |
| 3 | +using System.Threading.Tasks; |
2 | 4 |
|
3 | 5 | namespace NETworkManager.Utilities; |
4 | 6 |
|
5 | 7 | public static class DNSClientHelper |
6 | 8 | { |
| 9 | + /// <summary> |
| 10 | + /// Detect the DNS suffix to use for suffix-appending. Prefers the Windows "Primary DNS Suffix" |
| 11 | + /// (<see cref="IPGlobalProperties.DomainName" />), falling back to the connection-specific suffix |
| 12 | + /// of an active network adapter if no primary suffix is configured (e.g. machine is not domain-joined |
| 13 | + /// or the primary suffix was cleared manually), which mirrors what shows up under "DNS Suffix Search |
| 14 | + /// List" in <c>ipconfig /all</c> in that case. |
| 15 | + /// </summary> |
| 16 | + public static string DetectDNSSuffix() |
| 17 | + { |
| 18 | + var suffix = IPGlobalProperties.GetIPGlobalProperties().DomainName; |
| 19 | + |
| 20 | + if (!string.IsNullOrWhiteSpace(suffix)) |
| 21 | + return suffix; |
| 22 | + |
| 23 | + // Rank candidates so the adapter most likely to be "the" active connection is tried first: |
| 24 | + // routed (has a gateway) > wired > wireless > other > faster link speed. |
| 25 | + var prioritizedAdapters = NetworkInterface.GetAllNetworkInterfaces() |
| 26 | + .Where(nic => nic.OperationalStatus == OperationalStatus.Up && |
| 27 | + nic.NetworkInterfaceType != NetworkInterfaceType.Loopback && |
| 28 | + nic.NetworkInterfaceType != NetworkInterfaceType.Tunnel) |
| 29 | + .OrderByDescending(nic => nic.GetIPProperties().GatewayAddresses.Count > 0) |
| 30 | + .ThenByDescending(nic => GetInterfaceTypePriority(nic.NetworkInterfaceType)) |
| 31 | + .ThenByDescending(nic => nic.Speed); |
| 32 | + |
| 33 | + return prioritizedAdapters |
| 34 | + .Select(nic => nic.GetIPProperties().DnsSuffix) |
| 35 | + .FirstOrDefault(s => !string.IsNullOrWhiteSpace(s)) |
| 36 | + ?? string.Empty; |
| 37 | + } |
| 38 | + |
| 39 | + private static int GetInterfaceTypePriority(NetworkInterfaceType type) => type switch |
| 40 | + { |
| 41 | + NetworkInterfaceType.Ethernet => 2, |
| 42 | + NetworkInterfaceType.Wireless80211 => 1, |
| 43 | + _ => 0 |
| 44 | + }; |
| 45 | + |
7 | 46 | public static async Task<DNSClientResultIPAddress> ResolveAorAaaaAsync(string query, bool preferIPv4) |
8 | 47 | { |
9 | 48 | DNSClientResultIPAddress firstResult = null; |
|
0 commit comments