@@ -48,24 +48,27 @@ public static void SetKeepAlive(this Socket socket, uint keepAliveTimeSeconds)
48
48
return ;
49
49
50
50
// If keepAliveTimeSeconds > 0, override keepalive options on the socket
51
- const int keepAliveIntervalMillis = 1000 ;
52
51
#if ! NETCOREAPP3_0
53
52
if ( Utility . IsWindows ( ) )
54
53
{
55
54
// http://stackoverflow.com/a/11834055/1419658
56
55
// Windows takes time in milliseconds
57
56
var keepAliveTimeMillis = keepAliveTimeSeconds > uint . MaxValue / 1000 ? uint . MaxValue : keepAliveTimeSeconds * 1000 ;
58
- var inOptionValues = new byte [ sizeof ( uint ) * 3 ] ;
59
- BitConverter . GetBytes ( ( uint ) 1 ) . CopyTo ( inOptionValues , 0 ) ;
60
- BitConverter . GetBytes ( keepAliveTimeMillis ) . CopyTo ( inOptionValues , sizeof ( uint ) ) ;
61
- BitConverter . GetBytes ( keepAliveIntervalMillis ) . CopyTo ( inOptionValues , sizeof ( uint ) * 2 ) ;
57
+ var inOptionValues = new byte [ 12 ] ;
58
+ inOptionValues [ 0 ] = 1 ;
59
+ inOptionValues [ 4 ] = ( byte ) ( keepAliveTimeMillis & 0xFF ) ;
60
+ inOptionValues [ 5 ] = ( byte ) ( ( keepAliveTimeMillis >> 8 ) & 0xFF ) ;
61
+ inOptionValues [ 6 ] = ( byte ) ( ( keepAliveTimeMillis >> 16 ) & 0xFF ) ;
62
+ inOptionValues [ 7 ] = ( byte ) ( ( keepAliveTimeMillis >> 24 ) & 0xFF ) ;
63
+ inOptionValues [ 8 ] = 0xE8 ;
64
+ inOptionValues [ 9 ] = 0x03 ;
62
65
socket . IOControl ( IOControlCode . KeepAliveValues , inOptionValues , null ) ;
63
66
}
64
67
// Unix not supported: The appropriate socket options to set Keepalive options are not exposd in .NET
65
68
// https://github.com/dotnet/corefx/issues/14237
66
69
// Unix will still respect the OS Default Keepalive settings
67
70
#else
68
- socket . SetSocketOption ( SocketOptionLevel . Tcp , SocketOptionName . TcpKeepAliveInterval , keepAliveIntervalMillis / 1000 ) ;
71
+ socket . SetSocketOption ( SocketOptionLevel . Tcp , SocketOptionName . TcpKeepAliveInterval , 1 ) ;
69
72
socket . SetSocketOption ( SocketOptionLevel . Tcp , SocketOptionName . TcpKeepAliveTime , ( int ) keepAliveTimeSeconds ) ;
70
73
#endif
71
74
}
0 commit comments