Microsoft MVP성태의 닷넷 이야기
.NET Framework: 1121. C# - 동일한 IP:Port로 바인딩 가능한 서버 소켓 [링크 복사], [링크+제목 복사],
조회: 22017
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

C# - 동일한 IP:Port로 바인딩 가능한 서버 소켓

Python flask app을 실습하면서, 실수로 PyCharm에서도 디버깅을 시작하고 명령행에서도 "flask run"을 했는데요, 동일하게 127.0.0.1:5000으로 바인딩한 응용 프로그램이 아무런 문제 없이 잘 실행이 됩니다.

재미있는 것은, 이후에 실행된 응용 프로그램이 소켓 accept를 할 수 있고, 그 프로그램이 종료하면 다시 예전 프로그램이 아무런 일도 없었다는 듯이 소켓 accept 동작을 이어갑니다.

실제로 netstat로 확인하면 이렇게 서로 다른 프로세스(python.exe)가 동일한 IP:Port 바인딩을 열고 있습니다.

C:\temp> netstat -ano | findstr 5000 | findstr LISTEN
  TCP    127.0.0.1:5000         0.0.0.0:0              LISTENING       20332
  TCP    127.0.0.1:5000         0.0.0.0:0              LISTENING       10220

/*
PS> Get-Process -Id (Get-NetTcpConnection -LocalPort 5000).OwningProcess

Handles  NPM(K)    PM(K)      WS(K)     CPU(s)     Id  SI ProcessName
-------  ------    -----      -----     ------     --  -- -----------
    144       9     1568       6292       0.02  18424   1 wslhost
*/

오호... 재미있군요. ^^ 이에 대해 검색해 보니 저같은 사람이 이미 있었습니다.

Flask allows multiple server instances to listen on the same port
; https://stackoverflow.com/questions/47786463/flask-allows-multiple-server-instances-to-listen-on-the-same-port




문서를 보면,

SO_EXCLUSIVEADDRUSE socket option
; https://learn.microsoft.com/en-us/windows/win32/winsock/so-exclusiveaddruse

In the case where the first bind sets no options or SO_REUSEADDR, and the second bind performs a SO_REUSEADDR, the second socket has overtaken the port and behavior regarding which socket will receive packets is undetermined. SO_EXCLUSIVEADDRUSE was introduced to address this situation.


첫 번째 프로그램이 아무런 옵션 없이, 또는 SO_REUSEADDR를 사용해 바인딩한 경우 이후의 프로그램에서 SO_REUSEADDR를 사용해 해당 바인딩을 점유할 수 있다고 합니다.

정말 그런지 테스트를 해볼까요? ^^ 우선, 아무런 옵션 없이 준 경우로,

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

internal class Program
{
    static void Main(string[] args)
    {
        IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Loopback, 11000);
        Socket listener = new Socket(AddressFamily.InterNetwork, 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());
        }
    }
}

빌드해 2개의 인스턴스를 띄워보면 첫 번째를 제외하고는 화면에 아래와 같은 식의 에러 메시지가 나오는 것을 볼 수 있습니다.

System.Net.Sockets.SocketException (10048): Only one usage of each socket address (protocol/network address/port) is normally permitted.
   at System.Net.Sockets.Socket.UpdateStatusAfterSocketErrorAndThrowException(SocketError error, String callerName)
   at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.Sockets.Socket.Bind(EndPoint localEP)
   at Program.Main(String[] args)

자, 그럼 테스트를 쉽게 하기 위해 명령행 인자의 수에 따라 SO_REUSEADDR 옵션을 제어하도록 바꾼 다음,

if (args.Length >= 1)
{
    listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
}

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

/* 첫 번째 인스턴스
C:\temp> ConsoleApp1
Waiting for a connection...
*/

/* 두 번째 인스턴스
C:\temp> ConsoleApp1 1
System.Net.Sockets.SocketException [...예외 발생...]
*/

실행해 보면, 보는 바와 같이 처음 실행한 프로그램에서 아무런 옵션을 주지 않으면 두 번째 프로그램에서 SO_REUSEADDR 옵션을 주더라도 이전과 마찬가지로 예외가 발생합니다. 즉, 문서의 내용이 틀린 것인데요, 어쩌면 문서의 내용에서 "Minimum supported client"가 "Windows 2000 Professional"이니만큼 저 당시에는 SO_EXCLUSIVEADDRUSE 옵션이 명시적으로 필요했을지도 모릅니다.

하지만, 2개의 프로그램 모두 SO_REUSEADDR 옵션을 적용해 실행하는 것은 잘 됩니다.

/* 첫 번째 인스턴스
C:\temp> ConsoleApp1 1
Waiting for a connection...
*/

/* 두 번째 인스턴스
C:\temp> ConsoleApp1 1
Waiting for a connection...
*/

그러니까, "flask"는 윈도우 버전인 경우 명시적으로 (굳이?) SO_REUSEADDR 옵션을 적용하고 있었던 것입니다.




저렇게 보면, SO_EXCLUSIVEADDRUSE 옵션이 왜 있는 것인가??? 의문입니다. 혹시 이 옵션에 대한 차이점을 재현할 수 있는 방법을 아시는 분은 덧글 부탁드립니다.

아울러, SO_REUSEADDR 옵션의 클라이언트 측 소켓 사용은 아래의 글에서 예시를 한번 든 적이 있습니다.

윈도우 환경에서 클라이언트 소켓의 최대 접속 수 (2) - SO_REUSEADDR
; https://www.sysnet.pe.kr/2/0/12432

