Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 4개 있습니다.)
(시리즈 글이 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




윈도우 환경에서 클라이언트 소켓의 최대 접속 수 (4) - ReuseUnicastPort를 이용한 포트 고갈 문제 해결

지난 글에서,

C# - dynamicport 값의 범위를 알아내는 방법
; https://www.sysnet.pe.kr/2/0/12434

Get-NetTCPSetting의 출력 결과를 보면 특이한 속성이 2개 있습니다.

...[생략]...
DynamicPortRangeStartPort       : 1024
DynamicPortRangeNumberOfPorts   : 64511
AutomaticUseCustom              : Disabled
NonSackRttResiliency            : Disabled
ForceWS                         : Enabled
MaxSynRetransmissions           : 4
AutoReusePortRangeStartPort     : 0
AutoReusePortRangeNumberOfPorts : 0

/*
Service Name and Transport Protocol Port Number Registry
; https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml

System Ports(Well-Known Port Numbers): 0 ~ 1023
User Ports(Registered Port Numbers): 1024 ~ 49151
Dynamic and/or Private Ports: 49152 ~ 65535
*/

AutoReusePortRangeStartPort
Specifies the number of ports for the auto-reuse port range, which is a port range used for local ephemeral port selection by outbound TCP connections for which either SO_REUSE_UNICASTPORT has been set on the socket, or for which connect() has been called without calling bind() on the socket.

If you specify 0, the auto-reuse feature is disabled and ephemeral ports are drawn instead from the dynamic port range as specified by DynamicPortRangeStartPort and DynamicPortRangeNumberOfPorts, even if SO_REUSE_UNICASTPORT is set on a socket.


AutoReusePortRangeNumberOfPorts
Specifies the number of ports for the auto-reuse port range, which is a port range used for local ephemeral port selection by outbound TCP connections for which either SO_REUSE_UNICASTPORT has been set on the socket, or for which connect() has been called without calling bind() on the socket.

If you specify 0, the auto-reuse feature is disabled and ephemeral ports are drawn instead from the dynamic port range as specified by DynamicPortRangeStartPort and DynamicPortRangeNumberOfPorts, even if SO_REUSE_UNICASTPORT is set on a socket.


(WMI 관련 문서에서는 저 2개의 옵션에 대해 "This property is not supported before Windows 10 and Windows Server 2016."이라는 제약을 언급합니다.)

그리고 SO_REUSE_UNICASTPORT 옵션이 눈에 들어옵니다. 재미있는 것은, 그 옵션을 전부터 다음의 문서에 설명한 정도로만 알고 있었는데,

SOL_SOCKET Socket Options
; https://learn.microsoft.com/en-us/windows/win32/winsock/sol-socket-socket-options

SO_REUSE_UNICASTPORT

When set, allow ephemeral port reuse for Winsock API connection functions which require an explicit bind, such as ConnectEx. Note that connection functions with an implicit bind (such as connect without an explicit bind) have this option set by default. Use this option instead of SO_PORT_SCALABILITY on platforms where both are available.


문제는, 테스트 결과와 맞지 않아서 이해를 못하고 있었던 상태였습니다. 그런 와중에, 의도치 않게 MSFT_NetTCPSetting 설정에서 AutoReusePortRangeStartPort/AutoReusePortRangeNumberOfPorts 옵션의 값들이 0이라는 것에 실마리가 풀리기 시작합니다. 즉, 기본적으로 윈도우 환경에서 SO_REUSE_UNICASTPORT를 위한 환경 설정은 disabled 상태였던 것입니다.




눈치채셨겠지만, 윈도우에서는 특이하게 "REUSE PORT"를 위한 영역을 설정할 수 있게 했고 바로 그것이 AutoReusePortRangeStartPort/AutoReusePortRangeNumberOfPorts가 됩니다.

실제로 테스트를 해볼까요? ^^

"TCP Templates for Windows Server 2019 - How to tune your Windows Server Transports (Advanced users only)" 글에 따르면 SettingName의 성격에 따라 우리가 하려는 localhost로의 연결인 경우 DatacenterCustom이 맞을 것입니다.

그런데, 이 설정을 바꾸면 적용하기 위해 시스템 재부팅이 필요한데요, 일단 이 글은 클라이언트 소켓의 5-tuple 구분이 되느냐 여부가 관건이므로 그냥 ^^ 싹 변경을 해보겠습니다.

Set-NetTCPSetting -SettingName InternetCustom -AutoReusePortRangeStartPort 15000 -AutoReusePortRangeNumberOfPorts 1000
Set-NetTCPSetting -SettingName DatacenterCustom -AutoReusePortRangeStartPort 15000 -AutoReusePortRangeNumberOfPorts 1000
Set-NetTCPSetting -SettingName Internet -AutoReusePortRangeStartPort 15000 -AutoReusePortRangeNumberOfPorts 1000
Set-NetTCPSetting -SettingName Datacenter -AutoReusePortRangeStartPort 15000 -AutoReusePortRangeNumberOfPorts 1000

15,000번 포트부터 (테스트의 편의를 위해) 1,000개의 영역을 예약했는데요, 확인은 (반드시 재부팅 후에) 다음과 같이 Get-NetTCPSetting 명령어를 내리면 됩니다.

PS C:\WINDOWS\system32> Get-NetTCPSetting -SettingName Datacenter

SettingName                     : Datacenter
MinRto(ms)                      : 20
InitialCongestionWindow(MSS)    : 10
CongestionProvider              : CUBIC
CwndRestart                     : False
DelayedAckTimeout(ms)           : 10
DelayedAckFrequency             : 2
MemoryPressureProtection        : Enabled
AutoTuningLevelLocal            : Normal
AutoTuningLevelGroupPolicy      : NotConfigured
AutoTuningLevelEffective        : Local
EcnCapability                   : Disabled
Timestamps                      : Disabled
InitialRto(ms)                  : 1000
ScalingHeuristics               : Disabled
DynamicPortRangeStartPort       : 1024
DynamicPortRangeNumberOfPorts   : 977
AutomaticUseCustom              : Disabled
NonSackRttResiliency            : Disabled
ForceWS                         : Enabled
MaxSynRetransmissions           : 4
AutoReusePortRangeStartPort     : 15000
AutoReusePortRangeNumberOfPorts : 1000

잘 변경되었군요. ^^




일단 환경 구성은 완료했고, 재미있는 것은 이렇게 바꾼 후 지난 예제의 서버를 해당 PC에서 돌리면 다음과 같은 오류가 발생합니다.

D:\temp> ConsoleApp1.exe

Unhandled Exception:
Unhandled Exception: System.Net.Sockets.SocketException: An attempt was made to access a socket in a way forbidden by its access permissions
   at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.Sockets.Socket.Bind(EndPoint localEP)
   at System.Net.Sockets.TcpListener.Start(Int32 backlog)
   at ConsoleApp1.Program.acceptFunc(Object objPort) in C:\temp\unicast_socket_sample\ConsoleApp1\Program.cs:line 59
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart(Object obj)
System.Net.Sockets.SocketException: An attempt was made to access a socket in a way forbidden by its access permissions
   at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.Sockets.Socket.Bind(EndPoint localEP)
   at System.Net.Sockets.TcpListener.Start(Int32 backlog)
   at ConsoleApp1.Program.acceptFunc(Object objPort) in C:\temp\unicast_socket_sample\ConsoleApp1\Program.cs:line 59
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart(Object obj)

기존의 DynamicPorts 영역에서는 Listen 포트로도 사용이 가능했었던 것과는 달리, AutoReuse로 예약된 경우는 Listen 용도로도 허용이 안되는 듯합니다. 그래서 각각 17000번, 17001번 포트로 대기하도록 변경을 해줍니다. 그다음, 클라이언트 측 코드는 단순하게 다음과 같이 작성하면 됩니다.

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;

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.Connect(ipAddr, port);

                        Console.WriteLine($"{client.LocalEndPoint}-{client.RemoteEndPoint}");
                        clients1.Add(client);
                    }
                    catch (Exception)
                    {
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            Console.WriteLine(clients1.Count);
            Console.ReadLine();
        }
    }
}

