Microsoft MVP성태의 닷넷 이야기
닷넷: 2204. C# - TCP KeepAlive에 새로 추가된 Retry 옵션 [링크 복사], [링크+제목 복사],
조회: 10768
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 2개 있습니다.)
(시리즈 글이 6개 있습니다.)
.NET Framework: 487. Socket.Receive 메서드의 SocketFlags.Peek 동작을 이용해 소켓 연결 유무를 확인?
; https://www.sysnet.pe.kr/2/0/1824

.NET Framework: 488. TCP 소켓 연결의 해제를 알 수 있는 방법
; https://www.sysnet.pe.kr/2/0/1825

닷넷: 2204. C# - TCP KeepAlive에 새로 추가된 Retry 옵션
; https://www.sysnet.pe.kr/2/0/13531

닷넷: 2206. C# - TCP KeepAlive의 서버 측 구현
; https://www.sysnet.pe.kr/2/0/13533

Windows: 255. (디버거의 영향 등으로) 대상 프로세스가 멈추면 Socket KeepAlive로 연결이 끊길까요?
; https://www.sysnet.pe.kr/2/0/13546

Windows: 256. C# - Server socket이 닫히면 Accept 시켰던 자식 소켓이 닫힐까요?
; https://www.sysnet.pe.kr/2/0/13550




C# - TCP KeepAlive에 새로 추가된 Retry 옵션

예전 글에서,

TCP 소켓 연결의 해제를 알 수 있는 방법
; https://www.sysnet.pe.kr/2/0/1825

Socket.IOControl 메서드를 이용해 KeepAlive를 제어하는 방법을 소개했습니다. 그때 소개한 제어 방법은,

int size = sizeof(UInt32);
byte[] inArray = new byte[size * 3]; // 12바이트 할당
// ...[생략]...
_socket.IOControl(IOControlCode.KeepAliveValues, inArray, null);

IOControlCode.KeepAliveValues 옵션과 함께 해당 설정을 담은 버퍼값을 이용하고 있습니다. 버퍼값의 구조는, Windows 운영체제에서 구현한 Socket의 의존성이 발생하는데요, Windows의 경우 구조체는 다음과 같습니다.

// SIO_KEEPALIVE_VALS Control Code
// https://learn.microsoft.com/en-us/windows/win32/winsock/sio-keepalive-vals

/* Argument structure for SIO_KEEPALIVE_VALS */
struct tcp_keepalive {
    u_long  onoff;
    u_long  keepalivetime;
    u_long  keepaliveinterval;
};

닷넷도 저 형식에 따라 값을 설정해야만 KeepAlive 설정이 동작하게 됩니다.




그런데, 최근에 아래의 소스 코드를 보면서,

SuperSimpleTcp/src/SuperSimpleTcp/SimpleTcpClient.cs
; https://github.com/jchristn/SuperSimpleTcp/blob/master/src/SuperSimpleTcp/SimpleTcpClient.cs#L1125

#if NETCOREAPP3_1_OR_GREATER || NET6_0_OR_GREATER

    // NETCOREAPP3_1_OR_GREATER catches .NET 5.0

    _client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
    _client.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, _keepalive.TcpKeepAliveTime);
    _client.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, _keepalive.TcpKeepAliveInterval);

    // Windows 10 version 1703 or later

    if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
        && Environment.OSVersion.Version >= new Version(10, 0, 15063))
    {
        _client.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveRetryCount, _keepalive.TcpKeepAliveRetryCount);
    }

#elif NETFRAMEWORK

    byte[] keepAlive = new byte[12];

    // Turn keepalive on
    Buffer.BlockCopy(BitConverter.GetBytes((uint)1), 0, keepAlive, 0, 4);

    // Set TCP keepalive time
    Buffer.BlockCopy(BitConverter.GetBytes((uint)_keepalive.TcpKeepAliveTimeMilliseconds), 0, keepAlive, 4, 4);

    // Set TCP keepalive interval
    Buffer.BlockCopy(BitConverter.GetBytes((uint)_keepalive.TcpKeepAliveIntervalMilliseconds), 0, keepAlive, 8, 4);

    // Set keepalive settings on the underlying Socket
    _client.Client.IOControl(IOControlCode.KeepAliveValues, keepAlive, null);

#elif NETSTANDARD

#endif

SocketOptionName에 추가된 SocketOptionName.TcpKeepAliveTime, SocketOptionName.TcpKeepAliveInterval, SocketOptionName.TcpKeepAliveRetryCount 3가지 옵션을 알게 되었습니다.

