Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ internal unsafe struct HostEntry
[LibraryImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetHostEntryForName", StringMarshalling = StringMarshalling.Utf8)]
internal static unsafe partial int GetHostEntryForName(string address, AddressFamily family, HostEntry* entry);

[LibraryImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetHostEntryForLocalMachine", StringMarshalling = StringMarshalling.Utf8)]
internal static unsafe partial int GetHostEntryForLocalMachine(string address, AddressFamily family, HostEntry* entry);

[LibraryImport(Libraries.SystemNative, EntryPoint = "SystemNative_FreeHostEntry")]
internal static unsafe partial void FreeHostEntry(HostEntry* entry);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,14 +130,18 @@ private static unsafe void ParseHostEntry(Interop.Sys.HostEntry hostEntry, bool

public static unsafe SocketError TryGetAddrInfo(string name, bool justAddresses, AddressFamily addressFamily, out string? hostName, out string[] aliases, out IPAddress[] addresses, out int nativeErrorCode)
{
if (name == "")
bool localMachine = name == "";
if (localMachine)
{
// To match documented behavior on Windows, if an empty string is passed in, use the local host's name.
name = Dns.GetHostName();
}

Interop.Sys.HostEntry entry;
int result = Interop.Sys.GetHostEntryForName(name, addressFamily, &entry);
// Android can report "localhost" as its host name; empty-name lookups still need local interface addresses.
int result = localMachine && OperatingSystem.IsAndroid() ?
Interop.Sys.GetHostEntryForLocalMachine(name, addressFamily, &entry) :
Interop.Sys.GetHostEntryForName(name, addressFamily, &entry);
if (result != 0)
{
nativeErrorCode = result;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -370,15 +370,31 @@ public async Task DnsGetHostAddresses_MalformedReservedName_NotTreatedAsReserved
await Assert.ThrowsAnyAsync<Exception>(() => Dns.GetHostAddressesAsync(hostName));
}

[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsAndroid))]
[InlineData("localhost")]
[InlineData("LOCALHOST")]
public async Task DnsGetHostAddresses_LocalhostOnAndroid_ReturnsLoopback(string hostName)
{
IPAddress[] addresses = Dns.GetHostAddresses(hostName);
Assert.NotEmpty(addresses);
Assert.All(addresses, addr => Assert.True(IPAddress.IsLoopback(addr), $"Expected loopback address but got: {addr}"));

addresses = await Dns.GetHostAddressesAsync(hostName);
Assert.NotEmpty(addresses);
Assert.All(addresses, addr => Assert.True(IPAddress.IsLoopback(addr), $"Expected loopback address but got: {addr}"));
}

// "localhost." is resolved by the OS first, with fallback to plain "localhost" on failure or an empty result.
[Fact]
public async Task DnsGetHostAddresses_LocalhostWithTrailingDot_ReturnsLoopback()
[Theory]
[InlineData("localhost.")]
[InlineData("LOCALHOST.")]
public async Task DnsGetHostAddresses_LocalhostWithTrailingDot_ReturnsLoopback(string hostName)
{
IPAddress[] addresses = Dns.GetHostAddresses("localhost.");
IPAddress[] addresses = Dns.GetHostAddresses(hostName);
Assert.True(addresses.Length >= 1, "Expected at least one address");
Assert.All(addresses, addr => Assert.True(IPAddress.IsLoopback(addr), $"Expected loopback address but got: {addr}"));

addresses = await Dns.GetHostAddressesAsync("localhost.");
addresses = await Dns.GetHostAddressesAsync(hostName);
Assert.True(addresses.Length >= 1, "Expected at least one address");
Assert.All(addresses, addr => Assert.True(IPAddress.IsLoopback(addr), $"Expected loopback address but got: {addr}"));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
Expand Down Expand Up @@ -277,7 +278,7 @@ public async Task DnsGetHostEntry_NullCharacterInName_ThrowsArgumentException(st
[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)]
[ActiveIssue("https://github.com/dotnet/runtime/issues/124079", TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)]
public async Task DnsGetHostEntry_LocalHost_ReturnsFqdnAndLoopbackIPs(int mode)
{
IPHostEntry entry = mode switch
Expand All @@ -293,6 +294,33 @@ public async Task DnsGetHostEntry_LocalHost_ReturnsFqdnAndLoopbackIPs(int mode)
Assert.All(entry.AddressList, addr => Assert.True(IPAddress.IsLoopback(addr), "Not a loopback address: " + addr));
}

[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsAndroid))]
[InlineData(AddressFamily.Unspecified)]
[InlineData(AddressFamily.InterNetwork)]
public async Task Dns_EmptyHostName_IncludesLocalInterfaceAddress(AddressFamily family)
{
if (!string.Equals(Dns.GetHostName(), "localhost", StringComparison.OrdinalIgnoreCase))
{
throw new SkipTestException("The machine's host name is not localhost.");
}

IPAddress address = NetworkInterface.GetAllNetworkInterfaces()
.Where(n => n.OperationalStatus == OperationalStatus.Up && n.NetworkInterfaceType != NetworkInterfaceType.Loopback)
.SelectMany(n => n.GetIPProperties().UnicastAddresses)
.Select(a => a.Address)
.FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(a));

if (address is null)
{
throw new SkipTestException("No active non-loopback IPv4 interface is available.");
}

Assert.Contains(address, Dns.GetHostEntry("", family).AddressList);
Assert.Contains(address, (await Dns.GetHostEntryAsync("", family)).AddressList);
Assert.Contains(address, Dns.GetHostAddresses("", family));
Assert.Contains(address, await Dns.GetHostAddressesAsync("", family));
}

