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

비밀번호

댓글 작성자
 




... 16  17  18  19  20  21  22  23  [24]  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13030정성태4/15/20226491오류 유형: 804. 정규 표현식 오류 - Quantifier {x,y} following nothing.
13029정성태4/14/20226891Windows: 203. iisreset 후에도 이전에 설정한 전역 환경 변수가 w3wp.exe에 적용되는 문제
13028정성태4/13/20226803.NET Framework: 1193. (appsettings.json처럼) web.config의 Debug/Release에 따른 설정 적용
13027정성태4/12/20227101.NET Framework: 1192. C# - 환경 변수의 변화를 알리는 WM_SETTINGCHANGE Win32 메시지 사용법파일 다운로드1
13026정성태4/11/20228626.NET Framework: 1191. C 언어로 작성된 FFmpeg Examples의 C# 포팅 전체 소스 코드 [3]
13025정성태4/11/20227960.NET Framework: 1190. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 vaapi_encode.c, vaapi_transcode.c 예제 포팅
13024정성태4/7/20226454.NET Framework: 1189. C# - 런타임 환경에 따라 달라진 AppDomain.GetCurrentThreadId 메서드
13023정성태4/6/20226760.NET Framework: 1188. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 transcoding.c 예제 포팅 [3]
13022정성태3/31/20226662Windows: 202. 윈도우 11 업그레이드 - "PC Health Check"를 통과했지만 여전히 업그레이드가 안 되는 경우 해결책
13021정성태3/31/20226833Windows: 201. Windows - INF 파일을 이용한 장치 제거 방법
13020정성태3/30/20226571.NET Framework: 1187. RDP 접속 시 WPF UserControl의 Unloaded 이벤트 발생파일 다운로드1
13019정성태3/30/20226569.NET Framework: 1186. Win32 Message를 Code로부터 메시지 이름 자체를 구하고 싶다면?파일 다운로드1
13018정성태3/29/20227107.NET Framework: 1185. C# - Unsafe.AsPointer가 반환한 포인터는 pinning 상태일까요? [5]
13017정성태3/28/20226909.NET Framework: 1184. C# - GC Heap에 위치한 참조 개체의 주소를 알아내는 방법 - 두 번째 이야기 [3]
13016정성태3/27/20227763.NET Framework: 1183. C# 11에 추가된 ref 필드의 (우회) 구현 방법파일 다운로드1
13015정성태3/26/20229120.NET Framework: 1182. C# 11 - ref struct에 ref 필드를 허용 [1]
13014정성태3/23/20227693VC++: 155. CComPtr/CComQIPtr과 Conformance mode 옵션의 충돌 [1]
13013정성태3/22/20226019개발 환경 구성: 641. WSL 우분투 인스턴스에 파이썬 2.7 개발 환경 구성하는 방법
13012정성태3/21/20225341오류 유형: 803. C# - Local '...' or its members cannot have their address taken and be used inside an anonymous method or lambda expression
13011정성태3/21/20226823오류 유형: 802. 윈도우 운영체제에서 웹캠 카메라 인식이 안 되는 경우
13010정성태3/21/20225750오류 유형: 801. Oracle.ManagedDataAccess.Core - GetTypes 호출 시 "Could not load file or assembly 'System.DirectoryServices.Protocols...'" 오류
13009정성태3/20/20227376개발 환경 구성: 640. docker - ibmcom/db2 컨테이너 실행
13008정성태3/19/20226672VS.NET IDE: 176. 비주얼 스튜디오 - 솔루션 탐색기에서 프로젝트를 선택할 때 csproj 파일이 열리지 않도록 만드는 방법
13007정성태3/18/20226258.NET Framework: 1181. C# - Oracle.ManagedDataAccess의 Pool 및 그것의 연결 개체 수를 알아내는 방법파일 다운로드1
13006정성태3/17/20227331.NET Framework: 1180. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 remuxing.c 예제 포팅
13005정성태3/17/20226197오류 유형: 800. C# - System.InvalidOperationException: Late bound operations cannot be performed on fields with types for which Type.ContainsGenericParameters is true.
... 16  17  18  19  20  21  22  23  [24]  25  26  27  28  29  30  ...