아마도 닷넷에 이렇게 옵션이 있다는 것은 Windows SDK의 C/C++ Header 파일에도 추가되었음을 의미하는데요, 우선 이미 기존에도 있었던 SocketOptionLevel의 Socket/TCP에 해당하는 값들은 C/C++에서 이렇게 대응하고,

[SocketOptionLevel.Socket]
#define SOL_SOCKET      0xffff          /* options for socket level */

[SocketOptionLevel.Tcp]
#define IPPROTO_TCP             6               /* tcp */

그다음 새롭게 추가된 SocketOptionName 3개의 옵션은 다음과 같이 매핑됩니다.

[기존 SocketOptionLevel.Socket 레벨의 KeepAlive - winsock.h]
#define SO_KEEPALIVE    0x0008          /* keep connections alive */

[신규 SocketOptionLevel.Tcp 레벨의 TcpKeepAliveTime]
#define TCP_KEEPALIVE       	 3
#define TCP_KEEPIDLE             TCP_KEEPALIVE

[신규 SocketOptionLevel.Tcp 레벨의 TcpKeepAliveRetryCount]
#define TCP_KEEPCNT              16

[신규 SocketOptionLevel.Tcp 레벨의 TcpKeepAliveInterval]
#define TCP_KEEPINTVL            17

정리하면, 기존에는 Socket Level에서만 SO_KEEPALIVE 옵션으로 KeepAlive 관련 설정을 할 수 있었지만, 이제는 새롭게 TCP Level에서 TCP_KEEPALIVE(TCP_KEEPIDLE), TCP_KEEPINTVL과 함께 완전히 새로운 기능인 TCP_KEEPCNT를 추가 설정할 수 있도록 확장한 것입니다.

이 중에서 TcpKeepAliveRetryCount(TCP_KEEPCNT)가 특히 더 흥미로운데요, 왜냐하면 과거에는 TcpMaxDataRetransmissions라는 값으로 전역 레지스트리 설정(HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\Tcpip\Parameters)을 건드려야만 조정이 가능했기 때문입니다.




그렇다면 당연히 이 옵션들은 특정 운영체제부터 추가되었을 것이라고 짐작할 수 있습니다. 실제로 문서를 보면,

IPPROTO_TCP socket options
; https://learn.microsoft.com/en-us/windows/win32/winsock/ipproto-tcp-socket-options

TCP_KEEPIDLE(TCP_KEEPALIVE)

Gets or sets the number of seconds a TCP connection will remain idle before keepalive probes are sent to the remote.
Note:
This option is available starting with Windows 10, version 1709.

TCP_KEEPINTVL

Gets or sets the number of seconds a TCP connection will wait for a keepalive response before sending another keepalive probe.
Note:
This option is available starting with Windows 10, version 1709.

TCP_KEEPCNT

Gets or sets the number of TCP keep alive probes that will be sent before the connection is terminated. It is illegal to set TCP_KEEPCNT to a value greater than 255.

오히려 기존에 SO_KEEPALIVE로 설정 가능했던 TCP_KEEPALIVE, TCP_KEEPINTVL은 "Windows 10, version 1709"로 나중에 지원을 추가했고, 신규 기능인 TCP_KEEPCNT는 동일 문서의 별도로 정리돼 있는 표에,

Windows support for IPPROTO_TCP options
; https://learn.microsoft.com/en-us/windows/win32/winsock/ipproto-tcp-socket-options#windows-support-for-ipproto_tcp-options

"Starting with Windows 10, version 1703"으로 나옵니다. 약간의 차이는 있지만, 간단하게 Windows 10/Windows Server 2019 이상부터 쓸 수 있는 기능이라고 보면 됩니다.

이에 대해 SuperSimpleTcp/src/SuperSimpleTcp/SimpleTcpClient.cs 코드에는 다음과 같이 버전 제약을 두고 있는데요,

// Windows 10 version 1703 or later

if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
    && Environment.OSVersion.Version >= new Version(10, 0, 15063))
{
    _client.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveRetryCount, _keepalive.TcpKeepAliveRetryCount);
}

Windows Server 2016의 경우 10.0.14393 버전이기 때문에 new Version(10, 0, 15063)에서 걸러지게 됩니다. 만약 이 기능을 Windows Server 2016에서 사용한다면 C#의 경우 SocketException 예외가 발생합니다.

// Windows Server 2016에서 아래의 코드를 실행하면,

socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveRetryCount);