[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsMultithreadingSupported))]
[InlineData(0)]
[InlineData(1)]
Expand Down Expand Up @@ -422,16 +450,17 @@ public async Task DnsGetHostEntry_MalformedReservedName_NotTreatedAsReserved(str
await Assert.ThrowsAnyAsync<Exception>(() => Dns.GetHostEntryAsync(hostName));
}

// "localhost." is equivalent to plain "localhost".
// The OS resolver is tried first, falling back to plain "localhost" if resolution fails or returns no addresses.
[Fact]
public async Task DnsGetHostEntry_LocalhostWithTrailingDot_ReturnsLoopback()
// "localhost." is resolved by the OS first, with fallback to plain "localhost" on failure or an empty result.
[Theory]
[InlineData("localhost.")]
[InlineData("LOCALHOST.")]
public async Task DnsGetHostEntry_LocalhostWithTrailingDot_ReturnsLoopback(string hostName)
{
IPHostEntry entry = Dns.GetHostEntry("localhost.");
IPHostEntry entry = Dns.GetHostEntry(hostName);
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.");
entry = await Dns.GetHostEntryAsync(hostName);
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}"));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
</ItemGroup>

<ItemGroup>
<ProjectReference Include="$(LibrariesProjectRoot)Microsoft.Win32.Primitives\src\Microsoft.Win32.Primitives.csproj" />
<ProjectReference Include="$(LibrariesProjectRoot)System.Memory\src\System.Memory.csproj" />
<ProjectReference Include="$(LibrariesProjectRoot)System.Net.NameResolution\src\System.Net.NameResolution.csproj" />
<ProjectReference Include="$(LibrariesProjectRoot)System.Net.NetworkInformation\src\System.Net.NetworkInformation.csproj" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Threading;

