| 1 |
using System; |
| 2 |
using System.Collections.Generic; |
| 3 |
using System.Linq; |
| 4 |
using System.Net.Sockets; |
| 5 |
using System.Runtime.InteropServices; |
| 6 |
using System.Text; |
| 7 |
using System.Threading.Tasks; |
| 8 |
|
| 9 |
namespace TELTest { |
| 10 |
public static class SocketExtensions { |
| 11 |
public static void SetSocketKeepAliveValues(this Socket instance, int KeepAliveTime, int KeepAliveInterval) { |
| 12 |
//KeepAliveTime: default value is 2hr |
| 13 |
//KeepAliveInterval: default value is 1s and Detect 5 times |
| 14 |
|
| 15 |
//the native structure |
| 16 |
//struct tcp_keepalive { |
| 17 |
//ULONG onoff; |
| 18 |
//ULONG keepalivetime; |
| 19 |
//ULONG keepaliveinterval; |
| 20 |
//}; |
| 21 |
|
| 22 |
int size = Marshal.SizeOf(new uint()); |
| 23 |
byte[] inOptionValues = new byte[size * 3]; // 4 * 3 = 12 |
| 24 |
bool OnOff = true; |
| 25 |
|
| 26 |
BitConverter.GetBytes((uint)(OnOff ? 1 : 0)).CopyTo(inOptionValues, 0); |
| 27 |
BitConverter.GetBytes((uint)KeepAliveTime).CopyTo(inOptionValues, size); |
| 28 |
BitConverter.GetBytes((uint)KeepAliveInterval).CopyTo(inOptionValues, size * 2); |
| 29 |
|
| 30 |
instance.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null); |
| 31 |
} |
| 32 |
} |
| 33 |
} |