그리고, 윈도우의 경우 HttpListener를 사용하면 동일한 포트에 대해 (점유하는 방식이 아닌) 경로를 달리해 바인딩하는 것을 지원하는 것도 가능하니 참고하시고. ^^

IIS의 80 포트를 공유하는 응용 프로그램 만드는 방법
; https://www.sysnet.pe.kr/2/0/1555




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







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

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

비밀번호

댓글 작성자
 



2021-11-24 12시06분
[kernel] 기본값과 SO_EXCLUSIVEADDRUSE 설정의 차이는 이 문서의 비교 테이블을 참고하시면 될 것 같은데요.

https://learn.microsoft.com/ko-kr/windows/win32/winsock/using-so-reuseaddr-and-so-exclusiveaddruse#enhanced-socket-security
[guest]
2021-11-24 09시25분
@kernel 감사합니다. ^^ 올려주신 문서의 비교 테이블이 아주 명확하게 차이점을 설명하고 있군요.

게다가 제가 글에서 예상한 것을, "In Windows Server 2003, sockets are not in a sharable state by default."라고 2003 서버가 언급되는 걸로 봐서 2000 서버에서는 기본적으로 소켓이 공유 가능한 상태였고, 그 시대에는 "SO_EXCLUSIVEADDRUSE" 옵션을 통해 기본 공유를 막았던 게 맞는 듯합니다.
정성태

... 106  107  108  109  110  111  112  113  114  115  116  [117]  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11091정성태11/3/201628949VC++: 104. std::call_once를 이용해 thread-safe한 Singleton 객체 생성파일 다운로드1
11090정성태11/1/201630509VC++: 103. C++ CreateTimerQueue, CreateTimerQueueTimer 예제 코드 [9]파일 다운로드1
11089정성태11/1/201631186디버깅 기술: 82. Windows 10을 위한 Symbol(PDB) 파일 내려받는 방법 [2]
11088정성태11/1/201633168.NET Framework: 617. C# - AForge.NET을 이용한 MP4 동영상 파일 재생 [7]파일 다운로드1
11087정성태11/1/201627440.NET Framework: 616. AForge.Video.FFMPEG를 최신 버전의 ffmpeg 파일로 의존성을 변경하는 방법파일 다운로드1
11086정성태11/1/201622279오류 유형: 366. The Microsoft Passport Container service terminated with the following error: General access denied error
11085정성태10/27/201637648.NET Framework: 615. C# - AForge.NET을 이용한 웹캠 영상 출력 [2]파일 다운로드1
11084정성태10/26/201625211오류 유형: 365. The User Profile Service service failed to the sign-in.
11083정성태10/26/201631668Windows: 131. 윈도우 10에서 사라진 "Adapters and Bindings" 네트워크 우선 순위 조정 기능 [1]
11082정성태10/26/201634645.NET Framework: 614. C# - DateTime.Ticks의 정밀도 [4]파일 다운로드1
11081정성태10/26/201623925오류 유형: 364. You need to fix your Microsoft Account for apps on your other devices to be able to launch apps and continue experiences on this device.
11080정성태10/24/201628148Windows: 130. Windows Server 2016 Nano 서버 설치 방법
11079정성태10/21/201625114Windows: 129. Windows Server 2016 설치 CD에 있는 Convert-WindowsImage.ps1 사용 방법 정리
11078정성태10/21/201626316Windows: 128. Windows Server 2016 Nano 서버 VHD 이미지 만드는 방법 - TP5 기준
11077정성태10/21/201623935오류 유형: 363. Active Directory 서버의 NETLOGON 서비스가 멈췄을 때 발생하는 문제
11076정성태10/21/201624180오류 유형: 362. 윈도우 백업 시 오류 - 0x80780040
11075정성태10/20/201623954Windows: 127. Convert-WindowsImage.ps1 사용 방법 정리
11074정성태10/20/201633464Windows: 126. Windows Server 2016 평가판을 정식 버전으로 라이선스 변경하는 방법
11073정성태10/20/201629866.NET Framework: 613. 윈도우 데스크톱 응용 프로그램(예: Console)에서 알림 메시지(Toast notifications) 띄우기 [1]파일 다운로드1
11072정성태10/20/201626709VC++: 102. 새로 추가한 ATL COM 객체가 regsvr32.exe로 등록이 안 되는 문제
11071정성태10/20/201629657.NET Framework: 612. UWP(유니버설 윈도우 플랫폼) 앱에서 콜백 함수 내에서의 UI 요소 접근 방법 [1]
11070정성태10/20/201622752Windows: 125. 윈도우 서버 2016 마이그레이션
11069정성태10/19/201631074.NET Framework: 611. C++ 개발자들을 위한 C# Thread 동작 방식 [2]
11068정성태10/19/201633858Windows: 124. 윈도우 운영체제의 시간 함수 (5) - TSC(Time Stamp Counter)와 QueryPerformanceCounter [12]파일 다운로드1
11067정성태10/18/201629215Windows: 123. 윈도우 운영체제의 시간 함수 (4) - RTC, TSC, PM Clock, HPET Timer [2]
11066정성태10/17/201628827Windows: 122. 윈도우 운영체제의 시간 함수 (3) - QueryInterruptTimePrecise, QueryInterruptTime 함수파일 다운로드1
... 106  107  108  109  110  111  112  113  114  115  116  [117]  118  119  120  ...