Microsoft MVP성태의 닷넷 이야기
.NET Framework: 1121. C# - 동일한 IP:Port로 바인딩 가능한 서버 소켓 [링크 복사], [링크+제목 복사],
조회: 9149
글쓴 사람
정성태 (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)
13626정성태5/15/2024223Phone: 15. C# MAUI - MediaElement Source 경로 지정 방법파일 다운로드1
13625정성태5/14/2024421닷넷: 2262. C# - Exception Filter 조건(when)을 갖는 catch 절의 IL 구조
13624정성태5/12/2024656Phone: 14. C# - MAUI에서 MediaElement 사용파일 다운로드1
13623정성태5/11/2024799닷넷: 2261. C# - 구글 OAuth의 JWT (JSON Web Tokens) 해석파일 다운로드1
13622정성태5/10/2024849닷넷: 2260. C# - Google 로그인 연동 (ASP.NET 예제)파일 다운로드1
13621정성태5/10/2024779오류 유형: 902. IISExpress - Failed to register URL "..." for site "..." application "/". Error description: Cannot create a file when that file already exists. (0x800700b7)
13620정성태5/9/2024954VS.NET IDE: 190. Visual Studio가 node.exe를 경유해 Edge.exe를 띄우는 경우
13619정성태5/7/2024970닷넷: 2259. C# - decimal 저장소의 비트 구조파일 다운로드1
13618정성태5/6/20241102닷넷: 2258. C# - double (배정도 실수) 저장소의 비트 구조파일 다운로드1
13617정성태5/5/20241045닷넷: 2257. C# - float (단정도 실수) 저장소의 비트 구조파일 다운로드1
13616정성태5/3/2024986닷넷: 2256. ASP.NET Core 웹 사이트의 HTTP/HTTPS + Dual mode Socket (IPv4/IPv6) 지원 방법파일 다운로드1
13615정성태5/3/2024943닷넷: 2255. C# 배열을 Numpy ndarray 배열과 상호 변환
13614정성태5/2/2024869닷넷: 2254. C# - COM 인터페이스의 상속 시 중복으로 메서드를 선언
13613정성태5/1/2024902닷넷: 2253. C# - Video Capture 장치(Camera) 열거 및 지원 포맷 조회파일 다운로드1
13612정성태4/30/2024919오류 유형: 902. Visual Studio - error MSB3021: Unable to copy file
13611정성태4/29/2024934닷넷: 2252. C# - GUID 타입 전용의 UnmanagedType.LPStruct - 두 번째 이야기파일 다운로드1
13610정성태4/28/20241004닷넷: 2251. C# - 제네릭 인자를 가진 타입을 생성하는 방법 - 두 번째 이야기
13609정성태4/27/20241040닷넷: 2250. PInvoke 호출 시 참조 타입(class)을 마샬링하는 [IN], [OUT] 특성파일 다운로드1
13608정성태4/26/20241114닷넷: 2249. C# - 부모의 필드/프로퍼티에 대해 서로 다른 자식 클래스 간에 Reflection 접근이 동작할까요?파일 다운로드1
13607정성태4/25/20241121닷넷: 2248. C# - 인터페이스 타입의 다중 포인터를 인자로 갖는 C/C++ 함수 연동
13606정성태4/24/20241076닷넷: 2247. C# - tensorflow 연동 (MNIST 예제)파일 다운로드1
13605정성태4/23/20241087닷넷: 2246. C# - Python.NET을 이용한 파이썬 소스코드 연동파일 다운로드1
13604정성태4/22/20241062오류 유형: 901. Visual Studio - Unable to set the next statement. Set next statement cannot be used in '[Exception]' call stack frames.
13603정성태4/21/20241131닷넷: 2245. C# - IronPython을 이용한 파이썬 소스코드 연동파일 다운로드1
13602정성태4/20/20241069닷넷: 2244. C# - PCM 오디오 데이터를 연속(Streaming) 재생 (Windows Multimedia)파일 다운로드1
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...