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

1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13431정성태10/31/20232773스크립트: 60. 파이썬 - 비동기 FastAPI 앱을 gunicorn으로 호스팅
13430정성태10/30/20232668닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법
13429정성태10/27/20232955닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제파일 다운로드1
13428정성태10/25/20233017닷넷: 2151. C# 12 - ref readonly 매개변수
13427정성태10/18/20233219닷넷: 2150. C# 12 - 정적 문맥에서 인스턴스 멤버에 대한 nameof 접근 허용(Allow nameof to always access instance members from static context)
13426정성태10/13/20233385스크립트: 59. 파이썬 - 비동기 호출 함수(run_until_complete, run_in_executor, create_task, run_in_threadpool)
13425정성태10/11/20233187닷넷: 2149. C# - PLinq의 Partitioner<T>를 이용한 사용자 정의 분할파일 다운로드1
13423정성태10/6/20233167스크립트: 58. 파이썬 - async/await 기본 사용법
13422정성태10/5/20233311닷넷: 2148. C# - async 유무에 따른 awaitable 메서드의 병렬 및 예외 처리
13421정성태10/4/20233369닷넷: 2147. C# - 비동기 메서드의 async 예약어 유무에 따른 차이
13420정성태9/26/20235556스크립트: 57. 파이썬 - UnboundLocalError: cannot access local variable '...' where it is not associated with a value
13419정성태9/25/20233210스크립트: 56. 파이썬 - RuntimeError: dictionary changed size during iteration
13418정성태9/25/20233905닷넷: 2146. C# - ConcurrentDictionary 자료 구조의 동기화 방식
13417정성태9/19/20233439닷넷: 2145. C# - 제네릭의 형식 매개변수에 속한 (매개변수를 가진) 생성자를 호출하는 방법
13416정성태9/19/20233252오류 유형: 877. redis-py - MISCONF Redis is configured to save RDB snapshots, ...
13415정성태9/18/20233744닷넷: 2144. C# 12 - 컬렉션 식(Collection Expressions)
13414정성태9/16/20233501디버깅 기술: 193. Windbg - ThreadStatic 필드 값을 조사하는 방법
13413정성태9/14/20233699닷넷: 2143. C# - 시스템 Time Zone 변경 시 이벤트 알림을 받는 방법
13412정성태9/14/20236976닷넷: 2142. C# 12 - 인라인 배열(Inline Arrays) [1]
13411정성태9/12/20233477Windows: 252. 권한 상승 전/후 따로 관리되는 공유 네트워크 드라이브 정보
13410정성태9/11/20235000닷넷: 2141. C# 12 - Interceptor (컴파일 시에 메서드 호출 재작성) [1]
13409정성태9/8/20233860닷넷: 2140. C# - Win32 API를 이용한 모니터 전원 끄기
13408정성태9/5/20233819Windows: 251. 임의로 만든 EXE 파일을 포함한 ZIP 파일의 압축을 해제할 때 Windows Defender에 의해 삭제되는 경우
13407정성태9/4/20233574닷넷: 2139. C# - ParallelEnumerable을 이용한 IEnumerable에 대한 병렬 처리
13406정성태9/4/20233541VS.NET IDE: 186. Visual Studio Community 버전의 라이선스
13405정성태9/3/20233973닷넷: 2138. C# - async 메서드 호출 원칙
1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...