이후, 서버와 클라이언트의 실행 결과를 각각 다음과 같이 확인할 수 있습니다.

// 서버 측 포트 17000, 17001 Listen

D:\temp> ConsoleApp1.exe
# of 17000: 0, 17001: 0
# of 17000: 0, 17001: 0
# of 17000: 1000, 17001: 0
# of 17000: 1000, 17001: 0
# of 17000: 1000, 17001: 1000
# of 17000: 1000, 17001: 1000

// #1 클라이언트 측 - 17000 포트로 1001개 접속 시도

D:\temp> ConsoleApp2.exe localhost 17000 1001
127.0.0.1:15161-127.0.0.1:17000
127.0.0.1:15162-127.0.0.1:17000
127.0.0.1:15163-127.0.0.1:17000
127.0.0.1:15164-127.0.0.1:17000
127.0.0.1:15165-127.0.0.1:17000
127.0.0.1:15166-127.0.0.1:17000
...[생략]...
127.0.0.1:15156-127.0.0.1:17000
127.0.0.1:15157-127.0.0.1:17000
127.0.0.1:15158-127.0.0.1:17000
127.0.0.1:15159-127.0.0.1:17000
127.0.0.1:15160-127.0.0.1:17000
1000

// #2 클라이언트 측 - 17001 포트로 1001개 접속 시도

