-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Expand file tree
/
Copy pathGetHostEntryTest.cs
More file actions
557 lines (482 loc) · 27.6 KB
/
GetHostEntryTest.cs
File metadata and controls
557 lines (482 loc) · 27.6 KB
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.DotNet.RemoteExecutor;
using Microsoft.DotNet.XUnitExtensions;
using Xunit;
namespace System.Net.NameResolution.Tests
{
public class GetHostEntryTest
{
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsMultithreadingSupported))]
public async Task Dns_GetHostEntryAsync_IPAddress_Ok()
{
IPAddress localIPAddress = await TestSettings.GetLocalIPAddress();
await TestGetHostEntryAsync(() => Dns.GetHostEntryAsync(localIPAddress));
}
public static bool GetHostEntryWorks =
// [ActiveIssue("https://github.com/dotnet/runtime/issues/27622")]
PlatformDetection.IsNotArmNorArm64Process &&
// [ActiveIssue("https://github.com/dotnet/runtime/issues/1488", TestPlatforms.OSX)]
!PlatformDetection.IsOSX &&
// [ActiveIssue("https://github.com/dotnet/runtime/issues/51377", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)]
!PlatformDetection.IsiOS && !PlatformDetection.IstvOS && !PlatformDetection.IsMacCatalyst;
[ConditionalTheory(typeof(GetHostEntryTest), nameof(GetHostEntryWorks))]
[InlineData("")]
[InlineData(TestSettings.LocalHost)]
public async Task Dns_GetHostEntry_HostString_Ok(string hostName)
{
try
{
await TestGetHostEntryAsync(() => Task.FromResult(Dns.GetHostEntry(hostName)));
}
catch (Exception ex) when (hostName == "")
{
// Additional data for debugging sporadic CI failures https://github.com/dotnet/runtime/issues/1488
string actualHostName = Dns.GetHostName();
string etcHosts = "";
Exception getHostEntryException = null;
Exception etcHostsException = null;
try
{
Dns.GetHostEntry(actualHostName);
}
catch (Exception e2)
{
getHostEntryException = e2;
}
try
{
if (Environment.OSVersion.Platform != PlatformID.Win32NT)
{
etcHosts = File.ReadAllText("/etc/hosts");
}
}
catch (Exception e2)
{
etcHostsException = e2;
}
throw new Exception(
$"Failed for empty hostname.{Environment.NewLine}" +
$"Dns.GetHostName() == {actualHostName}{Environment.NewLine}" +
$"{nameof(getHostEntryException)}=={getHostEntryException}{Environment.NewLine}" +
$"{nameof(etcHostsException)}=={etcHostsException}{Environment.NewLine}" +
$"/etc/host =={Environment.NewLine}{etcHosts}",
ex);
}
}
[ConditionalTheory(typeof(GetHostEntryTest), nameof(GetHostEntryWorks))]
[InlineData("")]
[InlineData(TestSettings.LocalHost)]
public async Task Dns_GetHostEntryAsync_HostString_Ok(string hostName)
{
await TestGetHostEntryAsync(() => Dns.GetHostEntryAsync(hostName));
}
[Fact]
public async Task Dns_GetHostEntryAsync_IPString_Ok() =>
await TestGetHostEntryAsync(() => Dns.GetHostEntryAsync(TestSettings.LocalIPString));
private static async Task TestGetHostEntryAsync(Func<Task<IPHostEntry>> getHostEntryFunc)
{
Task<IPHostEntry> hostEntryTask1 = getHostEntryFunc();
Task<IPHostEntry> hostEntryTask2 = getHostEntryFunc();
await TestSettings.WhenAllOrAnyFailedWithTimeout(hostEntryTask1, hostEntryTask2);
IPAddress[] list1 = hostEntryTask1.Result.AddressList;
IPAddress[] list2 = hostEntryTask2.Result.AddressList;
Assert.NotNull(list1);
Assert.NotNull(list2);
Assert.Equal<IPAddress>(list1, list2);
}
public static bool GetHostEntry_DisableIPv6_Condition = GetHostEntryWorks && RemoteExecutor.IsSupported;
[ConditionalTheory(typeof(GetHostEntryTest), nameof(GetHostEntry_DisableIPv6_Condition))]
[InlineData("", false)]
[InlineData("", true)]
[InlineData(TestSettings.LocalHost, false)]
[InlineData(TestSettings.LocalHost, true)]
public void GetHostEntry_DisableIPv6_ExcludesIPv6Addresses(string hostnameOuter, bool useAsyncOuter)
{
string expectedHostName = Dns.GetHostEntry(hostnameOuter).HostName;
RemoteExecutor.Invoke(RunTest, hostnameOuter, expectedHostName, useAsyncOuter.ToString()).Dispose();
static async Task RunTest(string hostnameInner, string expectedHostName, string useAsync)
{
AppContext.SetSwitch("System.Net.DisableIPv6", true);
IPHostEntry entry = bool.Parse(useAsync) ?
await Dns.GetHostEntryAsync(hostnameInner) :
Dns.GetHostEntry(hostnameInner);
Assert.Equal(entry.HostName, expectedHostName);
Assert.All(entry.AddressList, address => Assert.Equal(AddressFamily.InterNetwork, address.AddressFamily));
}
}
[ConditionalTheory(typeof(GetHostEntryTest), nameof(GetHostEntry_DisableIPv6_Condition))]
[InlineData(false)]
[InlineData(true)]
public void GetHostEntry_DisableIPv6_AddressFamilyInterNetworkV6_ReturnsEmpty(bool useAsyncOuter)
{
RemoteExecutor.Invoke(RunTest, useAsyncOuter.ToString()).Dispose();
static async Task RunTest(string useAsync)
{
AppContext.SetSwitch("System.Net.DisableIPv6", true);
IPHostEntry entry = bool.Parse(useAsync) ?
await Dns.GetHostEntryAsync(TestSettings.LocalHost, AddressFamily.InterNetworkV6) :
Dns.GetHostEntry(TestSettings.LocalHost, AddressFamily.InterNetworkV6);
Assert.Empty(entry.AddressList);
}
}
[Fact]
public async Task Dns_GetHostEntry_NullStringHost_Fail()
{
Assert.Throws<ArgumentNullException>(() => Dns.GetHostEntry((string)null));
await Assert.ThrowsAsync<ArgumentNullException>(() => Dns.GetHostEntryAsync((string)null));
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsMultithreadingSupported))]
public async Task Dns_GetHostEntry_NullStringHost_Fail_Obsolete()
{
await Assert.ThrowsAsync<ArgumentNullException>(() => Task.Factory.FromAsync(Dns.BeginGetHostEntry, Dns.EndGetHostEntry, (string)null, null));
}
[Fact]
[SkipOnPlatform(TestPlatforms.Wasi, "WASI has no getnameinfo")]
public async Task Dns_GetHostEntryAsync_NullIPAddressHost_Fail()
{
Assert.Throws<ArgumentNullException>(() => Dns.GetHostEntry((IPAddress)null));
await Assert.ThrowsAsync<ArgumentNullException>(() => Dns.GetHostEntryAsync((IPAddress)null));
await Assert.ThrowsAsync<ArgumentNullException>(() => Task.Factory.FromAsync(Dns.BeginGetHostEntry, Dns.EndGetHostEntry, (IPAddress)null, null));
}
public static IEnumerable<object[]> GetInvalidAddresses()
{
yield return new object[] { IPAddress.Any };
yield return new object[] { IPAddress.IPv6Any };
yield return new object[] { IPAddress.IPv6None };
}
[Theory]
[MemberData(nameof(GetInvalidAddresses))]
[SkipOnPlatform(TestPlatforms.Wasi, "WASI has no getnameinfo")]
public async Task Dns_GetHostEntry_AnyIPAddress_Fail(IPAddress address)
{
Assert.Throws<ArgumentException>(() => Dns.GetHostEntry(address));
Assert.Throws<ArgumentException>(() => Dns.GetHostEntry(address.ToString()));
await Assert.ThrowsAsync<ArgumentException>(() => Dns.GetHostEntryAsync(address));
await Assert.ThrowsAsync<ArgumentException>(() => Dns.GetHostEntryAsync(address.ToString()));
await Assert.ThrowsAsync<ArgumentException>(() => Task.Factory.FromAsync(Dns.BeginGetHostEntry, Dns.EndGetHostEntry, address, null));
await Assert.ThrowsAsync<ArgumentException>(() => Task.Factory.FromAsync(Dns.BeginGetHostEntry, Dns.EndGetHostEntry, address.ToString(), null));
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsMultithreadingSupported))]
public async Task DnsGetHostEntry_MachineName_AllVariationsMatch()
{
IPHostEntry syncResult = Dns.GetHostEntry(TestSettings.LocalHost);
IPHostEntry apmResult = Dns.EndGetHostEntry(Dns.BeginGetHostEntry(TestSettings.LocalHost, null, null));
IPHostEntry asyncResult = await Dns.GetHostEntryAsync(TestSettings.LocalHost);
Assert.Equal(syncResult.HostName, apmResult.HostName);
Assert.Equal(syncResult.HostName, asyncResult.HostName);
Assert.Equal(syncResult.AddressList, apmResult.AddressList);
Assert.Equal(syncResult.AddressList, asyncResult.AddressList);
}
[Fact]
[SkipOnPlatform(TestPlatforms.Wasi, "WASI has no getnameinfo")]
public async Task DnsGetHostEntry_Loopback_AllVariationsMatch()
{
IPHostEntry syncResult = Dns.GetHostEntry(IPAddress.Loopback);
IPHostEntry apmResult = Dns.EndGetHostEntry(Dns.BeginGetHostEntry(IPAddress.Loopback, null, null));
IPHostEntry asyncResult = await Dns.GetHostEntryAsync(IPAddress.Loopback);
Assert.Equal(syncResult.HostName, apmResult.HostName);
Assert.Equal(syncResult.HostName, asyncResult.HostName);
Assert.Equal(syncResult.AddressList, apmResult.AddressList);
Assert.Equal(syncResult.AddressList, asyncResult.AddressList);
}
[Theory]
[InlineData("BadName")] // unknown name
[InlineData("0.0.1.1")] // unknown address
[InlineData("Test-\u65B0-Unicode")] // unknown unicode name
[InlineData("xn--test--unicode-0b01a")] // unknown punicode name
[InlineData("Really.Long.Name.Over.One.Hundred.And.Twenty.Six.Chars.Eeeeeeeventualllllllly.I.Will.Get.To.The.Eeeee"
+ "eeeeend.Almost.There.Are.We.Really.Long.Name.Over.One.Hundred.And.Twenty.Six.Chars.Eeeeeeeventualll"
+ "llllly.I.Will.Get.To.The.Eeeeeeeeeend.Almost.There.Are")] // very long name but not too long
[ActiveIssue("https://github.com/dotnet/runtime/issues/107339", TestPlatforms.Wasi)]
public async Task DnsGetHostEntry_BadName_ThrowsSocketException(string hostNameOrAddress)
{
Assert.ThrowsAny<SocketException>(() => Dns.GetHostEntry(hostNameOrAddress));
await Assert.ThrowsAnyAsync<SocketException>(() => Dns.GetHostEntryAsync(hostNameOrAddress));
await Assert.ThrowsAnyAsync<SocketException>(() => Task.Factory.FromAsync(Dns.BeginGetHostEntry, Dns.EndGetHostEntry, hostNameOrAddress, null));
}
[Theory]
[InlineData("Really.Long.Name.Over.One.Hundred.And.Twenty.Six.Chars.Eeeeeeeventualllllllly.I.Will.Get.To.The.Eeeee"
+ "eeeeend.Almost.There.Are.We.Really.Long.Name.Over.One.Hundred.And.Twenty.Six.Chars.Eeeeeeeventualll"
+ "llllly.I.Will.Get.To.The.Eeeeeeeeeend.Almost.There.Aret")]
public async Task DnsGetHostEntry_BadName_ThrowsArgumentOutOfRangeException(string hostNameOrAddress)
{
Assert.ThrowsAny<ArgumentOutOfRangeException>(() => Dns.GetHostEntry(hostNameOrAddress));
await Assert.ThrowsAnyAsync<ArgumentOutOfRangeException>(() => Dns.GetHostEntryAsync(hostNameOrAddress));
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsMultithreadingSupported))]
[InlineData("Really.Long.Name.Over.One.Hundred.And.Twenty.Six.Chars.Eeeeeeeventualllllllly.I.Will.Get.To.The.Eeeee"
+ "eeeeend.Almost.There.Are.We.Really.Long.Name.Over.One.Hundred.And.Twenty.Six.Chars.Eeeeeeeventualll"
+ "llllly.I.Will.Get.To.The.Eeeeeeeeeend.Almost.There.Aret")]
public async Task DnsGetHostEntry_BadName_ThrowsArgumentOutOfRangeException_Obsolete(string hostNameOrAddress)
{
await Assert.ThrowsAnyAsync<ArgumentOutOfRangeException>(() => Task.Factory.FromAsync(Dns.BeginGetHostEntry, Dns.EndGetHostEntry, hostNameOrAddress, null));
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[ActiveIssue("https://github.com/dotnet/runtime/issues/107339", TestPlatforms.Wasi)]
[ActiveIssue("https://github.com/dotnet/runtime/issues/124079", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst | TestPlatforms.Android)]
public async Task DnsGetHostEntry_LocalHost_ReturnsFqdnAndLoopbackIPs(int mode)
{
IPHostEntry entry = mode switch
{
0 => Dns.GetHostEntry("localhost"),
1 => await Dns.GetHostEntryAsync("localhost"),
_ => await Task.Factory.FromAsync(Dns.BeginGetHostEntry, Dns.EndGetHostEntry, "localhost", null)
};
Assert.NotNull(entry.HostName);
Assert.True(entry.HostName.Length > 0, "Empty host name");
Assert.True(entry.AddressList.Length >= 1, "No local IPs");
Assert.All(entry.AddressList, addr => Assert.True(IPAddress.IsLoopback(addr), "Not a loopback address: " + addr));
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsMultithreadingSupported))]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
public async Task DnsGetHostEntry_LoopbackIP_MatchesGetHostEntryLoopbackString(int mode)
{
if (OperatingSystem.IsWasi() && mode == 2)
throw new SkipTestException("mode 2 is not supported on WASI");
IPAddress address = IPAddress.Loopback;
IPHostEntry ipEntry = mode switch
{
0 => Dns.GetHostEntry(address),
1 => await Dns.GetHostEntryAsync(address),
_ => await Task.Factory.FromAsync(Dns.BeginGetHostEntry, Dns.EndGetHostEntry, address, null)
};
IPHostEntry stringEntry = mode switch
{
0 => Dns.GetHostEntry(address.ToString()),
1 => await Dns.GetHostEntryAsync(address.ToString()),
_ => await Task.Factory.FromAsync(Dns.BeginGetHostEntry, Dns.EndGetHostEntry, address.ToString(), null)
};
Assert.Equal(ipEntry.HostName, stringEntry.HostName);
Assert.Equal(ipEntry.AddressList, stringEntry.AddressList);
}
[OuterLoop]
[Theory]
[MemberData(nameof(AddressFamilySpecificTestData))]
public async Task DnsGetHostEntry_LocalHost_AddressFamilySpecific(bool useAsync, string host, AddressFamily addressFamily)
{
IPHostEntry entry =
useAsync ? await Dns.GetHostEntryAsync(host, addressFamily) :
Dns.GetHostEntry(host, addressFamily);
Assert.All(entry.AddressList, address => Assert.Equal(addressFamily, address.AddressFamily));
}
public static TheoryData<bool, string, AddressFamily> AddressFamilySpecificTestData =>
new TheoryData<bool, string, AddressFamily>()
{
// async, hostname, af
{ false, TestSettings.IPv4Host, AddressFamily.InterNetwork },
{ false, TestSettings.IPv6Host, AddressFamily.InterNetworkV6 },
{ true, TestSettings.IPv4Host, AddressFamily.InterNetwork },
{ true, TestSettings.IPv6Host, AddressFamily.InterNetworkV6 }
};
// RFC 6761 Section 6.4: "invalid" and "*.invalid" must always return NXDOMAIN (HostNotFound).
[Theory]
[InlineData("invalid")]
[InlineData("invalid.")]
[InlineData("test.invalid")]
[InlineData("test.invalid.")]
[InlineData("foo.bar.invalid")]
[InlineData("INVALID")]
[InlineData("Test.INVALID")]
public async Task DnsGetHostEntry_InvalidDomain_ThrowsHostNotFound(string hostName)
{
SocketException ex = Assert.ThrowsAny<SocketException>(() => Dns.GetHostEntry(hostName));
Assert.Equal(SocketError.HostNotFound, ex.SocketErrorCode);
ex = await Assert.ThrowsAnyAsync<SocketException>(() => Dns.GetHostEntryAsync(hostName));
Assert.Equal(SocketError.HostNotFound, ex.SocketErrorCode);
}
// RFC 6761 Section 6.3: "*.localhost" subdomains - OS resolver is tried first,
// falling back to plain "localhost" resolution if OS resolver fails or returns empty.
// This preserves /etc/hosts customizations.
[Theory]
[InlineData("foo.localhost")]
[InlineData("bar.foo.localhost")]
[InlineData("test.localhost")]
[InlineData("FOO.LOCALHOST")]
[InlineData("Test.LocalHost")]
public async Task DnsGetHostEntry_LocalhostSubdomain_ReturnsLoopback(string hostName)
{
// The subdomain goes to OS resolver first. If it fails (likely on most systems),
// it falls back to resolving plain "localhost", which should return loopback addresses.
// On Android/Apple mobile platforms the OS resolver may return non-loopback addresses
// for *.localhost.
bool requireLoopback = !PlatformDetection.IsAppleMobile && !PlatformDetection.IsAndroid;
IPHostEntry entry = Dns.GetHostEntry(hostName);
Assert.True(entry.AddressList.Length >= 1, "Expected at least one address");
if (requireLoopback)
{
Assert.All(entry.AddressList, addr => Assert.True(IPAddress.IsLoopback(addr), $"Expected loopback address but got: {addr}"));
}
entry = await Dns.GetHostEntryAsync(hostName);
Assert.True(entry.AddressList.Length >= 1, "Expected at least one address");
if (requireLoopback)
{
Assert.All(entry.AddressList, addr => Assert.True(IPAddress.IsLoopback(addr), $"Expected loopback address but got: {addr}"));
}
}
// RFC 6761: Ensure names that look similar but are not reserved are still resolved via OS.
[Theory]
[InlineData("notlocalhost")]
[InlineData("localhostfoo")]
[InlineData("invalidname")]
[InlineData("testinvalid")]
public async Task DnsGetHostEntry_SimilarButNotReserved_ThrowsSocketException(string hostName)
{
// These should go to the OS resolver and fail with HostNotFound (not special-cased).
Assert.ThrowsAny<SocketException>(() => Dns.GetHostEntry(hostName));
await Assert.ThrowsAnyAsync<SocketException>(() => Dns.GetHostEntryAsync(hostName));
}
// Malformed hostnames should not be treated as RFC 6761 reserved names.
// They should fall through to the OS resolver which will reject them.
// Note: Only ".invalid" variants are tested here. Malformed localhost names
// (e.g., ".localhost") may succeed on some platforms because the OS resolver
// handles localhost specially.
[Theory]
[InlineData(".invalid")]
[InlineData("test..invalid")]
public async Task DnsGetHostEntry_MalformedReservedName_NotTreatedAsReserved(string hostName)
{
// Malformed hostnames should go to OS resolver, not be special-cased.
// OS resolver will typically reject them with ArgumentException or SocketException.
Assert.ThrowsAny<Exception>(() => Dns.GetHostEntry(hostName));
await Assert.ThrowsAnyAsync<Exception>(() => Dns.GetHostEntryAsync(hostName));
}
// "localhost." (with trailing dot) should NOT be treated as a subdomain.
// It's equivalent to plain "localhost" and should resolve via OS resolver.
[Fact]
public async Task DnsGetHostEntry_LocalhostWithTrailingDot_ReturnsLoopback()
{
IPHostEntry entry = Dns.GetHostEntry("localhost.");
Assert.True(entry.AddressList.Length >= 1, "Expected at least one address");
Assert.All(entry.AddressList, addr => Assert.True(IPAddress.IsLoopback(addr), $"Expected loopback address but got: {addr}"));
entry = await Dns.GetHostEntryAsync("localhost.");
Assert.True(entry.AddressList.Length >= 1, "Expected at least one address");
Assert.All(entry.AddressList, addr => Assert.True(IPAddress.IsLoopback(addr), $"Expected loopback address but got: {addr}"));
}
// RFC 6761: "*.localhost" subdomains should respect AddressFamily parameter.
// OS resolver is tried first, falling back to plain "localhost" resolution.
[Theory]
[InlineData(AddressFamily.InterNetwork)]
[InlineData(AddressFamily.InterNetworkV6)]
public async Task DnsGetHostEntry_LocalhostSubdomain_RespectsAddressFamily(AddressFamily addressFamily)
{
// Skip IPv6 test if OS doesn't support it.
if (addressFamily == AddressFamily.InterNetworkV6 && !Socket.OSSupportsIPv6)
{
return;
}
string hostName = "test.localhost";
// On Android and Apple mobile the OS resolver may return addresses of a different
// family than requested (e.g. link-local IPv6 results for an IPv4 query), so we
// only require the requested family to be represented in the results there.
bool strictAddressFamily = !PlatformDetection.IsAppleMobile && !PlatformDetection.IsAndroid;
// The subdomain goes to OS resolver first. If it fails, it falls back to
// resolving plain "localhost" with the same address family filter.
IPHostEntry entry = Dns.GetHostEntry(hostName, addressFamily);
VerifyAddressFamily(entry, addressFamily, strictAddressFamily);
entry = await Dns.GetHostEntryAsync(hostName, addressFamily);
VerifyAddressFamily(entry, addressFamily, strictAddressFamily);
static void VerifyAddressFamily(IPHostEntry entry, AddressFamily addressFamily, bool strictAddressFamily)
{
if (addressFamily == AddressFamily.InterNetwork)
{
Assert.Contains(entry.AddressList, addr => addr.AddressFamily == addressFamily);
}
if (strictAddressFamily)
{
Assert.All(entry.AddressList, addr => Assert.Equal(addressFamily, addr.AddressFamily));
}
}
}
// RFC 6761: Verify that localhost subdomains return loopback addresses.
// Note: We don't require exact equality with plain "localhost" because:
// 1. The OS resolver is tried first for subdomains
// 2. The OS may return different results (e.g., both IPv4+IPv6 vs IPv4 only)
// 3. Different systems configure localhost differently
// On Android and Apple mobile the OS resolver may return non-loopback addresses
// for both plain "localhost" and "*.localhost" (e.g. link-local IPv6 or
// multicast DNS results), so we only require any address to be returned there.
[Fact]
public async Task DnsGetHostEntry_LocalhostAndSubdomain_BothReturnLoopback()
{
bool requireLoopback = !PlatformDetection.IsAppleMobile && !PlatformDetection.IsAndroid;
IPHostEntry localhostEntry = Dns.GetHostEntry("localhost");
IPHostEntry subdomainEntry = Dns.GetHostEntry("foo.localhost");
Assert.True(localhostEntry.AddressList.Length >= 1);
Assert.True(subdomainEntry.AddressList.Length >= 1);
if (requireLoopback)
{
Assert.All(localhostEntry.AddressList, addr => Assert.True(IPAddress.IsLoopback(addr), $"Expected loopback address but got: {addr}"));
Assert.All(subdomainEntry.AddressList, addr => Assert.True(IPAddress.IsLoopback(addr), $"Expected loopback address but got: {addr}"));
}
localhostEntry = await Dns.GetHostEntryAsync("localhost");
subdomainEntry = await Dns.GetHostEntryAsync("bar.localhost");
Assert.True(localhostEntry.AddressList.Length >= 1);
Assert.True(subdomainEntry.AddressList.Length >= 1);
if (requireLoopback)
{
Assert.All(localhostEntry.AddressList, addr => Assert.True(IPAddress.IsLoopback(addr), $"Expected loopback address but got: {addr}"));
Assert.All(subdomainEntry.AddressList, addr => Assert.True(IPAddress.IsLoopback(addr), $"Expected loopback address but got: {addr}"));
}
}
// RFC 6761: Localhost subdomains with trailing dot should work (e.g., "foo.localhost.")
// Trailing dot is valid DNS notation indicating the root.
[Theory]
[InlineData("foo.localhost.")]
[InlineData("bar.test.localhost.")]
public async Task DnsGetHostEntry_LocalhostSubdomainWithTrailingDot_ReturnsLoopback(string hostName)
{
bool requireLoopback = !PlatformDetection.IsAppleMobile && !PlatformDetection.IsAndroid;
IPHostEntry entry = Dns.GetHostEntry(hostName);
Assert.True(entry.AddressList.Length >= 1, "Expected at least one address");
if (requireLoopback)
{
Assert.All(entry.AddressList, addr => Assert.True(IPAddress.IsLoopback(addr), $"Expected loopback address but got: {addr}"));
}
entry = await Dns.GetHostEntryAsync(hostName);
Assert.True(entry.AddressList.Length >= 1, "Expected at least one address");
if (requireLoopback)
{
Assert.All(entry.AddressList, addr => Assert.True(IPAddress.IsLoopback(addr), $"Expected loopback address but got: {addr}"));
}
}
[Fact]
public async Task DnsGetHostEntry_PreCancelledToken_Throws()
{
using var cts = new CancellationTokenSource();
cts.Cancel();
OperationCanceledException oce = await Assert.ThrowsAnyAsync<OperationCanceledException>(() => Dns.GetHostEntryAsync(TestSettings.LocalHost, cts.Token));
Assert.Equal(cts.Token, oce.CancellationToken);
}
}
// Cancellation tests are sequential to reduce the chance of timing issues.
[Collection(nameof(DisableParallelization))]
public class GetHostEntryTest_Cancellation
{
[Fact]
[OuterLoop]
[ActiveIssue("https://github.com/dotnet/runtime/issues/33378", TestPlatforms.AnyUnix)] // Cancellation of an outstanding getaddrinfo is not supported on *nix.
[SkipOnCoreClr("JitStress interferes with cancellation timing", RuntimeTestModes.JitStress | RuntimeTestModes.JitStressRegs)]
public async Task DnsGetHostEntry_PostCancelledToken_Throws()
{
using var cts = new CancellationTokenSource();
Task task = Dns.GetHostEntryAsync(TestSettings.UncachedHost, cts.Token);
// This test might flake if the cancellation token takes too long to trigger:
// It's a race between the DNS server getting back to us and the cancellation processing.
cts.Cancel();
OperationCanceledException oce = await Assert.ThrowsAnyAsync<OperationCanceledException>(() => task);
Assert.Equal(cts.Token, oce.CancellationToken);
}
}
}