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)
13219정성태1/18/20233856Windows: 220. 네트워크의 인터넷 접속 가능 여부에 대한 판단 기준
13218정성태1/17/20233777VS.NET IDE: 178. Visual Studio 17.5 (Preview 2) - 포트 터널링을 이용한 웹 응용 프로그램의 외부 접근 허용
13217정성태1/13/20234381디버깅 기술: 185. windbg - 64비트 운영체제에서 작업 관리자로 뜬 32비트 프로세스의 덤프를 sos로 디버깅하는 방법
13216정성태1/12/20234646디버깅 기술: 184. windbg - 32비트 프로세스의 메모리 덤프인 경우 !peb 명령어로 나타나지 않는 환경 변수
13215정성태1/11/20236146Linux: 56. 리눅스 - /proc/pid/stat 정보를 이용해 프로세스의 CPU 사용량 구하는 방법 [1]
13214정성태1/10/20235721.NET Framework: 2087. .NET 6부터 SourceGenerator와 통합된 System.Text.Json [1]파일 다운로드1
13213정성태1/9/20235259오류 유형: 836. docker 이미지 빌드 시 "RUN apt install ..." 명령어가 실패하는 이유
13212정성태1/8/20235023기타: 85. 단정도/배정도 부동 소수점의 정밀도(Precision)에 따른 형변환 손실
13211정성태1/6/20235103웹: 42. (https가 아닌) http 다운로드를 막는 웹 브라우저
13210정성태1/5/20234128Windows: 219. 윈도우 x64의 경우 0x00000000`7ffe0000 아래의 주소는 왜 사용하지 않을까요?
13209정성태1/4/20234022Windows: 218. 왜 윈도우에서 가상 메모리 공간은 64KB 정렬이 된 걸까요?
13208정성태1/3/20233956.NET Framework: 2086. C# - Windows 운영체제의 2MB Large 페이지 크기 할당 방법파일 다운로드1
13207정성태12/26/20224263.NET Framework: 2085. C# - gpedit.msc의 "User Rights Assignment" 특권을 코드로 설정/해제하는 방법파일 다운로드1
13206정성태12/24/20224469.NET Framework: 2084. C# - GetTokenInformation으로 사용자 SID(Security identifiers) 구하는 방법 [3]파일 다운로드1
13205정성태12/24/20224869.NET Framework: 2083. C# - C++과의 연동을 위한 구조체의 fixed 배열 필드 사용 (2)파일 다운로드1
13204정성태12/22/20224147.NET Framework: 2082. C# - (LSA_UNICODE_STRING 예제로) CustomMarshaler 사용법파일 다운로드1
13203정성태12/22/20224270.NET Framework: 2081. C# Interop 예제 - (LSA_UNICODE_STRING 예제로) 구조체를 C++에 전달하는 방법파일 다운로드1
13202정성태12/21/20224639기타: 84. 직렬화로 설명하는 Little/Big Endian파일 다운로드1
13201정성태12/20/20225266오류 유형: 835. PyCharm 사용 시 C 드라이브 용량 부족
13200정성태12/19/20224146오류 유형: 834. 이벤트 로그 - SSL Certificate Settings created by an admin process for endpoint
13199정성태12/19/20224414개발 환경 구성: 656. Internal Network 유형의 스위치로 공유한 Hyper-V의 VM과 호스트가 통신이 안 되는 경우
13198정성태12/18/20224307.NET Framework: 2080. C# - Microsoft.XmlSerializer.Generator 처리 없이 XmlSerializer 생성자를 예외 없이 사용하고 싶다면?파일 다운로드1
13197정성태12/17/20224264.NET Framework: 2079. .NET Core/5+ 환경에서 XmlSerializer 사용 시 System.IO.FileNotFoundException 예외 발생하는 경우파일 다운로드1
13196정성태12/16/20224393.NET Framework: 2078. .NET Core/5+를 위한 SGen(Microsoft.XmlSerializer.Generator) 사용법
13195정성태12/15/20224986개발 환경 구성: 655. docker - bridge 네트워크 모드에서 컨테이너 간 통신 시 --link 옵션 권장 이유
13194정성태12/14/20225003오류 유형: 833. warning C4747: Calling managed 'DllMain': Managed code may not be run under loader lock파일 다운로드1
... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...