D:\temp>ConsoleApp2.exe localhost 17001 1001
127.0.0.1:15079-127.0.0.1:17001
127.0.0.1:15080-127.0.0.1:17001
127.0.0.1:15081-127.0.0.1:17001
127.0.0.1:15082-127.0.0.1:17001
127.0.0.1:15083-127.0.0.1:17001
127.0.0.1:15084-127.0.0.1:17001
127.0.0.1:15085-127.0.0.1:17001
...[생략]...
127.0.0.1:15073-127.0.0.1:17001
127.0.0.1:15074-127.0.0.1:17001
127.0.0.1:15075-127.0.0.1:17001
127.0.0.1:15076-127.0.0.1:17001
127.0.0.1:15077-127.0.0.1:17001
127.0.0.1:15078-127.0.0.1:17001
1000

보는 바와 같이, AutoReuse로 잡아 놓은 범위 내에서만 포트를 할당받고 있으며 2개의 클라이언트 모두 각각 1,000개까지의 연결을 성공적으로 하고 있습니다.




반면, 어떤 식으로든 (connect 전에) bind를 하는 경우에는,

client.Bind(new IPEndPoint(IPAddress.Any, 0));
client.Connect(targetIp, port);

해당 포트는 AutoReusePortRangeStartPort가 아닌 DynamicPortRangeStartPort로부터 포트를 할당받고 이 영역의 소켓은 (자동) reuse가 안되므로 지난 출력 결과와 같이 5-tuple 혜택을 받지 못해 원래대로 중복 포트 연결이 안 됩니다. 하지만, 만약 bind가 꼭 필요하다면, 이때 명시적으로 ReuseUnicastPort 옵션을 줘도 됩니다.

client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseUnicastPort, true);
client.Bind(new IPEndPoint(IPAddress.Any, 0));
client.Connect(targetIp, port); // AutoReuse 영역으로부터 포트 할당

이렇게 실습한 후에, 다시 한번 SO_REUSE_UNICASTPORT 설명을 보면,

SO_REUSE_UNICASTPORT

When set, allow ephemeral port reuse for Winsock API connection functions which require an explicit bind, such as ConnectEx. Note that connection functions with an implicit bind (such as connect without an explicit bind) have this option set by default. Use this option instead of SO_PORT_SCALABILITY on platforms where both are available.


이제서야 내용과 실습이 일치해서 이해가 갑니다. ^^

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




정리해 보면, 클라이언트 운영체제의 경우 Windows 10부터, 서버 운영체제인 경우에는 Windows Server 2016부터 AutoReusePortRangeStartPort/AutoReusePortRangeNumberOfPorts 옵션을 설정하면 일반적인 상황에서도 5-tuple 구분 값을 사용해 소켓을 사용할 수 있습니다. (다르게 말해 "ephemeral port exhaustion" 문제가 일부 환경에서 해결됩니다.)

현실적으로 봤을 때, 기존 응용 프로그램의 bind를 포함한 소켓 사용을 고려해 다음과 같은 범위로 설정하는 것이 좋을 듯합니다.

// 10,000개의 dynamic ports, 50,000개의 auto-reuse 포트

DynamicPortRangeStartPort : 1024
DynamicPortRangeNumberOfPorts : 10000
AutoReusePortRangeStartPort : 15000
AutoReusePortRangeNumberOfPorts : 50000

물론, 대부분의 응용 프로그램들이 기본값(64,511)의 ephemeral port 사용을 허용하는 기존 설정을 바꿀 필요는 없습니다. 저런 설정까지 필요한 것은 API Gateway 등의 역할을 수행하는 프로그램 정도가 될 것입니다. 예를 들어,

[그림 출처: https://making.pusher.com/ephemeral-port-exhaustion-and-how-to-avoid-it/]

websocket-server-haproxy.png

위와 같은 상황인 경우 Gateway 역할을 하는 haproxy 프로세스는 다른 서비스로 Socket Connect를 하게 될 텐데, 만약 auto-reuse 설정을 하지 않은 상태라면 socket:8080 ~ socket:8083까지 통틀어 총 64,000개 정도의 연결만 허용할 수 있는 반면, auto-reuse 설정을 (50,000개로 설정했다면) 각각 5만 개씩 총 20만 개의 포트가 열릴 수 있게 되는 것입니다.




윈도우 서버 환경에서, 최대 생성 가능한 소켓(socket) 연결 수는 얼마일까?
; https://www.sysnet.pe.kr/2/0/964

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

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

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




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 11/2/2022]

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