Expand All @@ -26,7 +27,32 @@ private static bool IsLocal(Uri host)
if (IPAddress.TryParse(hostString, out IPAddress? hostAddress))
{
EnsureNetworkChangeRegistration();
IPAddress[] localAddresses = s_localAddresses ??= Dns.GetHostEntry(Dns.GetHostName()).AddressList;
IPAddress[]? localAddresses = s_localAddresses;
if (localAddresses is null)
{
string hostName = Dns.GetHostName();
if (OperatingSystem.IsAndroid() &&
(hostName.Equals("localhost", StringComparison.OrdinalIgnoreCase) ||
hostName.Equals("localhost.", StringComparison.OrdinalIgnoreCase)))
{
// The empty-name lookup distinguishes the local machine from the loopback name.
try
{
localAddresses = Dns.GetHostEntry("").AddressList;
}
catch (SocketException) when (hostName.EndsWith('.'))
{
// A failed fully qualified lookup falls back to the relative name.
localAddresses = Dns.GetHostEntry("localhost").AddressList;
}
}
else
{
localAddresses = Dns.GetHostEntry(hostName).AddressList;
}
s_localAddresses = localAddresses;
}

return Array.IndexOf(localAddresses, hostAddress) >= 0;
}

Expand Down
55 changes: 55 additions & 0 deletions src/libraries/System.Net.WebProxy/tests/WebProxyTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.Linq;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using Microsoft.DotNet.XUnitExtensions;
using Xunit;

namespace System.Net.Tests
Expand Down Expand Up @@ -273,6 +274,60 @@ public static void WebProxy_BypassOnLocal_ConfiguredToNotBypassLocal()
Assert.False(new WebProxy("microsoft", BypassOnLocal: false).IsBypassed(new Uri($"http://{IPAddress.Loopback}")));
}

[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsAndroid))]
public static void WebProxy_BypassOnLocal_BypassesNonLoopbackInterfaceAddress()
{
string hostName = Dns.GetHostName();
bool hasTrailingDot = hostName.Equals("localhost.", StringComparison.OrdinalIgnoreCase);
if (!hostName.Equals("localhost", StringComparison.OrdinalIgnoreCase) && !hasTrailingDot)
{
throw new SkipTestException("The machine's host name is neither 'localhost' nor 'localhost.'.");
}

IPAddress address = NetworkInterface.GetAllNetworkInterfaces()
.Where(n => n.OperationalStatus == OperationalStatus.Up && n.NetworkInterfaceType != NetworkInterfaceType.Loopback)
.SelectMany(n => n.GetIPProperties().UnicastAddresses)
.Select(a => a.Address)
.FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(a));

if (address is null)
{
throw new SkipTestException("No active non-loopback IPv4 interface is available.");
}

if (hasTrailingDot)
{
try
{
Assert.Contains(address, Dns.GetHostEntry("").AddressList);
}
catch (SocketException)
{
throw new SkipTestException("The machine's host name does not resolve directly.");
}
}

Uri destination = new Uri($"http://{address}");
var proxy = new WebProxy("http://proxy.example", BypassOnLocal: true);
Assert.True(proxy.IsBypassed(destination));
Assert.Equal(destination, proxy.GetProxy(destination));
}

[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsAndroid))]
public static void WebProxy_BypassOnLocal_PreservesTrailingDotHostNameLookup()
{
string hostName = Dns.GetHostName();
if (!hostName.Equals("localhost.", StringComparison.OrdinalIgnoreCase))
{
throw new SkipTestException("The machine's host name is not localhost with a trailing dot.");
}

IPAddress address = IPAddress.Parse("192.0.2.1");
bool expected = Dns.GetHostEntry(hostName).AddressList.Contains(address);
var proxy = new WebProxy("http://proxy.example", BypassOnLocal: true);
Assert.Equal(expected, proxy.IsBypassed(new Uri($"http://{address}")));
}

[Theory]
[InlineData("http://user:pass@host", "user", "pass")]
[InlineData("http://user:pass@host:8080", "user", "pass")]
Expand Down
1 change: 1 addition & 0 deletions src/native/libs/System.Native/entrypoints.c
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ static const Entry s_sysNative[] =
DllImportEntry(SystemNative_CreateNetworkChangeListenerSocket)
#endif // !defined(TARGET_WASMARCH) && !defined(TARGET_WASI)
DllImportEntry(SystemNative_GetHostEntryForName)
DllImportEntry(SystemNative_GetHostEntryForLocalMachine)
DllImportEntry(SystemNative_FreeHostEntry)
DllImportEntry(SystemNative_GetNameInfo)
DllImportEntry(SystemNative_GetDomainName)
Expand Down
43 changes: 41 additions & 2 deletions src/native/libs/System.Native/pal_networking.c
Original file line number Diff line number Diff line change
Expand Up @@ -311,8 +311,35 @@ static int32_t CopySockAddrToIPAddress(sockaddr* addr, sa_family_t family, IPAdd
return -1;
}

