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)
13005정성태3/17/20226199오류 유형: 800. C# - System.InvalidOperationException: Late bound operations cannot be performed on fields with types for which Type.ContainsGenericParameters is true.
13004정성태3/16/20226204디버깅 기술: 182. windbg - 닷넷 메모리 덤프에서 AppDomain에 걸친 정적(static) 필드 값을 조사하는 방법
13003정성태3/15/20226353.NET Framework: 1179. C# - (.NET Framework를 위한) Oracle.ManagedDataAccess 패키지의 성능 카운터 설정 방법
13002정성태3/14/20227128.NET Framework: 1178. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 http_multiclient.c 예제 포팅
13001정성태3/13/20227490.NET Framework: 1177. C# - 닷넷에서 허용하는 메서드의 매개변수와 호출 인자의 최대 수
13000정성태3/12/20227074.NET Framework: 1176. C# - Oracle.ManagedDataAccess.Core의 성능 카운터 설정 방법
12999정성태3/10/20226590.NET Framework: 1175. Visual Studio - 프로젝트 또는 솔루션의 Clean 작업 시 응용 프로그램에서 생성한 파일을 함께 삭제파일 다운로드1
12998정성태3/10/20226168.NET Framework: 1174. C# - ELEMENT_TYPE_FNPTR 유형의 사용 예
12997정성태3/10/202210591오류 유형: 799. Oracle.ManagedDataAccess - "ORA-01882: timezone region not found" 오류가 발생하는 이유
12996정성태3/9/202215712VS.NET IDE: 175. Visual Studio - 인텔리센스에서 오버로드 메서드를 키보드로 선택하는 방법
12995정성태3/8/20228021.NET Framework: 1173. .NET에서 Producer/Consumer를 구현한 BlockingCollection<T>
12994정성태3/8/20227295오류 유형: 798. WinDbg - Failed to load data access module, 0x80004002
12993정성태3/4/20227130.NET Framework: 1172. .NET에서 Producer/Consumer를 구현하는 기초 인터페이스 - IProducerConsumerCollection<T>
12992정성태3/3/20228555.NET Framework: 1171. C# - BouncyCastle을 사용한 암호화/복호화 예제파일 다운로드1
12991정성태3/2/20227717.NET Framework: 1170. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 transcode_aac.c 예제 포팅
12990정성태3/2/20227317오류 유형: 797. msbuild - The BaseOutputPath/OutputPath property is not set for project '[...].vcxproj'
12989정성태3/2/20226848오류 유형: 796. mstest.exe - System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.VisualStudio.QualityTools.Tips.WebLoadTest.Tip
12988정성태3/2/20225806오류 유형: 795. CI 환경에서 Docker build 시 csproj의 Link 파일에 대한 빌드 오류
12987정성태3/1/20227301.NET Framework: 1169. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 demuxing_decoding.c 예제 포팅
12986정성태2/28/20228146.NET Framework: 1168. C# -IIncrementalGenerator를 적용한 Version 2 Source Generator 실습 [1]
12985정성태2/28/20228070.NET Framework: 1167. C# -Version 1 Source Generator 실습
12984정성태2/24/20227145.NET Framework: 1166. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 filtering_video.c 예제 포팅
12983정성태2/24/20227236.NET Framework: 1165. .NET Core/5+ 빌드 시 runtimeconfig.json에 설정을 반영하는 방법
12982정성태2/24/20227157.NET Framework: 1164. HTTP Error 500.31 - ANCM Failed to Find Native Dependencies
12981정성태2/23/20226753VC++: 154. C/C++ 언어의 문자열 Literal에 인덱스 적용하는 구문 [1]
12980정성태2/23/20227524.NET Framework: 1163. C# - 윈도우 환경에서 usleep을 호출하는 방법 [2]
... 16  17  18  19  20  21  22  23  24  [25]  26  27  28  29  30  ...