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)
13022정성태3/31/20226548Windows: 202. 윈도우 11 업그레이드 - "PC Health Check"를 통과했지만 여전히 업그레이드가 안 되는 경우 해결책
13021정성태3/31/20226710Windows: 201. Windows - INF 파일을 이용한 장치 제거 방법
13020정성태3/30/20226441.NET Framework: 1187. RDP 접속 시 WPF UserControl의 Unloaded 이벤트 발생파일 다운로드1
13019정성태3/30/20226431.NET Framework: 1186. Win32 Message를 Code로부터 메시지 이름 자체를 구하고 싶다면?파일 다운로드1
13018정성태3/29/20226951.NET Framework: 1185. C# - Unsafe.AsPointer가 반환한 포인터는 pinning 상태일까요? [5]
13017정성태3/28/20226794.NET Framework: 1184. C# - GC Heap에 위치한 참조 개체의 주소를 알아내는 방법 - 두 번째 이야기 [3]
13016정성태3/27/20227644.NET Framework: 1183. C# 11에 추가된 ref 필드의 (우회) 구현 방법파일 다운로드1
13015정성태3/26/20228987.NET Framework: 1182. C# 11 - ref struct에 ref 필드를 허용 [1]
13014정성태3/23/20227594VC++: 155. CComPtr/CComQIPtr과 Conformance mode 옵션의 충돌 [1]
13013정성태3/22/20225921개발 환경 구성: 641. WSL 우분투 인스턴스에 파이썬 2.7 개발 환경 구성하는 방법
13012정성태3/21/20225276오류 유형: 803. C# - Local '...' or its members cannot have their address taken and be used inside an anonymous method or lambda expression
13011정성태3/21/20226753오류 유형: 802. 윈도우 운영체제에서 웹캠 카메라 인식이 안 되는 경우
13010정성태3/21/20225687오류 유형: 801. Oracle.ManagedDataAccess.Core - GetTypes 호출 시 "Could not load file or assembly 'System.DirectoryServices.Protocols...'" 오류
13009정성태3/20/20227238개발 환경 구성: 640. docker - ibmcom/db2 컨테이너 실행
13008정성태3/19/20226531VS.NET IDE: 176. 비주얼 스튜디오 - 솔루션 탐색기에서 프로젝트를 선택할 때 csproj 파일이 열리지 않도록 만드는 방법
13007정성태3/18/20226154.NET Framework: 1181. C# - Oracle.ManagedDataAccess의 Pool 및 그것의 연결 개체 수를 알아내는 방법파일 다운로드1
13006정성태3/17/20227190.NET Framework: 1180. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 remuxing.c 예제 포팅
13005정성태3/17/20226068오류 유형: 800. C# - System.InvalidOperationException: Late bound operations cannot be performed on fields with types for which Type.ContainsGenericParameters is true.
13004정성태3/16/20226091디버깅 기술: 182. windbg - 닷넷 메모리 덤프에서 AppDomain에 걸친 정적(static) 필드 값을 조사하는 방법
13003정성태3/15/20226238.NET Framework: 1179. C# - (.NET Framework를 위한) Oracle.ManagedDataAccess 패키지의 성능 카운터 설정 방법
13002정성태3/14/20226989.NET Framework: 1178. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 http_multiclient.c 예제 포팅
13001정성태3/13/20227395.NET Framework: 1177. C# - 닷넷에서 허용하는 메서드의 매개변수와 호출 인자의 최대 수
13000정성태3/12/20226959.NET Framework: 1176. C# - Oracle.ManagedDataAccess.Core의 성능 카운터 설정 방법
12999정성태3/10/20226450.NET Framework: 1175. Visual Studio - 프로젝트 또는 솔루션의 Clean 작업 시 응용 프로그램에서 생성한 파일을 함께 삭제파일 다운로드1
12998정성태3/10/20226062.NET Framework: 1174. C# - ELEMENT_TYPE_FNPTR 유형의 사용 예
12997정성태3/10/202210452오류 유형: 799. Oracle.ManagedDataAccess - "ORA-01882: timezone region not found" 오류가 발생하는 이유
... 16  17  18  19  20  21  22  23  [24]  25  26  27  28  29  30  ...