Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)
(시리즈 글이 3개 있습니다.)
Windows: 171. "Administered port exclusions" 설명
; https://www.sysnet.pe.kr/2/0/12293

Windows: 172. "Administered port exclusions"이 아닌 포트 범위 항목을 삭제하는 방법
; https://www.sysnet.pe.kr/2/0/12305

닷넷: 2158. C# - 소켓 포트를 미리 시스템에 등록/예약해 사용하는 방법(Port Exclusion Ranges)
; https://www.sysnet.pe.kr/2/0/13439




C# - 소켓 포트를 미리 시스템에 등록/예약해 사용하는 방법(Port Exclusion Ranges)

아래와 같은 질문이 있군요. ^^

SocketException 액세스 권한에 의해 숨겨진 소켓에 액세스를 시도했습니다 오류
; https://forum.dotnetdev.kr/t/socketexception/8898

excludedportrange에 대해서는 저도 예전에 글을 남긴 적이 있습니다.

"Administered port exclusions" 설명
; https://www.sysnet.pe.kr/2/0/12293

그리고, 이러한 포트 점유로 인해 개인적으로 겪은 오류도 제법 됩니다. ^^;

소켓 바인딩 시 "System.Net.Sockets.SocketException: An attempt was made to access a socket in a way forbidden by its access permissions" 오류 발생
; https://www.sysnet.pe.kr/2/0/12240

Visual Studio - 웹 애플리케이션 실행 시 "Unable to connect to web server 'IIS Express'." 오류 발생
; https://www.sysnet.pe.kr/2/0/12265

Bitvise - Address is already in use; bind() in ListeningSocket::StartListening() failed: Windows error 10013: An attempt was made to access a socket in a way forbidden by its access permissions.
; https://www.sysnet.pe.kr/2/0/12295

SQL Server 시작 오류 - error code 10013
; https://www.sysnet.pe.kr/2/0/12306

Nox 실행이 안 되는 경우 - Unable to bind to the underlying transport for ...
; https://www.sysnet.pe.kr/2/0/12351

ASP.NET 0x80131620 Failed to bind to address
; https://www.sysnet.pe.kr/2/0/12492

Tomcat 실행 시 Failed to initialize connector [Connector[HTTP/1.1-8080]] 오류
; https://www.sysnet.pe.kr/2/0/12671

IntelliJ에서 Java webapp 실행 시 "Address localhost:1099 is already in use" 오류
; https://www.sysnet.pe.kr/2/0/12672

질문자는 왜 excludedportrange 제한이 있는가에 대한 질문을 했지만, 사실 이미 이름에 그 이유가 있습니다. 소켓 프로그래밍을 해보신 분이라면, 아마도 아래와 같은 오류 상황을 적지 않게 접했을 텐데요,

서버용 Socket에서 사용하는 포트가 충돌한다면?
; https://www.sysnet.pe.kr/2/0/1807

그렇습니다, 우리가 만든 서비스가 또는 응용 프로그램이 특정 포트 범위를 안전하게 사용하고 싶은 경우 excludedportrange에 그 범위를 등록해 두면 되는 것입니다.




그런데, 얼핏 생각하면 이게 말이 안 됩니다. 이유를 볼까요? ^^ 실습을 위해, 12000 포트를 하나 점유한 다음,

// "관리자 권한"으로 실행

using System.Runtime.InteropServices;

namespace ConsoleApp1;

internal class Program
{
    [DllImport("Iphlpapi.dll")]
    internal static extern uint CreatePersistentTcpPortReservation(ushort startPort, ushort numberOfPorts, out long token);

    static void Main(string[] args)
    {
        ushort portReserved = (ushort)IPAddress.HostToNetworkOrder((short)12000);

        error = CreatePersistentTcpPortReservation(portReserved, 1, out pToken);
        if (error != 0)
        {
            Console.WriteLine($"Error: {error}");
            return;
        }

        Console.WriteLine("Success: " + pToken);
    }
}

이제 소켓을 12000 포트에 바인딩해 보면,

using System.Net;
using System.Net.Sockets;

namespace ConsoleApp1;

internal class Program
{
    static void Main(string[] args)
    {
        IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 12000);
        Socket listener = new Socket(SocketType.Stream, ProtocolType.Tcp);

        try
        {
            listener.Bind(localEndPoint);
            listener.Listen(10);

            while (true)
            {
                Console.WriteLine("Waiting for a connection...");
                listener.Accept();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }

    }
}

이렇게 오류가 발생합니다.

C:\temp> ConsoleApp1.exe
System.Net.Sockets.SocketException (10013): An attempt was made to access a socket in a way forbidden by its access permissions.
   at System.Net.Sockets.Socket.UpdateStatusAfterSocketErrorAndThrowException(SocketError error, Boolean disconnectOnFailure, String callerName)
   at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.Sockets.Socket.Bind(EndPoint localEP)
   at ConsoleApp1.Program.Main(String[] args) in C:\ConsoleApp1\ConsoleApp1\Program.cs:line 38

