Microsoft MVP성태의 닷넷 이야기
.NET Framework: 1121. C# - 동일한 IP:Port로 바인딩 가능한 서버 소켓 [링크 복사], [링크+제목 복사],
조회: 17536
글쓴 사람
정성태 (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" 옵션을 통해 기본 공유를 막았던 게 맞는 듯합니다.
정성태

... 76  77  78  79  80  81  82  83  [84]  85  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
11836정성태3/5/201923202오류 유형: 525. Visual Studio 2019 Preview 4/RC - C# 8.0 Missing compiler required member 'System.Range..ctor' [1]
11835정성태3/5/201921716.NET Framework: 810. C# 8.0의 Index/Range 연산자를 .NET Framework에서 사용하는 방법 및 비동기 스트림의 컴파일 방법 [3]파일 다운로드1
11834정성태3/4/201920562개발 환경 구성: 432. Visual Studio 없이 최신 C# (8.0) 컴파일러를 사용하는 방법
11833정성태3/4/201921065개발 환경 구성: 431. Visual Studio 2019 - CMake를 이용한 공유/실행(so/out) 리눅스 프로젝트 설정파일 다운로드1
11832정성태3/4/201916995오류 유형: 524. Visual Studio CMake - rsync: connection unexpectedly closed
11831정성태3/4/201916808오류 유형: 523. Visual Studio 2019 - 새 창으로 뜬 윈도우를 닫을 때 비정상 종료
11830정성태2/26/201916501오류 유형: 522. 이벤트 로그 - Error opening event log file State. Log will not be processed. Return code from OpenEventLog is 87.
11829정성태2/26/201918255개발 환경 구성: 430. 마이크로소프트의 CoreCLR 프로파일러 예제 빌드 방법 - 리눅스 환경 [1]
11828정성태2/26/201926128개발 환경 구성: 429. Component Services 관리자의 RuntimeBroker 설정이 2개 있는 경우 [8]
11827정성태2/26/201919054오류 유형: 521. Visual Studio - Could not start the 'rsync' command on the remote host, please install it using your system package manager.
11826정성태2/26/201919244오류 유형: 520. 우분투에 .NET Core SDK 설치 시 패키지 의존성 오류
11825정성태2/25/201924453개발 환경 구성: 428. Visual Studio 2019 - CMake를 이용한 리눅스 빌드 환경 설정 [1]
11824정성태2/25/201918896오류 유형: 519. The SNMP Service encountered an error while accessing the registry key SYSTEM\CurrentControlSet\Services\SNMP\Parameters\TrapConfiguration. [1]
11823정성태2/21/201920616오류 유형: 518. IIS 관리 콘솔이 뜨지 않는 문제
11822정성태2/20/201918909오류 유형: 517. docker에 설치한 MongoDB 서버로 연결이 안 되는 경우
11821정성태2/20/201919676오류 유형: 516. Visual Studio 2019 - This extension uses deprecated APIs and is at risk of not functioning in a future VS update. [1]
11820정성태2/20/201922742오류 유형: 515. 윈도우 10 1809 업데이트 후 "User Profiles Service" 1534 경고 발생
11819정성태2/20/201922027Windows: 158. 컴퓨터와 사용자의 SID(security identifier) 확인 방법
11818정성태2/20/201920067VS.NET IDE: 131. Visual Studio 2019 Preview의 닷넷 프로젝트 빌드가 20초 이상 걸리는 경우 [2]
11817정성태2/17/201916446오류 유형: 514. WinDbg Preview 실행 오류 - Error : DbgX.dll : WindowsDebugger.WindowsDebuggerException: Could not load dbgeng.dll
11816정성태2/17/201919855Windows: 157. 윈도우 스토어 앱(Microsoft Store App)을 명령행에서 직접 실행하는 방법
11815정성태2/14/201918102오류 유형: 513. Visual Studio 2019 - VSIX 설치 시 "The extension cannot be installed to this product due to prerequisites that cannot be resolved." 오류 발생
11814정성태2/12/201916964오류 유형: 512. VM(가상 머신)의 NT 서비스들이 자동 시작되지 않는 문제
11813정성태2/12/201918312.NET Framework: 809. C# - ("Save File Dialog" 등의) 대화 창에 확장 속성을 보이는 방법
11812정성태2/11/201915610오류 유형: 511. Windows Server 2003 VM 부팅 후 로그인 시점에 0xC0000005 BSOD 발생
11811정성태2/11/201920799오류 유형: 510. 서버 운영체제에 NVIDIA GeForce Experience 실행 시 wlanapi.dll 누락 문제
... 76  77  78  79  80  81  82  83  [84]  85  86  87  88  89  90  ...