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

비밀번호

댓글 작성자
 




... 46  47  48  49  50  51  [52]  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12341정성태9/23/202010045.NET Framework: 944. C# - 인스턴스가 살아 있어 메모리 누수가 발생하고 있는지 확인하는 방법파일 다운로드1
12340정성태9/23/20209770.NET Framework: 943. WPF - WindowsFormsHost를 담은 윈도우 생성 시 메모리 누수
12339정성태9/21/20209779오류 유형: 655. 코어 모드의 윈도우는 GUI 모드의 윈도우로 교체가 안 됩니다.
12338정성태9/21/20209327오류 유형: 654. 우분투 설치 시 "CHS: Error 2001 reading sector ..." 오류 발생
12337정성태9/21/202010647오류 유형: 653. Windows - Time zone 설정을 바꿔도 반영이 안 되는 경우
12336정성태9/21/202013164.NET Framework: 942. C# - WOL(Wake On Lan) 구현
12335정성태9/21/202022527Linux: 31. 우분투 20.04 초기 설정 - 고정 IP 및 SSH 설치
12334정성태9/21/20207942오류 유형: 652. windbg - !py 확장 명령어 실행 시 "failed to find python interpreter"
12333정성태9/20/20208391.NET Framework: 941. C# - 전위/후위 증감 연산자에 대한 오버로딩 구현 (2)
12332정성태9/18/202010469.NET Framework: 940. C# - Windows Forms ListView와 DataGridView의 예제 코드파일 다운로드1
12331정성태9/18/20209600오류 유형: 651. repadmin /syncall - 0x80090322 The target principal name is incorrect.
12330정성태9/18/202010652.NET Framework: 939. C# - 전위/후위 증감 연산자에 대한 오버로딩 구현 [2]파일 다운로드1
12329정성태9/16/202012552오류 유형: 650. ASUS 메인보드 관련 소프트웨어 설치 후 ArmouryCrate.UserSessionHelper.exe 프로세스 무한 종료 현상
12328정성태9/16/202012779VS.NET IDE: 150. TFS의 이력에서 "Get This Version"과 같은 기능을 Git으로 처리한다면?
12327정성태9/12/202010361.NET Framework: 938. C# - ICS(Internet Connection Sharing) 제어파일 다운로드1
12326정성태9/12/20209855개발 환경 구성: 516. Azure VM의 Network Adapter를 실수로 비활성화한 경우
12325정성태9/12/20209431개발 환경 구성: 515. OpenVPN - 재부팅 후 ICS(Internet Connection Sharing) 기능이 동작 안하는 문제
12324정성태9/11/202010706개발 환경 구성: 514. smigdeploy.exe를 이용한 Windows Server 2016에서 2019로 마이그레이션 방법
12323정성태9/11/20209566오류 유형: 649. Copy Database Wizard - The job failed. Check the event log on the destination server for details.
12322정성태9/11/202010663개발 환경 구성: 513. Azure VM의 RDP 접속 위치 제한 [1]
12321정성태9/11/20208893오류 유형: 648. netsh http add urlacl - Error: 183 Cannot create a file when that file already exists.
12320정성태9/11/202010071개발 환경 구성: 512. RDP(원격 데스크톱) 접속 시 비밀 번호를 한 번 더 입력해야 하는 경우
12319정성태9/10/20209819오류 유형: 647. smigdeploy.exe를 Windows Server 2016에서 실행할 때 .NET Framework 미설치 오류 발생
12318정성태9/9/20209308오류 유형: 646. OpenVPN - "TAP-Windows Adapter V9" 어댑터의 "Network cable unplugged" 현상
12317정성태9/9/202011635개발 환경 구성: 511. Beats용 Kibana 기본 대시 보드 구성 방법
12316정성태9/8/202010068디버깅 기술: 170. WinDbg Preview 버전부터 닷넷 코어 3.0 이후의 메모리 덤프에 대해 sos.dll 자동 로드
... 46  47  48  49  50  51  [52]  53  54  55  56  57  58  59  60  ...