비밀번호

댓글 작성자
 



2021-12-14 11시04분
아래의 글에 보면,

Sockets - Handle port exhaustion by utilizing auto-reuse port range on Windows
; https://devblogs.microsoft.com/dotnet/dotnet-6-networking-improvements/#sockets

"auto-reuse port range" 기능이 Windows 8.1부터 가능했다고 합니다. 그런데, 아래의 소스 코드에 달린 주석을 보면,

ServicePoint.cs
; https://referencesource.microsoft.com/#System/net/System/Net/ServicePoint.cs,1326

관련 소켓 옵션 자체는 Windows 10부터 정의되었다고 합니다. ^^;

어쨌든, .NET 6부터는 모든 비동기 소켓의 외부 연결은 SO_REUSE_UNICASTPORT 옵션이 활성화된다고 합니다.
정성태

... 16  17  18  19  20  21  [22]  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13078정성태6/16/20226673.NET Framework: 2021. WPF - UI Thread와 Render Thread파일 다운로드1
13077정성태6/15/20226994스크립트: 40. 파이썬 - PostgreSQL 환경 구성
13075정성태6/15/20225955Linux: 50. Linux - apt와 apt-get의 차이 [2]
13074정성태6/13/20226286.NET Framework: 2020. C# - NTFS 파일에 사용자 정의 속성값 추가하는 방법파일 다운로드1
13073정성태6/12/20226506Windows: 207. Windows Server 2022에 도입된 WSL 2
13072정성태6/10/20226771Linux: 49. Linux - ls 명령어로 출력되는 디렉터리 색상 변경 방법
13071정성태6/9/20227347스크립트: 39. Python에서 cx_Oracle 환경 구성
13070정성태6/8/20227153오류 유형: 813. Windows 11에서 입력 포커스가 바뀌는 문제 [1]
13069정성태5/26/20229384.NET Framework: 2019. C# - .NET에서 제공하는 3가지 Timer 비교 [2]
13068정성태5/24/20227885.NET Framework: 2018. C# - 일정 크기를 할당하는 동안 GC를 (가능한) 멈추는 방법 [1]파일 다운로드1
13067정성태5/23/20227201Windows: 206. Outlook - 1년 이상 지난 메일이 기본적으로 안 보이는 문제
13066정성태5/23/20226513Windows: 205. Windows 11 - Windows + S(또는 Q)로 뜨는 작업 표시줄의 검색 바가 동작하지 않는 경우
13065정성태5/20/20227197.NET Framework: 2017. C# - Windows I/O Ring 소개 [2]파일 다운로드1
13064정성태5/18/20226739.NET Framework: 2016. C# - JIT 컴파일러의 인라인 메서드 처리 유무
13063정성태5/18/20227161.NET Framework: 2015. C# - 인라인 메서드(inline methods)
13062정성태5/17/20227984.NET Framework: 2014. C# - async/await 그리고 스레드 (4) 비동기 I/O 재현파일 다운로드1
13061정성태5/16/20226788.NET Framework: 2013. C# - FILE_FLAG_OVERLAPPED가 적용된 파일의 읽기/쓰기 시 Position 관리파일 다운로드1
13060정성태5/15/20229267.NET Framework: 2012. C# - async/await 그리고 스레드 (3) Task.Delay 재현파일 다운로드1
13059정성태5/14/20227719.NET Framework: 2011. C# - CLR ThreadPool의 I/O 스레드에 작업을 맡기는 방법 [1]파일 다운로드1
13058정성태5/13/20227621.NET Framework: 2010. C# - ThreadPool.SetMaxThreads 사용법
13057정성태5/12/20229293오류 유형: 812. 파이썬 - ImportError: cannot import name ...
13056정성태5/12/20226425.NET Framework: 2009. C# - async/await 그리고 스레드 (2) MyTask의 호출 흐름 [2]파일 다운로드1
13055정성태5/11/20229368.NET Framework: 2008. C# - async/await 그리고 스레드 (1) MyTask로 재현 [11]파일 다운로드1
13054정성태5/11/20226860.NET Framework: 2007. C# - 10진수 숫자를 담은 문자열을 숫자로 변환하는 방법 [11]파일 다운로드1
13053정성태5/10/20226507.NET Framework: 2006. C# - GC.KeepAlive 메서드의 역할
13052정성태5/9/20226503.NET Framework: 2005. C# - 생성한 참조 개체가 언제 GC의 정리 대상이 될까요?
... 16  17  18  19  20  21  [22]  23  24  25  26  27  28  29  30  ...