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)
13254정성태2/10/20234383Windows: 223. (WMI 쿼리를 위한) PowerShell 문자열 escape 처리
13253정성태2/9/20235159Windows: 222. C# - 다른 윈도우 프로그램이 실행되었음을 인식하는 방법파일 다운로드1
13252정성태2/9/20233996오류 유형: 844. ssh로 명령어 수행 시 멈춤 현상
13251정성태2/8/20234441스크립트: 44. 파이썬의 3가지 스레드 ID
13250정성태2/8/20236255오류 유형: 843. System.InvalidOperationException - Unable to configure HTTPS endpoint
13249정성태2/7/20235089오류 유형: 842. 리눅스 - You must wait longer to change your password
13248정성태2/7/20234160오류 유형: 841. 리눅스 - [사용자 계정] is not in the sudoers file. This incident will be reported.
13247정성태2/7/20235060VS.NET IDE: 180. Visual Studio - 닷넷 소스 코드 디버깅 중 "Decompile source code"가 동작하는 않는 문제
13246정성태2/6/20234181개발 환경 구성: 664. Hyper-V에 설치한 리눅스 VM의 VHD 크기 늘리는 방법 - 두 번째 이야기
13245정성태2/6/20234753.NET Framework: 2093. C# - PEM 파일을 이용한 RSA 개인키/공개키 설정 방법파일 다운로드1
13244정성태2/5/20234100VS.NET IDE: 179. Visual Studio - External Tools에 Shell 내장 명령어 등록
13243정성태2/5/20234957디버깅 기술: 190. windbg - Win32 API 호출 시점에 BP 거는 방법 [1]
13242정성태2/4/20234394디버깅 기술: 189. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.UnauthorizedAccessException
13241정성태2/3/20233904디버깅 기술: 188. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.IO.FileNotFoundException
13240정성태2/1/20234059디버깅 기술: 187. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.Web.HttpException
13239정성태2/1/20233722디버깅 기술: 186. C# - CacheDependency의 숨겨진 예외 - System.Web.HttpException
13238정성태1/31/20235796.NET Framework: 2092. IIS 웹 사이트를 TLS 1.2 또는 TLS 1.3 프로토콜로만 운영하는 방법
13237정성태1/30/20235465.NET Framework: 2091. C# - 웹 사이트가 어떤 버전의 TLS/SSL을 지원하는지 확인하는 방법
13236정성태1/29/20235072개발 환경 구성: 663. openssl을 이용해 인트라넷 IIS 사이트의 SSL 인증서 생성
13235정성태1/29/20234635개발 환경 구성: 662. openssl - 윈도우 환경의 명령행에서 SAN 적용하는 방법
13234정성태1/28/20235718개발 환경 구성: 661. dnSpy를 이용해 소스 코드가 없는 .NET 어셈블리의 코드를 변경하는 방법 [1]
13233정성태1/28/20237035오류 유형: 840. C# - WebClient로 https 호출 시 "The request was aborted: Could not create SSL/TLS secure channel" 예외 발생
13232정성태1/27/20234801스크립트: 43. uwsgi의 --processes와 --threads 옵션
13231정성태1/27/20233720오류 유형: 839. python - TypeError: '...' object is not callable
13230정성태1/26/20234096개발 환경 구성: 660. WSL 2 내부로부터 호스트 측의 네트워크로 UDP 데이터가 1개의 패킷으로만 제한되는 문제
13229정성태1/25/20235085.NET Framework: 2090. C# - UDP Datagram의 최대 크기
1  2  3  4  5  6  7  8  9  10  11  12  13  14  [15]  ...