diff --git a/src/libraries/System.Net.Sockets/src/System.Net.Sockets.csproj b/src/libraries/System.Net.Sockets/src/System.Net.Sockets.csproj
index 0c4b13e1c93..f8771e893d6 100644
--- a/src/libraries/System.Net.Sockets/src/System.Net.Sockets.csproj
+++ b/src/libraries/System.Net.Sockets/src/System.Net.Sockets.csproj
@@ -127,6 +127,7 @@
+
diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/IOControlKeepAlive.Windows.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/IOControlKeepAlive.Windows.cs
new file mode 100644
index 00000000000..887b1ff22ba
--- /dev/null
+++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/IOControlKeepAlive.Windows.cs
@@ -0,0 +1,115 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// 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.Diagnostics;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+namespace System.Net.Sockets
+{
+ // Allow hiding keep-alive time and interval handling behind *SocketOption
+ // on Windows < 10 v1709 that only supports set via IOControl
+ internal class IOControlKeepAlive
+ {
+ private const uint WindowsDefaultTimeMs = 7200000u;
+ private const uint WindowsDefaultIntervalMs = 1000u;
+ private static readonly bool s_supportsKeepAliveViaSocketOption = SupportsKeepAliveViaSocketOption();
+ private static readonly ConditionalWeakTable s_socketKeepAliveTable = new ConditionalWeakTable();
+ [ThreadStatic]
+ private static byte[] s_keepAliveValuesBuffer;
+
+ private uint _timeMs = WindowsDefaultTimeMs;
+ private uint _intervalMs = WindowsDefaultIntervalMs;
+
+ public static bool IsNeeded
+ {
+ get
+ {
+ return !s_supportsKeepAliveViaSocketOption;
+ }
+ }
+
+ public static SocketError Get(SafeSocketHandle handle, SocketOptionName optionName, byte[] optionValueSeconds, ref int optionLength)
+ {
+ if (optionValueSeconds == null || !BitConverter.TryWriteBytes(optionValueSeconds.AsSpan(), Get(handle, optionName)))
+ return SocketError.Fault;
+ optionLength = optionValueSeconds.Length;
+ return SocketError.Success;
+ }
+
+ public static int Get(SafeSocketHandle handle, SocketOptionName optionName)
+ {
+ IOControlKeepAlive ioControlKeepAlive;
+ s_socketKeepAliveTable.TryGetValue(handle, out ioControlKeepAlive);
+ return optionName == SocketOptionName.TcpKeepAliveTime ?
+ MillisecondsToSeconds(ioControlKeepAlive?._timeMs ?? WindowsDefaultTimeMs) :
+ MillisecondsToSeconds(ioControlKeepAlive?._intervalMs ?? WindowsDefaultIntervalMs);
+ }
+
+ public static SocketError Set(SafeSocketHandle handle, SocketOptionName optionName, byte[] optionValueSeconds)
+ {
+ if (optionValueSeconds == null || optionValueSeconds.Length < sizeof(int))
+ return SocketError.Fault;
+ return Set(handle, optionName, BitConverter.ToInt32(optionValueSeconds, 0));
+ }
+
+ public static SocketError Set(SafeSocketHandle handle, SocketOptionName optionName, int optionValueSeconds)
+ {
+ IOControlKeepAlive ioControlKeepAlive = s_socketKeepAliveTable.GetOrCreateValue(handle);
+ if (optionName == SocketOptionName.TcpKeepAliveTime)
+ ioControlKeepAlive._timeMs = SecondsToMilliseconds(optionValueSeconds);
+ else
+ ioControlKeepAlive._intervalMs = SecondsToMilliseconds(optionValueSeconds);
+
+ byte[] buffer = s_keepAliveValuesBuffer ?? (s_keepAliveValuesBuffer = new byte[3 * sizeof(uint)]);
+ ioControlKeepAlive.Fill(buffer);
+ int realOptionLength = 0;
+ return SocketPal.WindowsIoctl(handle, unchecked((int)IOControlCode.KeepAliveValues), buffer, null, out realOptionLength);
+ }
+
+ private static bool SupportsKeepAliveViaSocketOption()
+ {
+ AddressFamily addressFamily = Socket.OSSupportsIPv4 ? AddressFamily.InterNetwork : AddressFamily.InterNetworkV6;
+ using (Socket socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp))
+ {
+ int time = MillisecondsToSeconds(WindowsDefaultTimeMs);
+ SocketError timeErrCode = Interop.Winsock.setsockopt(
+ socket.SafeHandle,
+ SocketOptionLevel.Tcp,
+ SocketOptionName.TcpKeepAliveTime,
+ ref time,
+ sizeof(int));
+ int interval = MillisecondsToSeconds(WindowsDefaultIntervalMs);
+ SocketError intervalErrCode = Interop.Winsock.setsockopt(
+ socket.SafeHandle,
+ SocketOptionLevel.Tcp,
+ SocketOptionName.TcpKeepAliveInterval,
+ ref interval,
+ sizeof(int));
+ return timeErrCode == SocketError.Success && intervalErrCode == SocketError.Success;
+ }
+ }
+
+ private static int MillisecondsToSeconds(uint milliseconds)
+ {
+ return (int)(milliseconds / 1000u);
+ }
+
+ private static uint SecondsToMilliseconds(int seconds)
+ {
+ return (uint)seconds * 1000u;
+ }
+
+ private void Fill(byte[] buffer)
+ {
+ Debug.Assert(buffer != null);
+ Debug.Assert(buffer.Length == 3 * sizeof(uint));
+
+ const uint onOff = 1u;
+ BitConverter.TryWriteBytes(buffer.AsSpan(), onOff);
+ BitConverter.TryWriteBytes(buffer.AsSpan(sizeof(uint)), _timeMs);
+ BitConverter.TryWriteBytes(buffer.AsSpan(sizeof(uint) * 2), _intervalMs);
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Windows.cs b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Windows.cs
index 4ca57623d73..67da0980d54 100644
--- a/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Windows.cs
+++ b/src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketPal.Windows.cs
@@ -117,6 +117,7 @@ namespace System.Net.Sockets
IntPtr.Zero);
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
+
public static SocketError Send(SafeSocketHandle handle, IList> buffers, SocketFlags socketFlags, out int bytesTransferred)
{
const int StackThreshold = 16; // arbitrary limit to avoid too much space on stack (note: may be over-sized, that's OK - length passed separately)
@@ -489,23 +490,43 @@ namespace System.Net.Sockets
public static unsafe SocketError SetSockOpt(SafeSocketHandle handle, SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue)
{
- SocketError errorCode = Interop.Winsock.setsockopt(
- handle,
- optionLevel,
- optionName,
- ref optionValue,
- sizeof(int));
+ SocketError errorCode;
+ if (optionLevel == SocketOptionLevel.Tcp &&
+ (optionName == SocketOptionName.TcpKeepAliveTime || optionName == SocketOptionName.TcpKeepAliveInterval)
+ && IOControlKeepAlive.IsNeeded)
+ {
+ errorCode = IOControlKeepAlive.Set(handle, optionName, optionValue);
+ }
+ else
+ {
+ errorCode = Interop.Winsock.setsockopt(
+ handle,
+ optionLevel,
+ optionName,
+ ref optionValue,
+ sizeof(int));
+ }
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
public static SocketError SetSockOpt(SafeSocketHandle handle, SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue)
{
- SocketError errorCode = Interop.Winsock.setsockopt(
- handle,
- optionLevel,
- optionName,
- optionValue,
- optionValue != null ? optionValue.Length : 0);
+ SocketError errorCode;
+ if (optionLevel == SocketOptionLevel.Tcp &&
+ (optionName == SocketOptionName.TcpKeepAliveTime || optionName == SocketOptionName.TcpKeepAliveInterval)
+ && IOControlKeepAlive.IsNeeded)
+ {
+ errorCode = IOControlKeepAlive.Set(handle, optionName, optionValue);
+ }
+ else
+ {
+ errorCode = Interop.Winsock.setsockopt(
+ handle,
+ optionLevel,
+ optionName,
+ optionValue,
+ optionValue != null ? optionValue.Length : 0);
+ }
return errorCode == SocketError.SocketError ? GetLastSocketError() : SocketError.Success;
}
@@ -599,6 +620,14 @@ namespace System.Net.Sockets
public static SocketError GetSockOpt(SafeSocketHandle handle, SocketOptionLevel optionLevel, SocketOptionName optionName, out int optionValue)
{
+ if (optionLevel == SocketOptionLevel.Tcp &&
+ (optionName == SocketOptionName.TcpKeepAliveTime || optionName == SocketOptionName.TcpKeepAliveInterval)
+ && IOControlKeepAlive.IsNeeded)
+ {
+ optionValue = IOControlKeepAlive.Get(handle, optionName);
+ return SocketError.Success;
+ }
+
int optionLength = 4; // sizeof(int)
SocketError errorCode = Interop.Winsock.getsockopt(
handle,
@@ -611,6 +640,14 @@ namespace System.Net.Sockets
public static SocketError GetSockOpt(SafeSocketHandle handle, SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue, ref int optionLength)
{
+ if (optionLevel == SocketOptionLevel.Tcp &&
+ (optionName == SocketOptionName.TcpKeepAliveTime || optionName == SocketOptionName.TcpKeepAliveInterval)
+ && IOControlKeepAlive.IsNeeded)
+ {
+ IOControlKeepAlive.Get(handle, optionName, optionValue, ref optionLength);
+ return SocketError.Success;
+ }
+
SocketError errorCode = Interop.Winsock.getsockopt(
handle,
optionLevel,
diff --git a/src/libraries/System.Net.Sockets/tests/FunctionalTests/KeepAliveTest.netcoreapp.cs b/src/libraries/System.Net.Sockets/tests/FunctionalTests/KeepAliveTest.netcoreapp.cs
index a98051100ee..dbf865cb875 100644
--- a/src/libraries/System.Net.Sockets/tests/FunctionalTests/KeepAliveTest.netcoreapp.cs
+++ b/src/libraries/System.Net.Sockets/tests/FunctionalTests/KeepAliveTest.netcoreapp.cs
@@ -12,6 +12,8 @@ namespace System.Net.Sockets.Tests
private const int RetryCount = 60;
private const int Time = 5;
private const int Interval = 2;
+ private const int WindowsDefaultTime = 7200;
+ private const int WindowsDefaultInterval = 1;
private static bool IsUnixOrWindowsAtLeast1703 =>
!PlatformDetection.IsWindows || PlatformDetection.IsWindows10Version1703OrGreater;
@@ -19,9 +21,6 @@ namespace System.Net.Sockets.Tests
private static bool IsWindowsBelow1703 =>
PlatformDetection.IsWindows && !PlatformDetection.IsWindows10Version1703OrGreater;
- private static bool IsUnixOrWindowsAtLeast1709 =>
- !PlatformDetection.IsWindows || PlatformDetection.IsWindows10Version1709OrGreater;
-
private static bool IsWindowsBelow1709 =>
PlatformDetection.IsWindows && !PlatformDetection.IsWindows10Version1709OrGreater;
@@ -45,7 +44,7 @@ namespace System.Net.Sockets.Tests
}
[ConditionalFact(typeof(KeepAliveTest), nameof(IsUnixOrWindowsAtLeast1703))]
- public void Socket_Set_KeepAlive_RetryCount_Success()
+ public void Socket_KeepAlive_RetryCount_Success()
{
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
@@ -55,7 +54,7 @@ namespace System.Net.Sockets.Tests
}
[ConditionalFact(typeof(KeepAliveTest), nameof(IsWindowsBelow1703))]
- public void Socket_Set_KeepAlive_RetryCount_Failure()
+ public void Socket_KeepAlive_RetryCount_Failure()
{
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
@@ -65,7 +64,7 @@ namespace System.Net.Sockets.Tests
}
[Fact]
- public void Socket_Set_KeepAlive_Time_Success()
+ public void Socket_KeepAlive_Time()
{
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
@@ -74,8 +73,8 @@ namespace System.Net.Sockets.Tests
}
}
- [ConditionalFact(typeof(KeepAliveTest), nameof(IsUnixOrWindowsAtLeast1709))]
- public void Socket_Set_KeepAlive_Interval_Success()
+ [Fact]
+ public void Socket_KeepAlive_Interval()
{
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
@@ -85,12 +84,117 @@ namespace System.Net.Sockets.Tests
}
[ConditionalFact(typeof(KeepAliveTest), nameof(IsWindowsBelow1709))]
- public void Socket_Set_KeepAlive_Interval_Failure()
+ public void Socket_KeepAlive_Time_And_Interval()
{
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
- Assert.Throws(() => socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, Interval));
- Assert.Throws(() => socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval));
+ Assert.Equal(WindowsDefaultTime, (int)socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime));
+ Assert.Equal(WindowsDefaultInterval, (int)socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval));
+
+ socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, Time);
+ Assert.Equal(Time, (int)socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime));
+ Assert.Equal(WindowsDefaultInterval, (int)socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval));
+
+ socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, Interval);
+ Assert.Equal(Time, (int)socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime));
+ Assert.Equal(Interval, (int)socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval));
+ }
+ }
+
+ [ConditionalFact(typeof(KeepAliveTest), nameof(IsWindowsBelow1709))]
+ public void Socket_KeepAlive_Interval_And_Time()
+ {
+ using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
+ {
+ Assert.Equal(WindowsDefaultTime, (int)socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime));
+ Assert.Equal(WindowsDefaultInterval, (int)socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval));
+
+ socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, Interval);
+ Assert.Equal(WindowsDefaultTime, (int)socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime));
+ Assert.Equal(Interval, (int)socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval));
+
+ socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, Time);
+ Assert.Equal(Time, (int)socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime));
+ Assert.Equal(Interval, (int)socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval));
+ }
+ }
+
+ [Fact]
+ public void Socket_Get_KeepAlive_Time_AsByteArray_OptionLengthZero_Failure()
+ {
+ using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
+ {
+ Assert.Throws(() => socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, 0));
+ }
+ }
+
+ [Fact]
+ public void Socket_Get_KeepAlive_Time_AsByteArray_BufferNull_Failure()
+ {
+ using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
+ {
+ byte[] bufferNull = null;
+ Assert.Throws(() => socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, bufferNull));
+ }
+ }
+
+ [Fact]
+ public void Socket_Get_KeepAlive_Time_AsByteArray_BufferLengthZero_Failure()
+ {
+ using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
+ {
+ byte[] bufferLenghtZero = new byte[0];
+ Assert.Throws(() => socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, bufferLenghtZero));
+ }
+ }
+
+ [Fact]
+ public void Socket_Get_KeepAlive_Time_AsByteArray_BufferShort_Failure()
+ {
+ using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
+ {
+ byte[] bufferShort = new byte[1];
+ Assert.Throws(() => socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, bufferShort));
+ }
+ }
+
+ [Fact]
+ public void Socket_Set_KeepAlive_Time_AsByteArray_BufferNull_Failure()
+ {
+ using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
+ {
+ byte[] bufferNull = null;
+ Assert.Throws(() => socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, bufferNull));
+ }
+ }
+
+ [Fact]
+ public void Socket_Set_KeepAlive_Time_AsByteArray_BufferLengthZero_Failure()
+ {
+ using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
+ {
+ byte[] bufferLenghtZero = new byte[0];
+ Assert.Throws(() => socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, bufferLenghtZero));
+ }
+ }
+
+ [Fact]
+ public void Socket_Set_KeepAlive_Time_AsByteArray_BufferShort_Failure()
+ {
+ using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
+ {
+ byte[] bufferShort = new byte[1];
+ Assert.Throws(() => socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, bufferShort));
+ }
+ }
+
+ [Fact]
+ public void Socket_KeepAlive_Time_AsByteArray_Success()
+ {
+ using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
+ {
+ socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, BitConverter.GetBytes(Time));
+ Assert.Equal(Time, BitConverter.ToInt32(socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, sizeof(int)), 0));
}
}
}