Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

.NET Remoting에서 서비스 호출 시 SYN_SENT로 남는 현상

TCP 상태 다이어그램에 보면,

[출처: https://www.cisco.com/c/en/us/about/press/internet-protocol-journal/back-issues/table-contents-34/syn-flooding-attacks.html]
tcp_connect_1.jpg

SYN_SENT는 연결을 시도한 측에서 SYN 패킷을 보낸 후 대상이 ACK로 반응하기까지의 상태입니다. 다른 말로 하면, ACK 받기 전까지는 connect 한 측의 소켓이 SYN_SENT로 계속 머무른다는 것입니다. 이것을 재현하는 간단한 방법은, 서버 측 소켓에 backlog 값을 작게 주어 Accept 후 지연 시간을 주면,

using (_serverSocket = CreateServerSocket())
{
    _serverSocket.Listen(1);

    while (_serverSocket != null)
    {
        WriteLog("accept...");
        using (Socket clntSocket = _serverSocket.Accept())
        {
            Thread.Sleep(1000 * 60 * 5);
            clntSocket.Close();
        }
    }
}

클라이언트에서 접속 시,

static void Main(string[] args)
{
    while (true)
    {
        Thread t2 = new Thread(clntSockFunc);
        t2.Start();

        Console.WriteLine("Press any key to continue...");
        Console.ReadLine();
    }
}

private static void clntSockFunc(object obj)
{
    try
    {
        using (var socket = CreateClientSocket())
        {
            IPEndPoint ipEp = new IPEndPoint(IPAddress.Loopback, 57102);
            socket.Connect(ipEp);

            socket.Close();
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

처음 한 번의 접속은 Accept를 타게 되고, 이후 한 번은 Listen(1)로 인해 큐에 담기고 3번째 접속부터 다음과 같은 예외가 발생합니다.

System.Net.Sockets.SocketException (0x80004005): No connection could be made because the target machine actively refused it 127.0.0.1:57102
   at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.Sockets.Socket.Connect(EndPoint remoteEP)
   at Program.clntSockFunc(Object obj) in c:\temp\ConsoleApp2\Program.cs:line 31

그리고 위와 같은 오류가 발생하기 전, ^^ 재빠르게 netstat 명령어로 확인하면 다음과 같이 SYN_SENT를 볼 수 있습니다.

C:\Windows\System32> netstat -ano | findstr 57102
  TCP    127.0.0.1:2981         127.0.0.1:57102        ESTABLISHED     32564
  TCP    127.0.0.1:2983         127.0.0.1:57102        ESTABLISHED     32564
  TCP    127.0.0.1:2984         127.0.0.1:57102        SYN_SENT        32564
  TCP    127.0.0.1:57102        0.0.0.0:0              LISTENING       38696
  TCP    127.0.0.1:57102        127.0.0.1:2981         ESTABLISHED     38696
  TCP    127.0.0.1:57102        127.0.0.1:2983         ESTABLISHED     38696

또는 서버 측 대응 소켓이 없는 상태에서 클라이언트가 아무 데나 연결을 시도하면 역시 동일한 0x80004005 예외가 발생하고 그때도 잠시 SYN_SENT를 볼 수 있습니다. TIME_WAIT 과는 달리 삭제까지 별도로 대기 시간이 필요 없기 때문에 아주 잠시 SYN_SENT가 발생하므로 현업에서는 잘 볼 수 없습니다.




재미있는 것은, 이런 현상이 Windows Server 2008 x86 운영체제에서 .NET Remoting을 열었을 때 접속하려는 클라이언트 측에서 발생했습니다. SYN_SENT가 쌓이는데 시간이 지나도 끊어지지 않는다는 특징이 있습니다. 그래서 Socket.Connect를 호출한 측의 스레드가 블로킹되어 서비스 장애까지 간 것입니다.

재현 코드는 간단하게 .NET Remoing 서버를 다음과 같이 만들고,

using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;

class Program
{
    static TcpChannel tcpChannel;

    static void Main(string[] args)
    {
        RunServer();

        Console.WriteLine("Prees any key to run client...");
        Console.ReadLine();
    }

    static void RunServer()
    {
        try
        {
            /*
            Server Channel Properties
            ; https://learn.microsoft.com/en-us/previous-versions/dotnet/netframework-4.0/bb397831(v=vs.100)
            */
            System.Collections.IDictionary tcpProperties = new System.Collections.Hashtable();
            tcpProperties["port"] = HWConfig.TcpChannelPort;

            BinaryServerFormatterSinkProvider tcpServerProv = new BinaryServerFormatterSinkProvider();
            tcpServerProv.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Low;

            tcpChannel = new TcpChannel(tcpProperties, null, tcpServerProv);
            System.Diagnostics.Trace.WriteLine("TcpChannelPort is acquired!");

            ChannelServices.RegisterChannel(tcpChannel, false);
            RemotingConfiguration.RegisterWellKnownServiceType(typeof(HWSingleton), "HWSingleton", WellKnownObjectMode.Singleton);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
}

클라이언트 측은 이렇습니다.

using System;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;

class Program
{
    static void Main(string[] args)
    {
        string tcpServer = string.Format("tcp://localhost:{0}/HWSingleton", HWConfig.TcpChannelPort);
        Console.WriteLine(tcpServer);
        RegisterClient();

        HWSingleton hwSingleton = (HWSingleton)Activator.GetObject(typeof(HWSingleton), tcpServer);
        Console.WriteLine(hwSingleton.Echo("Hello"));
    }

    private static void RegisterClient()
    {
        /*
        Client Channel Properties
        ; https://learn.microsoft.com/en-us/previous-versions/dotnet/netframework-4.0/bb397839(v=vs.100)
        */

        System.Collections.IDictionary tcpProperties = new System.Collections.Hashtable();
        BinaryServerFormatterSinkProvider tcpServerProv = new BinaryServerFormatterSinkProvider();
        tcpServerProv.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Low;
        TcpChannel tcpChannel = new TcpChannel(tcpProperties, null, tcpServerProv);

        ChannelServices.RegisterChannel(tcpChannel, false);
    }
}

이렇게 하고 실행했더니, 다른 컴퓨터에서는 괜찮은데 유독 Windows Server 2008 x86에서만 클라이언트 측의 접속이 SYN_SENT로 머무르면서 절대 소켓 연결 시도가 끊기질 않습니다.




결국 해결 방법은 못 찾았습니다. 재미있는 것은 해당 시스템의 Tcpip 관련 레지스트리(HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters) 설정이 좀 이상했다는 점입니다. 가령 다음과 같은 값들이 그랬습니다.

TcpTimedWaitDelay ffffffff
TcpFinWait2Delay ffffffff
KeepAliveInterval ffffffff
KeepAliveTime ffffffff
EnablePMTUDiscovery ff
TcpMaxDataRetransmissions ff

아무래도 Tcpip 관련 옵션들에서 어떤 문제가 발생한 듯싶은데 저런 값들을 다른 시스템에 맞춰 값을 조절하거나 삭제를 하기도 했지만 저 문제가 없어지지는 않았습니다.

그런데, 재미있는 점이 하나 있었다면 접속 측에서 "localhost"가 아닌 IP 주소로 접속(예: 127.0.0.1)하면 잘 되었습니다. 그래서 HOSTS 파일의 localhost 등록을 명시적으로 임시 설정하고,

127.0.0.1 localhost

소스 코드의 접속 관련 코드들에서 "localhost"를 "127.0.0.1"로 바꾼 후 HOSTS 파일을 다시 원복하는 것으로 문제를 우회 해결했습니다. (다행히 테스트 서버에서 발생한 문제였습니다. ^^)

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




참고로, .NET Remoting은 이제 역사의 뒤안길로 사라지는 기술이 되었습니다. 마이크로소프트는 향후 .NET 5로의 통합에서 더 이상 .NET Remoting(뿐만 아니라 WCF까지도!)을 지원하지 않기로 했으며 그 대체재로 gRPC를 추가하기로 결정했습니다.




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

[연관 글]






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

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

비밀번호

댓글 작성자
 




... 16  17  18  19  20  [21]  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13103정성태7/22/20227222오류 유형: 818. WSL - systemd-genie와 관련한 2가지(systemd-remount-fs.service, multipathd.socket) 에러
13102정성태7/19/20226631.NET Framework: 2033. .NET Core/5+에서는 구할 수 없는 HttpRuntime.AppDomainAppId
13101정성태7/15/202215493도서: 시작하세요! C# 10 프로그래밍
13100정성태7/15/20227995.NET Framework: 2032. C# 11 - shift 연산자 재정의에 대한 제약 완화 (Relaxing Shift Operator)
13099정성태7/14/20227863.NET Framework: 2031. C# 11 - 사용자 정의 checked 연산자파일 다운로드1
13098정성태7/13/20226144개발 환경 구성: 647. Azure - scale-out 상태의 App Service에서 특정 인스턴스에 요청을 보내는 방법 [1]
13097정성태7/12/20225534오류 유형: 817. Golang - binary.Read: invalid type int32
13096정성태7/8/20228311.NET Framework: 2030. C# 11 - UTF-8 문자열 리터럴
13095정성태7/7/20226408Windows: 208. AD 도메인에 참여하지 않은 컴퓨터에서 Kerberos 인증을 사용하는 방법
13094정성태7/6/20226129오류 유형: 816. Golang - "short write" 오류 원인
13093정성태7/5/20227057.NET Framework: 2029. C# - HttpWebRequest로 localhost 접속 시 2초 이상 지연
13092정성태7/3/20227998.NET Framework: 2028. C# - HttpWebRequest의 POST 동작 방식파일 다운로드1
13091정성태7/3/20226794.NET Framework: 2027. C# - IPv4, IPv6를 모두 지원하는 서버 소켓 생성 방법
13090정성태6/29/20225966오류 유형: 815. PyPI에 업로드한 패키지가 반영이 안 되는 경우
13089정성태6/28/20226428개발 환경 구성: 646. HOSTS 파일 변경 시 Edge 브라우저에 반영하는 방법
13088정성태6/27/20225525개발 환경 구성: 645. "Developer Command Prompt for VS 2022" 명령행 환경의 폰트를 바꾸는 방법
13087정성태6/23/20228502스크립트: 41. 파이썬 - FastAPI / uvicorn 호스팅 환경에서 asyncio 사용하는 방법 [1]
13086정성태6/22/20227921.NET Framework: 2026. C# 11 - 문자열 보간 개선 2가지파일 다운로드1
13085정성태6/22/20227992.NET Framework: 2025. C# 11 - 원시 문자열 리터럴(raw string literals)파일 다운로드1
13084정성태6/21/20226620개발 환경 구성: 644. Windows - 파이썬 2.7을 msi 설치 없이 구성하는 방법
13083정성태6/20/20227229.NET Framework: 2024. .NET 7에 도입된 GC의 메모리 해제에 대한 segment와 region의 차이점 [2]
13082정성태6/19/20226262.NET Framework: 2023. C# - Process의 I/O 사용량을 보여주는 GetProcessIoCounters Win32 API파일 다운로드1
13081정성태6/17/20226326.NET Framework: 2022. C# - .NET 7 Preview 5 신규 기능 - System.IO.Stream ReadExactly / ReadAtLeast파일 다운로드1
13080정성태6/17/20226939개발 환경 구성: 643. Visual Studio 2022 17.2 버전에서 C# 11 또는 .NET 7.0 preview 적용
13079정성태6/17/20224612오류 유형: 814. 파이썬 - Error: The file/path provided (...) does not appear to exist
13078정성태6/16/20226655.NET Framework: 2021. WPF - UI Thread와 Render Thread파일 다운로드1
... 16  17  18  19  20  [21]  22  23  24  25  26  27  28  29  30  ...