우리가 원했던 바이긴 한데, 정작 우리도 그 포트를 사용할 수 없게 된 것입니다. ^^




당연히 이런 경우를 위해, 소켓을 바인딩하는 별도의 방법이 있고, 아래의 문서에 C++ 예제 코드와 함께 상세하게 나와 있습니다.

CreatePersistentTcpPortReservation function (iphlpapi.h)
; https://learn.microsoft.com/en-us/windows/win32/api/iphlpapi/nf-iphlpapi-createpersistenttcpportreservation

그걸 C#으로 옮기면 Socket.IOControl 메서드를 이용해 다음과 같이 포팅할 수 있습니다.

// "관리자 권한"으로 실행

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

namespace ConsoleApp1;

internal class Program
{
    [DllImport("Iphlpapi.dll")] // iphlpapi.h
    internal static extern uint LookupPersistentTcpPortReservation(ushort startPort, ushort numberOfPorts, out long token);

    static void Main(string[] args)
    {
        int portNumber = 12000;

        ushort portReserved = (ushort)IPAddress.HostToNetworkOrder((short)portNumber);
        uint status = LookupPersistentTcpPortReservation(portReserved, 1, out long portToBind);

        if (status != 0)
        {
            Console.WriteLine($"Lookup failed, creating reservation (port: {portNumber})");
            return;
        }

        Console.WriteLine("PID: " + System.Diagnostics.Process.GetCurrentProcess().Id);
        
        Socket listener = new Socket(SocketType.Stream, ProtocolType.Tcp);

        const int SIO_ASSOCIATE_PORT_RESERVATION = -1744830362;
        byte[] resToken = BitConverter.GetBytes(portToBind);

        int result = listener.IOControl(SIO_ASSOCIATE_PORT_RESERVATION, resToken, null);
        if (result != 0)
        {
            Console.WriteLine($"WSAIoctl(SIO_ASSOCIATE_PORT_RESERVATION) failed with error = {result}");
            return;
        }

        IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, portNumber);

