diff --git a/src/libraries/System.Net.NameResolution/src/Resources/Strings.resx b/src/libraries/System.Net.NameResolution/src/Resources/Strings.resx
index ed124526d86fbe..cd5e315107e139 100644
--- a/src/libraries/System.Net.NameResolution/src/Resources/Strings.resx
+++ b/src/libraries/System.Net.NameResolution/src/Resources/Strings.resx
@@ -72,6 +72,9 @@
IPv4 address 0.0.0.0 and IPv6 address ::0 are unspecified addresses that cannot be used as a target address.
+
+ The host name cannot contain a null character.
+
System.Net.NameResolution is not supported on this platform.
diff --git a/src/libraries/System.Net.NameResolution/src/System/Net/Dns.cs b/src/libraries/System.Net.NameResolution/src/System/Net/Dns.cs
index fdac620bbf15df..51938265ed50d8 100644
--- a/src/libraries/System.Net.NameResolution/src/System/Net/Dns.cs
+++ b/src/libraries/System.Net.NameResolution/src/System/Net/Dns.cs
@@ -895,6 +895,13 @@ private static void ValidateHostName(string hostName)
throw new ArgumentOutOfRangeException(nameof(hostName),
SR.Format(SR.net_toolong, nameof(hostName), MaxHostName.ToString(NumberFormatInfo.CurrentInfo)));
}
+
+ // The hostname is passed to native APIs that treat '\0' as the end of the string,
+ // so embedded null characters would silently truncate the name. Reject them up front.
+ if (hostName.Contains('\0'))
+ {
+ throw new ArgumentException(SR.net_hostname_invalid_character, nameof(hostName));
+ }
}
private static bool LogFailure(object hostNameOrAddress, in NameResolutionActivity activity, Exception exception)
diff --git a/src/libraries/System.Net.NameResolution/tests/FunctionalTests/GetHostEntryTest.cs b/src/libraries/System.Net.NameResolution/tests/FunctionalTests/GetHostEntryTest.cs
index d3d1676c9b110f..f0275c27c0312f 100644
--- a/src/libraries/System.Net.NameResolution/tests/FunctionalTests/GetHostEntryTest.cs
+++ b/src/libraries/System.Net.NameResolution/tests/FunctionalTests/GetHostEntryTest.cs
@@ -255,6 +255,20 @@ public async Task DnsGetHostEntry_BadName_ThrowsArgumentOutOfRangeException_Obso
await Assert.ThrowsAnyAsync(() => Task.Factory.FromAsync(Dns.BeginGetHostEntry, Dns.EndGetHostEntry, hostNameOrAddress, null));
}
+ [Theory]
+ [InlineData("\0")]
+ [InlineData("\0host")]
+ [InlineData("host\0")]
+ [InlineData("ho\0st")]
+ [InlineData("host\0name")]
+ public async Task DnsGetHostEntry_NullCharacterInName_ThrowsArgumentException(string hostNameOrAddress)
+ {
+ Assert.Throws(() => Dns.GetHostEntry(hostNameOrAddress));
+ Assert.Throws(() => Dns.GetHostAddresses(hostNameOrAddress));
+ await Assert.ThrowsAsync(() => Dns.GetHostEntryAsync(hostNameOrAddress));
+ await Assert.ThrowsAsync(() => Dns.GetHostAddressesAsync(hostNameOrAddress));
+ }
+
[Theory]
[InlineData(0)]
[InlineData(1)]