// 예외 발생:
// System.Net.Sockets.SocketException: An unknown, invalid, or unsupported option or level was specified in a getsockopt or setsockopt call
   at System.Net.Sockets.Socket.GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName)

반면, Windows 10 또는 Windows Server 2019에서 실행해 보면 다음과 같은 기본값을 확인할 수 있습니다.

Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

Console.WriteLine($"KeepAlive: {socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive)}");
Console.WriteLine($"TcpKeepAliveTime: {socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime)}");
Console.WriteLine($"TcpKeepAliveInterval: {socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval)}");
Console.WriteLine($"TcpKeepAliveRetryCount: {socket.GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveRetryCount)}");

/* 출력 결과:
KeepAlive: 0
TcpKeepAliveTime: 7200
TcpKeepAliveInterval: 1
TcpKeepAliveRetryCount: 10
*/

따라서 만약 단순히 SocketOptionName.KeepAlive만 활성화시켰다면, 2시간에 한 번씩 KeepAlive 확인을 하다가 그것에 실패하면 이후 1초마다 10번의 확인 신호를 전송하는 식으로 동작합니다. 운이 없다면 2시간 10초 만에 연결 끊김을 감지할 수도 있고, 운이 억수로 좋다면 연결이 끊긴 그 순간이 2시간의 타이밍에 맞춰 발생한다면 약 10초 만에 연결 끊김을 감지할 수도 있습니다.




SuperSimpleTcp/src/SuperSimpleTcp/SimpleTcpClient.cs에서 약간 이해할 수 없는 점이 있다면,

#if NETCOREAPP3_1_OR_GREATER || NET6_0_OR_GREATER

    // NETCOREAPP3_1_OR_GREATER catches .NET 5.0

    _client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
    // ...[생략]...

#elif NETFRAMEWORK

    byte[] keepAlive = new byte[12];

    // ...[생략]...
    _client.Client.IOControl(IOControlCode.KeepAliveValues, keepAlive, null);

#elif NETSTANDARD

#endif

닷넷 코어 3.1 이상인 경우에만 신규 SocketOptionName.KeepAlive, SocketOptionName.TcpKeepAliveInterval, SocketOptionName.TcpKeepAliveRetryCount를 사용하도록 빌드한다는 점입니다. 물론, 해당 enum 값들이 .NET Core 3.1 이상의 BCL에서 정의돼 그런 것일 수도 있지만, 위에서도 설명했듯이 그것들은 단순한 상수 이외의 의미가 없으므로 .NET Framework에서도 동일하게 사용할 수 있습니다. 따라서, 그냥 다음과 같이 합쳐도 무방합니다.

// .NET Framework / .NET Core 공동으로 사용 가능

if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // 윈도우에서만 가능 
{
    if (Environment.OSVersion.Version >= new Version(10, 0, 15063)) // TcpKeepAliveRetryCount까지 설정 가능
    {
        socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
        socket.SetSocketOption(SocketOptionLevel.Tcp, (SocketOptionName)3, 1);
        socket.SetSocketOption(SocketOptionLevel.Tcp, (SocketOptionName)17, 3);
        socket.SetSocketOption(SocketOptionLevel.Tcp, (SocketOptionName)16, 10);
    }
    else // Windows 8 또는 Windows Server 2016 이하에서는 KeepAlive, TcpKeepAliveInterval만 설정 가능
    {
        byte[] keepAlive = new byte[12];

        // Turn keepalive on
        Buffer.BlockCopy(BitConverter.GetBytes((uint)1), 0, keepAlive, 0, 4);

        // Set TCP keepalive time
        Buffer.BlockCopy(BitConverter.GetBytes((uint)_keepalive.TcpKeepAliveTimeMilliseconds), 0, keepAlive, 4, 4);

        // Set TCP keepalive interval
        Buffer.BlockCopy(BitConverter.GetBytes((uint)_keepalive.TcpKeepAliveIntervalMilliseconds), 0, keepAlive, 8, 4);

        // Set keepalive settings on the underlying Socket
        _client.Client.IOControl(IOControlCode.KeepAliveValues, keepAlive, null);
    }
}

그나저나, 실제로 retry 옵션이 잘 동작하는지 테스트를 해볼까요? ^^ 이를 위해 우선 (이런 상황에서 테스트하기 쉬운) VM에 실행해 둘 간단한 서버를 다음과 같이 만들어 두고,

using System.Net.Sockets;
using System.Net;

namespace ConsoleApp1;