        try
        {
            listener.Bind(localEndPoint);
            listener.Listen(10);

            while (true)
            {
                Console.WriteLine("Waiting for a connection...");
                listener.Accept();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
}

실행해 보면, 정상적으로 12000 포트로 바인딩하는 것을 볼 수 있고, netstat로도 확인이 됩니다.

c:\temp> netstat -ano | findstr 12000
  TCP    0.0.0.0:12000          0.0.0.0:0              LISTENING       55708




주의할 것은, SIO_ASSOCIATE_PORT_RESERVATION 옵션으로 IOControl을 수행하려면 관리자 권한이 있어야 한다는 점입니다. 그렇지 않으면 다음과 같은 예외가 발생합니다.

System.Net.Sockets.SocketException
  HResult=0x80004005
  Message=An attempt was made to access a socket in a way forbidden by its access permissions.
  Source=System.Net.Sockets
  StackTrace:
   at System.Net.Sockets.Socket.UpdateStatusAfterSocketErrorAndThrowException(SocketError error, Boolean disconnectOnFailure, String callerName)
   at System.Net.Sockets.Socket.IOControl(Int32 ioControlCode, Byte[] optionInValue, Byte[] optionOutValue)
   at ConsoleApp1.Program.Main(String[] args) in C:\ConsoleApp1\ConsoleApp1\Program.cs:line 43

그러니까, CreatePersistentTcpPortReservation도 관리자 권한이 필요하고, 그렇게 해서 등록한 포트 영역을 사용하기 위해서도 관리자 권한이 필요한 것인데요, 이런 면에서 봤을 때 "NT 서비스"로 실행하는 응용 프로그램 등의 구성 요소에서 사용하는 용도로 쓸 수 있겠습니다.

그리고 문서에 나오듯이, 이런 점을 이용해 다음의 2가지 시나리오로 사용하면 됩니다.

Applications and services which need to reserve ports fall into two categories.

The first category includes components which need a particular port as part of their operation. Such components will generally prefer to specify their required port at installation time (in an application manifest, for example).

The second category includes components which need any available port or block of ports at runtime.





한 가지 재미있는 건, 정작 netsh로 "Administered port exclusions" 영역을 등록한 경우에는,

[추가]
netsh int ipv4 Add excludedportrange protocol=tcp startport=12000 numberofports=1 store=persistent
netsh int ipv6 Add excludedportrange protocol=tcp startport=12000 numberofports=1 store=persistent

[확인]
netsh int ipv4 show excludedportrange protocol=tcp
netsh int ipv6 show excludedportrange protocol=tcp

[삭제]
netsh int ipv4 delete excludedportrange protocol=tcp startport=12000 numberofports=1
netsh int ipv6 delete excludedportrange protocol=tcp startport=12000 numberofports=1

소켓 바인딩이 허용된다는 점입니다.

// Administered port exclusions 영역의 포트는 직접 바인딩 가능

IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 12000);
listener.Bind(localEndPoint);

그래서, 왜 "Administered" 영역이 있는가에 대한 이유가 불분명합니다. 이건 어쩌면 효력은 없지만, 이 설정을 알고 있는 프로그램들끼리의 약속을 잡아 놓는 것이 아닌가... 하는 추측만 합니다. 예를 들어, 대표적으로 Hyper-V에서 "Administered" 포트 영역을 설정하는데, 그 영역을 설정해 두었으니, (적어도 마이크로소프트가 만든) 다른 소프트웨어에서는 그것을 인지하고 다른 영역의 포트를 사용하도록 유도한다는 식의... ^^ 개인적인 가정입니다.

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





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

[연관 글]






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

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

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13356정성태5/15/20233894DDK: 10. Device Driver 테스트 설치 관련 오류 (Code 37, Code 31) 및 인증서 관련 정리
13355정성태5/12/20233831.NET Framework: 2123. C# - Semantic Kernel의 ChatGPT 대화 구현 [1]파일 다운로드1
13354정성태5/12/20234089.NET Framework: 2122. C# - "Use Unicode UTF-8 for worldwide language support" 설정을 한 경우, 한글 입력이 '\0' 문자로 처리
13352정성태5/12/20233698.NET Framework: 2121. C# - Semantic Kernel의 대화 문맥 유지파일 다운로드1
13351정성태5/11/20234207VS.NET IDE: 185. Visual Studio - 원격 Docker container 내에 실행 중인 응용 프로그램에 대한 디버깅 [1]
13350정성태5/11/20233477오류 유형: 859. Windows Date and Time - Unable to continue. You do not have permission to perform this task
13349정성태5/11/20233783.NET Framework: 2120. C# - Semantic Kernel의 Skill과 Function 사용 예제파일 다운로드1
13348정성태5/10/20233687.NET Framework: 2119. C# - Semantic Kernel의 "Basic Loading of the Kernel" 예제
13347정성태5/10/20234077.NET Framework: 2118. C# - Semantic Kernel의 Prompt chaining 예제파일 다운로드1
13346정성태5/10/20233905오류 유형: 858. RDP 원격 환경과 로컬 PC 간의 Ctrl+C, Ctrl+V 복사가 안 되는 문제
13345정성태5/9/20235283.NET Framework: 2117. C# - (OpenAI 기반의) Microsoft Semantic Kernel을 이용한 자연어 처리 [1]파일 다운로드1
13344정성태5/9/20236489.NET Framework: 2116. C# - OpenAI API 사용 - 지원 모델 목록 [1]파일 다운로드1
13343정성태5/9/20234361디버깅 기술: 192. Windbg - Hyper-V VM으로 이더넷 원격 디버깅 연결하는 방법
13342정성태5/8/20234273.NET Framework: 2115. System.Text.Json의 역직렬화 시 필드/속성 주의
13341정성태5/8/20234005닷넷: 2114. C# 12 - 모든 형식의 별칭(Using aliases for any type)
13340정성태5/8/20234079오류 유형: 857. Microsoft.Data.SqlClient.SqlException - 0x80131904
13339정성태5/6/20234742닷넷: 2113. C# 12 - 기본 생성자(Primary Constructors)
13338정성태5/6/20234261닷넷: 2112. C# 12 - 기본 람다 매개 변수파일 다운로드1
13337정성태5/5/20234765Linux: 59. dockerfile - docker exec로 container에 접속 시 자동으로 실행되는 코드 적용
13336정성태5/4/20234573.NET Framework: 2111. C# - 바이너리 출력 디렉터리와 연관된 csproj 설정
13335정성태4/30/20234673.NET Framework: 2110. C# - FFmpeg.AutoGen 라이브러리를 이용한 기본 프로젝트 구성 - Windows Forms파일 다운로드1
13334정성태4/29/20234308Windows: 250. Win32 C/C++ - Modal 메시지 루프 내에서 SetWindowsHookEx를 이용한 Thread 메시지 처리 방법
13333정성태4/28/20233751Windows: 249. Win32 C/C++ - 대화창 템플릿을 런타임에 코딩해서 사용파일 다운로드1
13332정성태4/27/20233853Windows: 248. Win32 C/C++ - 대화창을 위한 메시지 루프 사용자 정의파일 다운로드1
13331정성태4/27/20233884오류 유형: 856. dockerfile - 구 버전의 .NET Core 이미지 사용 시 apt update 오류
13330정성태4/26/20233526Windows: 247. Win32 C/C++ - CS_GLOBALCLASS 설명
1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...