/// <summary>Gets the host name of the local machine.</summary>
public static string GetHostName()
{
- if (NetEventSource.IsEnabled) NetEventSource.Info(null, null);
NameResolutionPal.EnsureSocketsAreInitialized();
- return NameResolutionPal.GetHostName();
+ string name = NameResolutionPal.GetHostName();
+ if (NetEventSource.IsEnabled) NetEventSource.Info(null, name);
+ return name;
}
public static IPHostEntry GetHostEntry(IPAddress address)
{
- if (NetEventSource.IsEnabled) NetEventSource.Enter(null, address);
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(address, address);
NameResolutionPal.EnsureSocketsAreInitialized();
if (address is null)
if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))
{
+ if (NetEventSource.IsEnabled) NetEventSource.Error(address, $"Invalid address '{address}'");
throw new ArgumentException(SR.Format(SR.net_invalid_ip_addr, nameof(address)));
}
IPHostEntry ipHostEntry = GetHostEntryCore(address);
- if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry);
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(address, $"{ipHostEntry} with {ipHostEntry.AddressList.Length} entries");
return ipHostEntry;
}
public static IPHostEntry GetHostEntry(string hostNameOrAddress)
{
- if (NetEventSource.IsEnabled) NetEventSource.Enter(null, hostNameOrAddress);
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(hostNameOrAddress, hostNameOrAddress);
NameResolutionPal.EnsureSocketsAreInitialized();
if (hostNameOrAddress is null)
{
if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))
{
+ if (NetEventSource.IsEnabled) NetEventSource.Error(address, $"Invalid address '{address}'");
throw new ArgumentException(SR.Format(SR.net_invalid_ip_addr, nameof(hostNameOrAddress)));
}
ipHostEntry = GetHostEntryCore(hostNameOrAddress);
}
- if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry);
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(hostNameOrAddress, $"{ipHostEntry} with {ipHostEntry.AddressList.Length} entries");
return ipHostEntry;
}
- public static Task<IPHostEntry> GetHostEntryAsync(string hostNameOrAddress) =>
- GetHostEntryCoreAsync(hostNameOrAddress, justReturnParsedIp: false, throwOnIIPAny: true);
+ public static Task<IPHostEntry> GetHostEntryAsync(string hostNameOrAddress)
+ {
+ if (NetEventSource.IsEnabled)
+ {
+ NetEventSource.Enter(hostNameOrAddress, hostNameOrAddress);
+ Task<IPHostEntry> t = GetHostEntryCoreAsync(hostNameOrAddress, justReturnParsedIp: false, throwOnIIPAny: true);
+ t.ContinueWith((t, s) => NetEventSource.Exit((string)s, $"{t.Result} with {((IPHostEntry)t.Result).AddressList.Length} entries"),
+ hostNameOrAddress, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Default);
+ return t;
+ }
+ else
+ {
+ return GetHostEntryCoreAsync(hostNameOrAddress, justReturnParsedIp: false, throwOnIIPAny: true);
+ }
+ }
public static Task<IPHostEntry> GetHostEntryAsync(IPAddress address)
{
- if (NetEventSource.IsEnabled) NetEventSource.Info(null, address);
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(address, address);
+
NameResolutionPal.EnsureSocketsAreInitialized();
if (address is null)
if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))
{
+ if (NetEventSource.IsEnabled) NetEventSource.Error(address, $"Invalid address '{address}'");
throw new ArgumentException(SR.net_invalid_ip_addr, nameof(address));
}
- return RunAsync(s => GetHostEntryCore((IPAddress)s), address);
+ return RunAsync(s => {
+ IPHostEntry ipHostEntry = GetHostEntryCore((IPAddress)s);
+ if (NetEventSource.IsEnabled) NetEventSource.Exit((IPAddress)s, $"{ipHostEntry} with {ipHostEntry.AddressList.Length} entries");
+ return ipHostEntry;
+ }, address);
}
public static IAsyncResult BeginGetHostEntry(IPAddress address, AsyncCallback requestCallback, object stateObject)
{
- if (NetEventSource.IsEnabled) NetEventSource.Enter(null, address);
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(address, address);
IAsyncResult asyncResult = TaskToApm.Begin(GetHostEntryAsync(address), requestCallback, stateObject);
- if (NetEventSource.IsEnabled) NetEventSource.Exit(null, asyncResult);
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(address, asyncResult);
return asyncResult;
}
public static IAsyncResult BeginGetHostEntry(string hostNameOrAddress, AsyncCallback requestCallback, object stateObject)
{
- if (NetEventSource.IsEnabled) NetEventSource.Enter(null, hostNameOrAddress);
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(hostNameOrAddress, hostNameOrAddress);
IAsyncResult asyncResult = TaskToApm.Begin(GetHostEntryAsync(hostNameOrAddress), requestCallback, stateObject);
- if (NetEventSource.IsEnabled) NetEventSource.Exit(null, asyncResult);
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(asyncResult, asyncResult);
return asyncResult;
}
public static IPHostEntry EndGetHostEntry(IAsyncResult asyncResult)
{
- if (NetEventSource.IsEnabled) NetEventSource.Enter(null, asyncResult);
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(asyncResult, asyncResult);
IPHostEntry ipHostEntry = TaskToApm.End<IPHostEntry>(asyncResult ?? throw new ArgumentNullException(nameof(asyncResult)));
- if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry);
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(asyncResult, $"{ipHostEntry} with {ipHostEntry.AddressList.Length} entries" );
return ipHostEntry;
}
public static IPAddress[] GetHostAddresses(string hostNameOrAddress)
{
- if (NetEventSource.IsEnabled) NetEventSource.Enter(null, hostNameOrAddress);
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(hostNameOrAddress, hostNameOrAddress);
NameResolutionPal.EnsureSocketsAreInitialized();
if (hostNameOrAddress is null)
{
if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))
{
+ if (NetEventSource.IsEnabled) NetEventSource.Error(address, $"Invalid address '{address}'");
throw new ArgumentException(SR.Format(SR.net_invalid_ip_addr, nameof(hostNameOrAddress)));
}
addresses = GetHostAddressesCore(hostNameOrAddress);
}
- if (NetEventSource.IsEnabled) NetEventSource.Exit(null, addresses);
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(hostNameOrAddress, addresses);
return addresses;
}
public static IAsyncResult BeginGetHostAddresses(string hostNameOrAddress, AsyncCallback requestCallback, object state)
{
- if (NetEventSource.IsEnabled) NetEventSource.Enter(null, hostNameOrAddress);
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(hostNameOrAddress, hostNameOrAddress);
IAsyncResult asyncResult = TaskToApm.Begin(GetHostAddressesAsync(hostNameOrAddress), requestCallback, state);
- if (NetEventSource.IsEnabled) NetEventSource.Exit(null, asyncResult);
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(hostNameOrAddress, asyncResult);
return asyncResult;
}
public static IPAddress[] EndGetHostAddresses(IAsyncResult asyncResult)
{
- if (NetEventSource.IsEnabled) NetEventSource.Enter(null, asyncResult);
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(asyncResult, asyncResult);
IPAddress[] addresses = TaskToApm.End<IPAddress[]>(asyncResult ?? throw new ArgumentNullException(nameof(asyncResult)));
- if (NetEventSource.IsEnabled) NetEventSource.Exit(null, addresses);
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(asyncResult, addresses);
return addresses;
}
[Obsolete("BeginGetHostByName is obsoleted for this type, please use BeginGetHostEntry instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public static IAsyncResult BeginGetHostByName(string hostName, AsyncCallback requestCallback, object stateObject)
{
- if (NetEventSource.IsEnabled) NetEventSource.Enter(null, hostName);
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(hostName, hostName);
IAsyncResult asyncResult = TaskToApm.Begin(GetHostEntryCoreAsync(hostName, justReturnParsedIp: true, throwOnIIPAny: true), requestCallback, stateObject);
- if (NetEventSource.IsEnabled) NetEventSource.Exit(null, asyncResult);
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(hostName, asyncResult);
return asyncResult;
}
[Obsolete("EndGetHostByName is obsoleted for this type, please use EndGetHostEntry instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public static IPHostEntry EndGetHostByName(IAsyncResult asyncResult)
{
- if (NetEventSource.IsEnabled) NetEventSource.Enter(null, asyncResult);
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(asyncResult, asyncResult);
IPHostEntry ipHostEntry = TaskToApm.End<IPHostEntry>(asyncResult ?? throw new ArgumentNullException(nameof(asyncResult)));
- if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry);
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(asyncResult, ipHostEntry);
return ipHostEntry;
}
[Obsolete("GetHostByAddress is obsoleted for this type, please use GetHostEntry instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public static IPHostEntry GetHostByAddress(string address)
{
- if (NetEventSource.IsEnabled) NetEventSource.Enter(null, address);
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(address, address);
NameResolutionPal.EnsureSocketsAreInitialized();
if (address is null)
IPHostEntry ipHostEntry = GetHostEntryCore(IPAddress.Parse(address));
- if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry);
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(address, ipHostEntry);
return ipHostEntry;
}
[Obsolete("GetHostByAddress is obsoleted for this type, please use GetHostEntry instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public static IPHostEntry GetHostByAddress(IPAddress address)
{
- if (NetEventSource.IsEnabled) NetEventSource.Enter(null, address);
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(address, address);
NameResolutionPal.EnsureSocketsAreInitialized();
if (address is null)
IPHostEntry ipHostEntry = GetHostEntryCore(address);
- if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry);
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(address, ipHostEntry);
return ipHostEntry;
}
[Obsolete("Resolve is obsoleted for this type, please use GetHostEntry instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public static IPHostEntry Resolve(string hostName)
{
- if (NetEventSource.IsEnabled) NetEventSource.Enter(null, hostName);
+ if (NetEventSource.IsEnabled) NetEventSource.Enter(hostName, hostName);
NameResolutionPal.EnsureSocketsAreInitialized();
if (hostName is null)
}
catch (SocketException ex)
{
- if (NetEventSource.IsEnabled) NetEventSource.Error(null, ex);
+ if (NetEventSource.IsEnabled) NetEventSource.Error(hostName, ex);
ipHostEntry = CreateHostEntryForAddress(address);
}
}
ipHostEntry = GetHostEntryCore(hostName);
}
- if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry);
+ if (NetEventSource.IsEnabled) NetEventSource.Exit(hostName, ipHostEntry);
return ipHostEntry;
}
private static object GetHostEntryOrAddressesCore(string hostName, bool justAddresses)
{
- if (NetEventSource.IsEnabled) NetEventSource.Enter(null, hostName);
ValidateHostName(hostName);
- SocketError errorCode = NameResolutionPal.TryGetAddrInfo(hostName, justAddresses, out hostName, out string[] aliases, out IPAddress[] addresses, out int nativeErrorCode);
+ SocketError errorCode = NameResolutionPal.TryGetAddrInfo(hostName, justAddresses, out string newHostName, out string[] aliases, out IPAddress[] addresses, out int nativeErrorCode);
+
if (errorCode != SocketError.Success)
{
+ if (NetEventSource.IsEnabled) NetEventSource.Error(hostName, $"{hostName} DNS lookup failed with {errorCode}");
throw SocketExceptionFactory.CreateSocketException(errorCode, nativeErrorCode);
}
new IPHostEntry
{
AddressList = addresses,
- HostName = hostName,
+ HostName = newHostName,
Aliases = aliases
};
- if (NetEventSource.IsEnabled) NetEventSource.Exit(null, result);
return result;
}
// Does internal IPAddress reverse and then forward lookups (for Legacy and current public methods).
private static object GetHostEntryOrAddressesCore(IPAddress address, bool justAddresses)
{
- if (NetEventSource.IsEnabled) NetEventSource.Info(null, address);
-
// Try to get the data for the host from its address.
// We need to call getnameinfo first, because getaddrinfo w/ the ipaddress string
// will only return that address and not the full list.
string name = NameResolutionPal.TryGetNameInfo(address, out SocketError errorCode, out int nativeErrorCode);
if (errorCode != SocketError.Success)
{
+ if (NetEventSource.IsEnabled) NetEventSource.Error(address, $"{address} DNS lookup failed with {errorCode}");
throw SocketExceptionFactory.CreateSocketException(errorCode, nativeErrorCode);
}
if (errorCode != SocketError.Success)
{
- if (NetEventSource.IsEnabled) NetEventSource.Error(null, SocketExceptionFactory.CreateSocketException(errorCode, nativeErrorCode));
+ if (NetEventSource.IsEnabled) NetEventSource.Error(address, $"forward lookup for '{name}' failed with {errorCode}");
}
// One of three things happened:
// If hostName is an IPString and justReturnParsedIP==true then no reverse lookup will be attempted, but the original address is returned.
private static Task GetHostEntryOrAddressesCoreAsync(string hostName, bool justReturnParsedIp, bool throwOnIIPAny, bool justAddresses)
{
- if (NetEventSource.IsEnabled) NetEventSource.Info(null, hostName);
NameResolutionPal.EnsureSocketsAreInitialized();
if (hostName is null)
{
if (throwOnIIPAny && (ipAddress.Equals(IPAddress.Any) || ipAddress.Equals(IPAddress.IPv6Any)))
{
+ if (NetEventSource.IsEnabled) NetEventSource.Error(hostName, $"Invalid address '{ipAddress}'");
throw new ArgumentException(SR.net_invalid_ip_addr, nameof(hostName));
}
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Collections.Concurrent;
using System.Diagnostics.Tracing;
+using System.Linq;
+using System.Net.Sockets;
using System.Reflection;
+using System.Threading.Tasks;
+using Microsoft.DotNet.XUnitExtensions;
using Xunit;
+using Xunit.Abstractions;
namespace System.Net.NameResolution.Tests
{
- public static class LoggingTest
+ using Configuration = System.Net.Test.Common.Configuration;
+
+ [Collection("NoParallelTests")]
+ public class LoggingTest
{
[Fact]
public static void EventSource_ExistsWithCorrectId()
Assert.NotEmpty(EventSource.GenerateManifest(esType, "assemblyPathToIncludeInManifest"));
}
+
+ [ConditionalFact]
+ public void GetHostEntry_InvalidHost_LogsError()
+ {
+ using (var listener = new TestEventListener("Microsoft-System-Net-NameResolution", EventLevel.Error))
+ {
+ var events = new ConcurrentQueue<EventWrittenEventArgs>();
+
+ listener.RunWithCallback(ev => events.Enqueue(ev), () =>
+ {
+ try
+ {
+ Dns.GetHostEntry(Configuration.Sockets.InvalidHost);
+ throw new SkipTestException("GetHostEntry() should fail but it did not.");
+ }
+ catch (SocketException e) when (e.SocketErrorCode == SocketError.HostNotFound)
+ {
+ }
+ catch (Exception e)
+ {
+ throw new SkipTestException($"GetHostEntry failed unexpectedly: {e.Message}");
+ }
+ });
+
+ Assert.True(events.Count() > 0);
+ foreach (EventWrittenEventArgs ev in events)
+ {
+ Assert.True(ev.Payload.Count >= 3);
+ Assert.NotNull(ev.Payload[0]);
+ Assert.NotNull(ev.Payload[1]);
+ Assert.NotNull(ev.Payload[2]);
+ }
+ }
+ }
+
+ [ConditionalFact]
+ [PlatformSpecific(~TestPlatforms.Windows)] // Unreliable on Windows.
+ public void GetHostEntryAsync_InvalidHost_LogsError()
+ {
+ using (var listener = new TestEventListener("Microsoft-System-Net-NameResolution", EventLevel.Error))
+ {
+ var events = new ConcurrentQueue<EventWrittenEventArgs>();
+
+ listener.RunWithCallback(ev => events.Enqueue(ev), () =>
+ {
+ try
+ {
+ Dns.GetHostEntryAsync(Configuration.Sockets.InvalidHost).GetAwaiter().GetResult();
+ throw new SkipTestException("GetHostEntry() should fail but it did not.");
+ }
+ catch (SocketException e) when (e.SocketErrorCode == SocketError.HostNotFound)
+ {
+ }
+ catch (Exception e)
+ {
+ throw new SkipTestException($"GetHostEntry failed unexpectedly: {e.Message}");
+ }
+ });
+
+ Assert.True(events.Count() > 0);
+ foreach (EventWrittenEventArgs ev in events)
+ {
+ Assert.True(ev.Payload.Count >= 3);
+ Assert.NotNull(ev.Payload[0]);
+ Assert.NotNull(ev.Payload[1]);
+ Assert.NotNull(ev.Payload[2]);
+ }
+ }
+ }
+
+ [ConditionalFact]
+ public void GetHostEntry_ValidName_NoErrors()
+ {
+ using (var listener = new TestEventListener("Microsoft-System-Net-NameResolution", EventLevel.Verbose))
+ {
+ var events = new ConcurrentQueue<EventWrittenEventArgs>();
+
+ listener.RunWithCallback(ev => events.Enqueue(ev), () =>
+ {
+ try
+ {
+ Dns.GetHostEntryAsync("localhost").GetAwaiter().GetResult();
+ Dns.GetHostEntryAsync(IPAddress.Loopback).GetAwaiter().GetResult();
+ Dns.GetHostEntry("localhost");
+ Dns.GetHostEntry(IPAddress.Loopback);
+ }
+ catch (Exception e)
+ {
+ throw new SkipTestException($"Localhost lookup failed unexpectedly: {e.Message}");
+ }
+ });
+
+ // We get some traces.
+ Assert.True(events.Count() > 0);
+ // No errors or warning for successful query.
+ Assert.True(events.Count(ev => (int)ev.Level > (int)EventLevel.Informational) == 0);
+ }
+ }
}
}