internal class Program
{
    static void Main(string[] args)
    {
        int port = 18500;
        Socket listenSocket = new Socket(AddressFamily.InterNetwork,
                                     SocketType.Stream,
                                     ProtocolType.Tcp);

        IPEndPoint ep = new IPEndPoint(IPAddress.Any, port);
        listenSocket.Bind(ep);
        listenSocket.Listen(5);

        while (true)
        {
            Socket clientSocket = listenSocket.Accept();
            Task.Run(() =>
            {
                clientSocket.Send(new byte[4] { 1, 2, 3, 4 });

                try
                {
                    clientSocket.Receive(new byte[4]);
                }
                catch (Exception e)
                {
                }
            });
        }
    }
}

클라이언트는 서버에 연결한 다음, 서버 측의 VM을 Pause 시켰을 때 연결이 끊겼음을 감지하기 위한 Ping 시간을 함께 체크하도록 다음과 같이 만들 수 있습니다.

using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;

namespace ConsoleApp2;

internal class Program
{
    static void Main(string[] args)
    {
        string host = "192.168.100.50"; // VM 서버 IP
        int port = 18500;

        Task.Run(() =>
        {
            bool connected = true;

            while (true)
            {
                Ping ping = new Ping();

                PingOptions options = new PingOptions();
                options.DontFragment = true;

                string data = "test";
                byte[] buffer = ASCIIEncoding.ASCII.GetBytes(data);
                int timeout = 300;

                PingReply reply = ping.Send(IPAddress.Parse(host), timeout, buffer, options);
                bool replied = reply.Status == IPStatus.Success;

                if (connected != replied)
                {
                    connected = replied;
                    Log($"Status changed to {reply.Status}"); // ping이 안 되기 시작한 시간을 남기고,
                }

                Thread.Sleep(32);
            }
        });

        Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
        socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, 1);
        socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, 3);
        socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveRetryCount, 10);

        socket.Connect(host, port);
        Log("Connected");

        int received = socket.Receive(new byte[4]);
        Log("Received");

        try
        {
            socket.Receive(new byte[4]);
            Log("Received");
        }
        catch (Exception ex)
        {
            Log($"Exception thrown: {ex.Message}"); // KeepAlive로 인해 연결이 끊기는 시간을 확인
        }

        socket.Close();

    }

    private static void Log(string text)
    {
        Console.WriteLine($"[{DateTime.Now:mm ss fff}] {text}");
    }
}

자, 이제 서버와 클라이언트를 실행해 두고 VM을 "일시 중지"시키면 다음과 같은 결과를 얻을 수 있습니다.

C:\test> ConsoleApp2.exe
[57 37 176] Connected
[57 37 229] Received
[58 27 205] Status changed to TimedOut
[58 57 810] Exception thrown: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

27초부터 Ping이 안 되고, 57에 KeepAlive로 인해 Receive에서 예외를 반환하고 있으니 대략 30초 만에 연결이 끊겼습니다. 코드에서 설정한 값으로 시간 계산해 본 것과,

TcpKeepAliveTime == 1
TcpKeepAliveInterval == 3
TcpKeepAliveRetryCount == 10

1초마다 KeepAlive를 보내다가 ACK가 안 오면 이후 3초마다 10번에 걸쳐서 Retry 후 그래도 ACK가 없으면 연결을 끊음.

따라서, 1 + (3 * 10) = 31초 내에 연결이 끊김 (30 ~ 31)

크게 다르지 않은 차이입니다. (1초 정도는, KeepAliveTime의 주기와 위에서 제가 만든 Ping 호출의 주기를 감안하면 발생할 수 있는 차이입니다.) 혹시 모르니, 다른 값으로 한 번 더 테스트를 해볼까요? ^^

TcpKeepAliveTime == 20
TcpKeepAliveInterval == 50
TcpKeepAliveRetryCount == 1

20초마다 KeepAlive를 보내다가 ACK가 안 오면 이후 50초마다 1번에 걸쳐서 Retry 후 그래도 ACK가 없으면 연결을 끊음.

따라서, 20 + (50 * 1) = 70초 내에 연결이 끊김 (50 ~ 70)

이번엔 결과가 다음과 같이 나왔습니다.

C:\test> ConsoleApp2.exe
[02 19 402] Connected
[02 19 459] Received
[02 29 199] Status changed to TimedOut
[03 29 475] Exception thrown: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

