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)
13331정성태4/27/20233885오류 유형: 856. dockerfile - 구 버전의 .NET Core 이미지 사용 시 apt update 오류
13330정성태4/26/20233529Windows: 247. Win32 C/C++ - CS_GLOBALCLASS 설명
13329정성태4/24/20233723Windows: 246. Win32 C/C++ - 직접 띄운 대화창 템플릿을 위한 Modal 메시지 루프 생성파일 다운로드1
13328정성태4/19/20233398VS.NET IDE: 184. Visual Studio - Fine Code Coverage에서 동작하지 않는 Fake/Shim 테스트
13327정성태4/19/20233807VS.NET IDE: 183. C# - .NET Core/5+ 환경에서 Fakes를 이용한 단위 테스트 방법
13326정성태4/18/20235231.NET Framework: 2109. C# - 닷넷 응용 프로그램에서 SQLite 사용 (System.Data.SQLite) [1]파일 다운로드1
13325정성태4/18/20234525스크립트: 48. 파이썬 - PostgreSQL의 with 문을 사용한 경우 연결 개체 누수
13324정성태4/17/20234356.NET Framework: 2108. C# - Octave의 "save -binary ..."로 생성한 바이너리 파일 분석파일 다운로드1
13323정성태4/16/20234287개발 환경 구성: 677. Octave에서 Excel read/write를 위한 io 패키지 설치
13322정성태4/15/20235063VS.NET IDE: 182. Visual Studio - 32비트로만 빌드된 ActiveX와 작업해야 한다면?
13321정성태4/14/20233890개발 환경 구성: 676. WSL/Linux Octave - Python 스크립트 연동
13320정성태4/13/20233867개발 환경 구성: 675. Windows Octave 8.1.0 - Python 스크립트 연동
13319정성태4/12/20234307개발 환경 구성: 674. WSL 2 환경에서 GNU Octave 설치
13318정성태4/11/20234142개발 환경 구성: 673. JetBrains IDE에서 "Squash Commits..." 메뉴가 비활성화된 경우
13317정성태4/11/20234234오류 유형: 855. WSL 2 Ubuntu 20.04 - error: cannot communicate with server: Post http://localhost/v2/snaps/...
13316정성태4/10/20233562오류 유형: 854. docker-compose 시 "json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)" 오류 발생
13315정성태4/10/20233760Windows: 245. Win32 - 시간 만료를 갖는 컨텍스트 메뉴와 윈도우 메시지의 영역별 정의파일 다운로드1
13314정성태4/9/20233847개발 환경 구성: 672. DosBox를 이용한 Turbo C, Windows 3.1 설치
13313정성태4/9/20233934개발 환경 구성: 671. Hyper-V VM에 Turbo C 2.0 설치 [2]
13312정성태4/8/20233945Windows: 244. Win32 - 시간 만료를 갖는 MessageBox 대화창 구현 (개선된 버전)파일 다운로드1
13311정성태4/7/20234459C/C++: 163. Visual Studio 2022 - DirectShow 예제 컴파일(WAV Dest)
13310정성태4/6/20234043C/C++: 162. Visual Studio - /NODEFAULTLIB 옵션 설정 후 수동으로 추가해야 할 library
13309정성태4/5/20234219.NET Framework: 2107. .NET 6+ FileStream의 구조 변화
13308정성태4/4/20234117스크립트: 47. 파이썬의 time.time() 실숫값을 GoLang / C#에서 사용하는 방법
13307정성태4/4/20233881.NET Framework: 2106. C# - .NET Core/5+ 환경의 Windows Forms 응용 프로그램에서 HINSTANCE 구하는 방법
13306정성태4/3/20233675Windows: 243. Win32 - 윈도우(cbWndExtra) 및 윈도우 클래스(cbClsExtra) 저장소 사용 방법
1  2  3  4  5  6  7  8  9  10  11  [12]  13  14  15  ...