Microsoft MVP성태의 닷넷 이야기
.NET Framework: 983. C# - TIME_WAIT과 ephemeral port 재사용 [링크 복사], [링크+제목 복사]
조회: 10198
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 2개 있습니다.)
(시리즈 글이 9개 있습니다.)
개발 환경 구성: 92. 윈도우 서버 환경에서, 최대 생성 가능한 소켓(socket) 연결 수는 얼마일까?
; https://www.sysnet.pe.kr/2/0/964

Windows: 175. 윈도우 환경에서 클라이언트 소켓의 최대 접속 수
; https://www.sysnet.pe.kr/2/0/12350

Windows: 178. 윈도우 환경에서 클라이언트 소켓의 최대 접속 수 (2) - SO_REUSEADDR
; https://www.sysnet.pe.kr/2/0/12432

Windows: 179. 윈도우 환경에서 클라이언트 소켓의 최대 접속 수 (3) - SO_PORT_SCALABILITY
; https://www.sysnet.pe.kr/2/0/12433

Windows: 181. 윈도우 환경에서 클라이언트 소켓의 최대 접속 수 (4) - ReuseUnicastPort를 이용한 포트 고갈 문제 해결
; https://www.sysnet.pe.kr/2/0/12435

.NET Framework: 981. C# - HttpWebRequest, WebClient와 ephemeral port 재사용
; https://www.sysnet.pe.kr/2/0/12448

.NET Framework: 982. C# - HttpClient에서의 ephemeral port 재사용
; https://www.sysnet.pe.kr/2/0/12449

.NET Framework: 983. C# - TIME_WAIT과 ephemeral port 재사용
; https://www.sysnet.pe.kr/2/0/12450

Linux: 35. C# - 리눅스 환경에서 클라이언트 소켓의 ephemeral port 재사용
; https://www.sysnet.pe.kr/2/0/12459




C# - TIME_WAIT과 ephemeral port 재사용

예전에 소켓 상태 테스트를 하면서,

코드로 재현하는 소켓 상태(FIN_WAIT1, FIN_WAIT2, TIME_WAIT, CLOSE_WAIT, LAST_WAIT)
; https://www.sysnet.pe.kr/2/0/1334

맨 처음 closesocket을 호출한 측(만약, 둘이 동시에 closesocket을 호출하면 양측 모두)에 TIME_WAIT 상태로 2MSL(maximum segment lifetime) 시간 동안 유지된다고 했는데요, 그때도 언급했지만 2MSL 시간이라는 게 참 애매합니다. 이에 대해 직접적으로 설명한 공식 문서는 찾을 수 없고, 연관된 것들에서 그 흔적을 볼 수 있는데요,

TcpTimedWaitDelay
LPFN_CONNECTEX callback function (mswsock.h)
; https://docs.microsoft.com/en-us/windows/win32/api/mswsock/nc-mswsock-lpfn_connectex

By default, the MSL is defined to be 120 seconds. The TcpTimedWaitDelay registry setting defaults to a value 240 seconds, which represents 2 times the maximum segment lifetime of 120 seconds or 4 minutes.


SystemConfig_Network class
; https://docs.microsoft.com/en-us/windows/win32/etw/systemconfig-network

RFC 793 published by the IETF requires that TCP maintains a closed connection for an interval at least equal to twice the maximum segment lifetime (2MSL) of the network. When a connection is released, its socket pair and TCP control block (TCB) can be used to support another connection. By default, the MSL is defined to be 120 seconds, and the value of this entry is equal to two MSLs, or 4 minutes. For more information, see RFC 793.


MSL의 시간이 120초, 따라서 2MSL로 TcpTimedWaitDelay가 정해졌으니 4분인데, 엉뚱하게도 biztalk 문서에 보면,

Settings that can be Modified to Improve Network Performance
; https://docs.microsoft.com/en-us/biztalk/technical-guides/settings-that-can-be-modified-to-improve-network-performance

120으로 기본값이 설정되었다고 하며 실제로 테스트해보면 Windows 10에서 2분(120)이 맞습니다.