약 60초에 연결이 끊겼는데요, 역시나 첫 20초의 주기에 어떤 순간이 걸릴지 모르니 대략 비슷하다고 봐야 합니다. 이론상 위의 경우에는 20초의 주기로 인해 운에 따라 50초 ~ 70초 내에 연결이 끊긴다고 봐야 합니다.

참고로, 위의 결과는 .NET Core로 만들든, .NET Framework로 만들든 동일하게 발생합니다. 즉, 닷넷 버전이 중요한 것이 아니고, 해당 프로그램이 실행되는 운영체제의 버전이 중요합니다.

뭐, 대충 이 정도면 대략 감이 오시겠죠. ^^

(첨부 파일은 이 글의 코드를 포함합니다.)





[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 11/7/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 121  122  123  124  125  126  127  [128]  129  130  131  132  133  134  135  ...
NoWriterDateCnt.TitleFile(s)
1855정성태2/10/201520796개발 환경 구성: 256. WebDAV Redirector - Sysinternals 폴더 연결 시 "The network path was not found" 오류 해결 방법
1854정성태2/10/201521768Windows: 104. 폴더는 삭제할 수 없지만, 그 하위 폴더/파일은 생성/삭제/변경하는 보안 설정
1853정성태2/6/201552055웹: 29. 여신금융협회 웹 사이트의 "Netscape 6.0은 지원하지 않습니다." 오류 메시지 [5]
1852정성태2/5/201522465.NET Framework: 492. .NET CLR Memory 성능 카운터의 의미파일 다운로드1
1851정성태2/5/201523395VC++: 88. 하룻밤의 꿈 - 인텔 하스웰의 TSX Instruction 지원 [2]
1850정성태2/4/201544189Windows: 103. 작업 관리자에서의 "Commit size"가 가리키는 메모리의 의미 [4]
1849정성태2/4/201524177기타: 51. DropBox의 CPU 100% 현상 [1]파일 다운로드1
1848정성태2/4/201519410.NET Framework: 491. 닷넷 Generic 타입의 메타 데이터 토큰 값 알아내는 방법 [2]
1847정성태2/3/201522688기타: 50. C# - 윈도우에서 dropbox 동기화 폴더 경로 및 종료하는 방법
1846정성태2/2/201532007Windows: 102. 제어판의 프로그램 추가/삭제 항목을 수동으로 실행하고 싶다면? [1]
1845정성태1/26/201532886Windows: 101. 제어판의 "Windows 자격 증명 관리(Manage your credentials)"를 금지시키는 방법
1844정성태1/26/201530844오류 유형: 269. USB 메모리의 용량이 비정상적으로 보여진다면? [7]
1843정성태1/24/201521902VC++: 87. 무시할 수 없는 Visual C++ 런타임 함수 성능
1842정성태1/23/201544394개발 환경 구성: 255. 노트북 키보드에 없는 BREAK 키를 다른 키로 대체하는 방법
1841정성태1/21/201519374오류 유형: 268. Win32 핸들 관련 CLR4 보안 오류 사례
1840정성태1/8/201527603오류 유형: 267. Visual Studio - CodeLens 사용 시 CPU 100% 현상
1839정성태1/5/201520517디버깅 기술: 69. windbg 분석 사례 - cpu 100% 현상 (2)
1838정성태1/4/201540232기타: 49. 윈도우 내레이터(Narrator) 기능 끄는 방법(윈도우에 파란색의 굵은 테두리 선이 나타난다면?) [4]
1837정성태1/4/201526327디버깅 기술: 68. windbg 분석 사례 - 메모리 부족 [1]
1836정성태1/4/201526342디버깅 기술: 67. windbg - 덤프 파일과 handle 정보
1835정성태1/3/201526818개발 환경 구성: 254. SQL 서버 역시 SSL 3.0/TLS 1.0만을 지원하는 듯!
1834정성태1/3/201551445개발 환경 구성: 253. TLS 1.2를 적용한 IIS 웹 사이트 구성
1833정성태1/3/201527512.NET Framework: 490. System.Data.SqlClient는 SSL 3.0/TLS 1.0만 지원하는 듯! [3]
1832정성태1/2/201520623오류 유형: 266. Azure에 응용 프로그램 게시 중 로그인 오류
1831정성태1/1/201528514디버깅 기술: 66. windbg 분석 사례 - cpu 100% 현상 (1) [1]
1830정성태1/1/201527556오류 유형: 265. svchost.exe 프로세스(IP Helper: IPHLPSVC)의 CPU 100% 현상
... 121  122  123  124  125  126  127  [128]  129  130  131  132  133  134  135  ...