int32_t SystemNative_GetHostEntryForName(const uint8_t* address, int32_t addressFamily, HostEntry* entry)
#if HAVE_GETIFADDRS
// Determines whether the result of resolving 'address' should be augmented with the local
// interface addresses, which happens when 'address' refers to the machine's own host name.
static bool ShouldAugmentWithInterfaceAddresses(const char* address, const char* hostName, bool localMachine)
{
(void)localMachine;

if (strcasecmp(address, hostName) != 0)
{
return false;
}

#ifdef TARGET_ANDROID
// Android may report localhost as its host name, but resolving localhost should not
// add the addresses of the machine's other interfaces.
if (!localMachine && (strcasecmp(address, "localhost") == 0 || strcasecmp(address, "localhost.") == 0))
{
return false;
}
#endif

return true;
}
#endif

static int32_t GetHostEntryForName(const uint8_t* address, int32_t addressFamily, HostEntry* entry, bool localMachine)
{
(void)localMachine;

if (address == NULL || entry == NULL)
{
return GetAddrInfoErrorFlags_EAI_BADARG;
Expand Down Expand Up @@ -376,7 +403,9 @@ int32_t SystemNative_GetHostEntryForName(const uint8_t* address, int32_t address
includeIPv4Loopback = true;
includeIPv6Loopback = true;

if (result == 0 && strcasecmp((const char*)address, name) == 0)
// Augment the result with the local interface addresses when resolving the machine's own
// host name (see ShouldAugmentWithInterfaceAddresses for platform-specific exceptions).
if (result == 0 && ShouldAugmentWithInterfaceAddresses((const char*)address, name, localMachine))
{
// Get all interface addresses if the host name corresponds to the local host.
result = getifaddrs(&addrs);
Expand Down Expand Up @@ -509,6 +538,16 @@ int32_t SystemNative_GetHostEntryForName(const uint8_t* address, int32_t address
return ret;
}

int32_t SystemNative_GetHostEntryForName(const uint8_t* address, int32_t addressFamily, HostEntry* entry)
{
return GetHostEntryForName(address, addressFamily, entry, false);
}

int32_t SystemNative_GetHostEntryForLocalMachine(const uint8_t* address, int32_t addressFamily, HostEntry* entry)
{
return GetHostEntryForName(address, addressFamily, entry, true);
}

void SystemNative_FreeHostEntry(HostEntry* entry)
{
if (entry != NULL)
Expand Down
2 changes: 2 additions & 0 deletions src/native/libs/System.Native/pal_networking.h
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,8 @@ typedef struct

PALEXPORT int32_t SystemNative_GetHostEntryForName(const uint8_t* address, int32_t addressFamily, HostEntry* entry);

PALEXPORT int32_t SystemNative_GetHostEntryForLocalMachine(const uint8_t* address, int32_t addressFamily, HostEntry* entry);

PALEXPORT void SystemNative_FreeHostEntry(HostEntry* entry);


Expand Down
5 changes: 5 additions & 0 deletions src/native/libs/System.Native/pal_networking_browser.c
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ int32_t SystemNative_GetHostEntryForName(const uint8_t* address, int32_t address
return Error_ENOTSUP;
}

int32_t SystemNative_GetHostEntryForLocalMachine(const uint8_t* address, int32_t addressFamily, HostEntry* entry)
{
return SystemNative_GetHostEntryForName(address, addressFamily, entry);
}

void SystemNative_FreeHostEntry(HostEntry* entry)
{
(void)entry;
Expand Down