자, 그럼 TIME_WAIT 상태로 머무는 동안 점유된 포트는 이후 어떻게 소켓 통신에 영향을 미치게 될까요? 기왕에 이번 테스트를 하면서 환경도 구축했으니,

경로: HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\Tcpip\Parameters
이름: MaxUserPort
타입: DWORD
값: 7d0 (2000)

DynamicPortRangeStartPort       : 1024
DynamicPortRangeNumberOfPorts   : 977
AutoReusePortRangeStartPort     : 15000
AutoReusePortRangeNumberOfPorts : 1000

^^ 마저 결과를 확인해 보겠습니다.




어차피 서버 측은 5-tuple 구분을 하므로, 여기서 궁금한 것은 클라이언트 측의 TIME_WAIT 상태에 따른 포트 재사용 문제입니다. 따라서, 다음과 같이 서버와 클라이언트 코드를 구성해,

// 서버 예제 코드

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace ConsoleApp1
{
    class Program
    {
        static List<TcpClient> _cla17000 = new List<TcpClient>();
        static List<TcpClient> _cla17001 = new List<TcpClient>();

        static void Main(string[] args)
        {
            Thread t = new Thread(CountFunc);
            t.IsBackground = true;
            t.Start();

            bool active1 = true;
            bool active2 = true;

            if (args.Length >= 1)
            {
                if (args[0] == "1")
                {
                    active2 = false;
                }
                else if (args[0] == "2")
                {
                    active1 = false;
                }
            }

            if (active1 == true)
            {
                Thread t17000 = new Thread(acceptFunc);
                t17000.IsBackground = true;
                t17000.Start(17000);
            }

            if (active2 == true)
            {
                Thread t17001 = new Thread(acceptFunc);
                t17001.IsBackground = true;
                t17001.Start(17001);
            }

            while (true)
            {
                string txt = Console.ReadLine();
                if (txt == "1")
                {
                    foreach (var cla in _cla17000)
                    {
                        try
                        {
                            cla.Close();
                        } catch { }
                    }

                    _cla17000.Clear();
                }

                Console.WriteLine(DateTime.Now);
            }
        }

        private static void acceptFunc(object objPort)
        {
            int port = (int)objPort;

            TcpListener svr = new TcpListener(IPAddress.Any, port);
            {
                svr.Start();

                while (true)
                {
                    TcpClient client = svr.AcceptTcpClient();

                    if (port == 17000)
                    {
                        _cla17000.Add(client);
                    }
                    else
                    {
                        _cla17001.Add(client);
                    }
                }
            }
        }

        private static void CountFunc()
        {
            while (true)
            {
                Console.WriteLine($"# of 17000: {_cla17000.Count}, 17001: {_cla17001.Count}");
                Thread.Sleep(5000);
            }
        }
    }
}

// 클라이언트 예제 코드

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            string ipAddr = args[0];
            int port = int.Parse(args[1]);
            int numberOf = int.Parse(args[2]);

            List<Socket> clients1 = new List<Socket>();

            try
            {
                for (int i = 0; i < numberOf; i++)
                {
                    try
                    {
                        Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                        client.Bind(new IPEndPoint(IPAddress.Any, 0));
                        client.Connect(ipAddr, port);

                        Console.WriteLine($"{client.LocalEndPoint}-{client.RemoteEndPoint}");

                        clients1.Add(client);
                    }
                    catch { }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            Console.WriteLine($"{clients1.Count}, {Process.GetCurrentProcess().Id}");

            while (true)
            {
                string txt = Console.ReadLine();
                if (txt == "1")
                {
                    foreach (var cla in clients1)
                    {
                        cla.Close();
                    }
                }
                Console.ReadLine();
            }
        }
    }
}

실행해 보면, 클라이언트 측의 Bind로 인해 DynamicPortRangeStartPort 영역의 포트를 사용하게 되고 Reuse를 하지 못해 지난번처럼 DynamicPortRangeNumberOfPorts 즈음에서 더 이상 접속이 안 됩니다.

