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

비밀번호

댓글 작성자
 




... 31  32  33  34  [35]  36  37  38  39  40  41  42  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
12754정성태8/5/20218094오류 유형: 750. manage.py - Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
12753정성태8/5/20218362오류 유형: 749. PyCharm - Error: Django is not importable in this environment
12752정성태8/4/20216440개발 환경 구성: 592. JetBrains의 IDE(예를 들어, PyCharm)에서 Visual Studio 키보드 매핑 적용
12751정성태8/4/20219517개발 환경 구성: 591. Windows 10 WSL2 환경에서 docker-compose 빌드하는 방법
12750정성태8/3/20216302디버깅 기술: 181. windbg - 콜 스택의 "Call Site" 오프셋 값이 가리키는 위치
12749정성태8/2/20215720개발 환경 구성: 590. Visual Studio 2017부터 단위 테스트에 DataRow 특성 지원
12748정성태8/2/20216322개발 환경 구성: 589. Azure Active Directory - tenant의 관리자(admin) 계정 로그인 방법
12747정성태8/1/20216926오류 유형: 748. 오류 기록 - MICROSOFT GRAPH – HOW TO IMPLEMENT IAUTHENTICATIONPROVIDER파일 다운로드1
12746정성태7/31/20218945개발 환경 구성: 588. 네트워크 장비 환경을 시뮬레이션하는 Packet Tracer 프로그램 소개
12745정성태7/31/20216776개발 환경 구성: 587. Azure Active Directory - tenant의 관리자 계정 로그인 방법
12744정성태7/30/20217385개발 환경 구성: 586. Azure Active Directory에 연결된 App 목록을 확인하는 방법?
12743정성태7/30/20218064.NET Framework: 1083. Azure Active Directory - 외부 Token Cache 저장소를 사용하는 방법파일 다운로드1
12742정성태7/30/20217326개발 환경 구성: 585. Azure AD 인증을 위한 사용자 인증 유형
12741정성태7/29/20218535.NET Framework: 1082. Azure Active Directory - Microsoft Graph API 호출 방법파일 다운로드1
12740정성태7/29/20217215오류 유형: 747. SharePoint - InvalidOperationException 0x80131509
12739정성태7/28/20217169오류 유형: 746. Azure Active Directory - IDW10106: The 'ClientId' option must be provided.
12738정성태7/28/20217753오류 유형: 745. Azure Active Directory - Client credential flows must have a scope value with /.default suffixed to the resource identifier (application ID URI).
12737정성태7/28/20216721오류 유형: 744. Azure Active Directory - The resource principal named api://...[client_id]... was not found in the tenant
12736정성태7/28/20217224오류 유형: 743. Active Azure Directory에서 "API permissions"의 권한 설정이 "Not granted for ..."로 나오는 문제
12735정성태7/27/20217755.NET Framework: 1081. C# - Azure AD 인증을 지원하는 데스크톱 애플리케이션 예제(Windows Forms) [2]파일 다운로드1
12734정성태7/26/202123753스크립트: 20. 특정 단어로 시작하거나/끝나는 문자열을 포함/제외하는 정규 표현식 - Look-around
12733정성태7/23/202111096.NET Framework: 1081. Self-Contained/SingleFile 유형의 .NET Core/5+ 실행 파일을 임베딩한다면? [1]파일 다운로드2
12732정성태7/23/20216383오류 유형: 742. SharePoint - The super user account utilized by the cache is not configured.
12731정성태7/23/20217529개발 환경 구성: 584. Add Internal URLs 화면에서 "Save" 버튼이 비활성화 된 경우
12730정성태7/23/20219052개발 환경 구성: 583. Visual Studio Code - Go 코드에서 입력을 받는 경우
12729정성태7/22/20218001.NET Framework: 1080. xUnit 단위 테스트에 메서드/클래스 수준의 문맥 제공 - Fixture
... 31  32  33  34  [35]  36  37  38  39  40  41  42  43  44  45  ...