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 옵션이 활성화된다고 합니다.
정성태

1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13472정성태12/4/20232132C/C++: 164. Visual C++ - InterlockedCompareExchange128 사용 방법
13471정성태12/4/20232161Copilot - To enable GitHub Copilot, authorize this extension using GitHub's device flow
13470정성태12/2/20232468닷넷: 2178. C# - .NET 8부터 COM Interop에 대한 자동 소스 코드 생성 도입파일 다운로드1
13469정성태12/1/20232178닷넷: 2177. C# - (Interop DLL 없이) CoClass를 이용한 COM 개체 생성 방법파일 다운로드1
13468정성태12/1/20232172닷넷: 2176. C# - .NET Core/5+부터 달라진 RCW(Runtime Callable Wrapper) 대응 방식파일 다운로드1
13467정성태11/30/20232149오류 유형: 882. C# - Unhandled exception. System.Runtime.InteropServices.COMException (0x800080A5)파일 다운로드1
13466정성태11/29/20232373닷넷: 2175. C# - DllImport 메서드의 AOT 지원을 위한 LibraryImport 옵션
13465정성태11/28/20232103개발 환경 구성: 689. MSBuild - CopyToOutputDirectory가 "dotnet publish" 시에는 적용되지 않는 문제파일 다운로드1
13464정성태11/28/20232207닷넷: 2174. C# - .NET 7부터 UnmanagedCallersOnly 함수 export 기능을 AOT 빌드에 통합파일 다운로드1
13463정성태11/27/20232092오류 유형: 881. Visual Studio - NU1605: Warning As Error: Detected package downgrade
13462정성태11/27/20232140오류 유형: 880. Visual Studio - error CS0246: The type or namespace name '...' could not be found
13461정성태11/26/20232205닷넷: 2173. .NET Core 3/5+ 기반의 COM Server를 registry 등록 없이 사용하는 방법파일 다운로드1
13460정성태11/26/20232164닷넷: 2172. .NET 6+ 기반의 COM Server 내에 Type Library를 내장하는 방법파일 다운로드1
13459정성태11/26/20232191닷넷: 2171. .NET Core 3/5+ 기반의 COM Server를 기존의 regasm처럼 등록하는 방법파일 다운로드1
13458정성태11/26/20232194닷넷: 2170. .NET Core/5+ 기반의 COM Server를 tlb 파일을 생성하는 방법(tlbexp)
13457정성태11/25/20232145VS.NET IDE: 187. Visual Studio - 16.9 버전부터 추가된 "Display inline type hints" 옵션
13456정성태11/25/20232438닷넷: 2169. C# - OpenAI를 사용해 PDF 데이터를 대상으로 OpenAI 챗봇 작성 [1]파일 다운로드1
13455정성태11/25/20232323닷넷: 2168. C# - Azure.AI.OpenAI 패키지로 OpenAI 사용파일 다운로드1
13454정성태11/23/20232661닷넷: 2167. C# - Qdrant Vector DB를 이용한 Embedding 벡터 값 보관/조회 (Azure OpenAI) [1]파일 다운로드1
13453정성태11/23/20232205오류 유형: 879. docker desktop 설치 시 "Invalid JSON string. (Exception from HRESULT: 0x83750007)"
13452정성태11/22/20232289닷넷: 2166. C# - Azure OpenAI API를 이용해 사용자가 제공하는 정보를 대상으로 검색하는 방법파일 다운로드1
13451정성태11/21/20232420닷넷: 2165. C# - Azure OpenAI API를 이용해 ChatGPT처럼 동작하는 콘솔 응용 프로그램 제작파일 다운로드1
13450정성태11/21/20232242닷넷: 2164. C# - Octokit을 이용한 GitHub Issue 검색파일 다운로드1
13449정성태11/21/20232340개발 환경 구성: 688. Azure OpenAI 서비스 신청 방법
13448정성태11/20/20232616닷넷: 2163. .NET 8 - Dynamic PGO를 결합한 성능 향상파일 다운로드1
13447정성태11/16/20232480닷넷: 2162. ASP.NET Core 웹 사이트의 SSL 설정을 코드로 하는 방법
1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...