C:\temp2> ConsoleApp1.exe
# of 17000: 0, 15001: 0
# of 17000: 966, 15001: 0

C:\temp2> ConsoleApp2 localhost 17000 1000
...[생략]...
966

이 상태에서, 클라이언트 측 콘솔에 1+{ENTER}를 치면 소켓 접속을 모두 끊고, 이어 서버 측에서도 1+{ENTER}를 치면 대응 소켓을 모두 끊으므로 클라이언트 측 소켓에 대해 TIME_WAIT이 남는 것을 "netstat -ano | findstr TIME_WAIT"로 확인할 수 있습니다.

C:\WINDOWS\system32> netstat -ano | findstr TIME_WAIT
  TCP    127.0.0.1:1024         127.0.0.1:17000        TIME_WAIT       0
  TCP    127.0.0.1:1025         127.0.0.1:17000        TIME_WAIT       0
  TCP    127.0.0.1:1026         127.0.0.1:17000        TIME_WAIT       0
  TCP    127.0.0.1:1027         127.0.0.1:17000        TIME_WAIT       0
...[생략]...
  TCP    127.0.0.1:1997         127.0.0.1:17000        TIME_WAIT       0
  TCP    127.0.0.1:1998         127.0.0.1:17000        TIME_WAIT       0
  TCP    127.0.0.1:1999         127.0.0.1:17000        TIME_WAIT       0
  TCP    127.0.0.1:2000         127.0.0.1:17000        TIME_WAIT       0

이제 2분의 여유 시간이 있으니 이 사이에 포트 재사용 여부를 테스트할 수 있습니다. ^^

우선, cmd.exe 창을 띄워 같은 포트로 접속을 시도해 보면,

D:\temp> ConsoleApp2.exe localhost 17000 1001
0

TIME_WAIT으로 점유된 포트로 인해 더 이상 가용 포트가 없어 접속이 안되는 것을 확인할 수 있습니다. 반면, 다른 포트로 접속하면 어떻게 될까요?

D:\temp> ConsoleApp2.exe localhost 17001 1001
127.0.0.1:1116-127.0.0.1:17001
127.0.0.1:1117-127.0.0.1:17001
127.0.0.1:1118-127.0.0.1:17001
127.0.0.1:1119-127.0.0.1:17001
...[생략]...
127.0.0.1:1112-127.0.0.1:17001
127.0.0.1:1113-127.0.0.1:17001
127.0.0.1:1114-127.0.0.1:17001
127.0.0.1:1115-127.0.0.1:17001
965

이런 경우에는, 별다른 설정이 없었는데도 5-tuple 구분을 통해 정상적으로 동일한 포트 번호를 점유하는 것을 확인할 수 있습니다. 실제로 위에서 출력된 포트 하나를 기준으로 netstat 명령을 내려보면,

C:\WINDOWS\system32> netstat -ano | findstr 1115
  TCP    127.0.0.1:1115         127.0.0.1:17000        TIME_WAIT       0
  TCP    127.0.0.1:1115         127.0.0.1:17001        ESTABLISHED     17304

1115 포트가 TIME_WAIT, ESTABLISHED에 각각 사용된 것이 보입니다.

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




따라서, 5-tuple 구분이 되는 서버 소켓으로의 접속이라면 클라이언트 측의 TIME_WAIT으로 인한 소켓 고갈을 염려할 필요는 없습니다. 단지, 주소 및 포트까지 동일한 서버 소켓으로 접속하는 경우라면, TIME_WAIT으로 인한 소켓 포트 점유는 문제가 됩니다.

닷넷 환경이라면 어떨까요?

만약 여러분이 소켓을 사용해 직접 구현한 경우라면 TIME_WAIT으로 인한 소켓 포트 점유를 주의 깊게 살펴야 합니다. 반면, HttpWebRequest, WebClient, HttpClient 등을 이용한 경우라면 그것들 자체 내에 풀링 기능이 있으므로,

You're using HttpClient wrong and it is destabilizing your software
; https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/

TIME_WAIT이 문제가 되는 경우는 거의 없습니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 12/14/2020]

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)
12923정성태1/15/20227602개발 환경 구성: 626. ffmpeg.exe를 사용해 비디오 파일을 MPEG1 포맷으로 변경하는 방법
12922정성태1/14/20226647개발 환경 구성: 625. AKS - Azure Kubernetes Service 생성 및 SLO/SLA 변경 방법
12921정성태1/14/20225632개발 환경 구성: 624. Docker Desktop에서 별도 서버에 설치한 docker registry에 이미지 올리는 방법
12920정성태1/14/20226405오류 유형: 786. Camtasia - An error occurred with the camera: Failed to Add Video Sampler.
12919정성태1/13/20226232Windows: 199. Host Network Service (HNS)에 의해서 점유되는 포트
12918정성태1/13/20226450Linux: 47. WSL - shell script에서 설정한 환경 변수가 스크립트 실행 후 반영되지 않는 문제
12917정성태1/12/20225682오류 유형: 785. C# - The type or namespace name '...' could not be found (are you missing a using directive or an assembly reference?)
12916정성태1/12/20225412오류 유형: 784. TFS - One or more source control bindings for this solution are not valid and are listed below.
12915정성태1/11/20225695오류 유형: 783. Visual Studio - We didn't find any interpreters
12914정성태1/11/20227620VS.NET IDE: 172. 비주얼 스튜디오 2022의 파이선 개발 환경 지원
12913정성태1/11/20228138.NET Framework: 1133. C# - byte * (바이트 포인터)를 FileStream으로 쓰는 방법 [1]
12912정성태1/11/20228766개발 환경 구성: 623. ffmpeg.exe를 사용해 비디오 파일의 이미지를 PGM(Portable Gray Map) 파일 포맷으로 출력하는 방법 [1]
12911정성태1/11/20226101VS.NET IDE: 171. 비주얼 스튜디오 - 더 이상 만들 수 없는 "ASP.NET Core 3.1 Web Application (.NET Framework)" 프로젝트
12910정성태1/10/20226566제니퍼 .NET: 30. 제니퍼 닷넷 적용 사례 (8) - CPU high와 DB 쿼리 성능에 문제가 함께 있는 사이트
12909정성태1/10/20227966오류 유형: 782. Visual Studio 2022 설치 시 "Couldn't install Microsoft.VisualCpp.Redist.14.Latest"
12908정성태1/10/20225819.NET Framework: 1132. C# - ref/out 매개변수의 IL 코드 처리
12907정성태1/9/20226256오류 유형: 781. (youtube-dl.exe) 실행 시 "This app can't run on your PC" / "Access is denied." 오류 발생
12906정성태1/9/20226871.NET Framework: 1131. C# - 네임스페이스까지 동일한 타입을 2개의 DLL에서 제공하는 경우 충돌을 우회하는 방법 [1]파일 다운로드1
12905정성태1/8/20226535오류 유형: 780. Could not load file or assembly 'Microsoft.VisualStudio.TextTemplating.VSHost.15.0, Version=16.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies.
12904정성태1/8/20228553개발 환경 구성: 623. Visual Studio 2022 빌드 환경을 위한 github Actions 설정 [1]
12903정성태1/7/20227150.NET Framework: 1130. C# - ELEMENT_TYPE_INTERNAL 유형의 사용 예
12902정성태1/7/20227191오류 유형: 779. SQL 서버 로그인 에러 - provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.
12901정성태1/5/20227285오류 유형: 778. C# - .NET 5+에서 warning CA1416: This call site is reachable on all platforms. '...' is only supported on: 'windows' 경고 발생
12900정성태1/5/20228936개발 환경 구성: 622. vcpkg로 ffmpeg를 빌드하는 경우 생성될 구성 요소 제어하는 방법
12899정성태1/3/20228421개발 환경 구성: 621. windbg에서 python 스크립트 실행하는 방법 - pykd (2)
12898정성태1/2/20228975.NET Framework: 1129. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 비디오 인코딩 예제(encode_video.c) [1]파일 다운로드1
... 16  17  18  19  20  21  22  23  24  25  26  27  [28]  29  30  ...