Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

(시리즈 글이 4개 있습니다.)
Linux: 69. 리눅스 - "Docker Desktop for Windows" Container 환경에서 IPv6 Loopback Address 바인딩 오류
; https://www.sysnet.pe.kr/2/0/13540

개발 환경 구성: 705. "Docker Desktop for Windows" - ASP.NET Core 응용 프로그램의 소켓 주소 바인딩(IPv4/IPv6 loopback, Any)
; https://www.sysnet.pe.kr/2/0/13548

개발 환경 구성: 706. C# - 컨테이너에서 실행하기 위한 (소켓) 콘솔 프로젝트 구성
; https://www.sysnet.pe.kr/2/0/13549

닷넷: 2226. C# - "Docker Desktop for Windows" Container 환경에서의 IPv6 DualMode 소켓
; https://www.sysnet.pe.kr/2/0/13574




C# - "Docker Desktop for Windows" Container 환경에서의 IPv6 DualMode 소켓

지난 글에서,

리눅스 - "Docker Desktop for Windows" Container 환경에서 IPv6 Loopback Address 바인딩 오류
; https://www.sysnet.pe.kr/2/0/13540

Docker Desktop for Windows 환경의 (기본) container에서는 IPv6의 Loopback Address 바인딩이 안 된다고 했습니다. 반면 IPv6.Any에 대해서는 바인딩이 되는데요, 따라서 소켓 바인딩을 다음과 같은 예제로 구성해,

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

namespace ConsoleApp2;

internal class Program
{
    static void Main(string[] args)
    {
        Socket socket = new Socket(AddressFamily.InterNetworkV6,
            SocketType.Stream, ProtocolType.Tcp);

        IPEndPoint ep = new IPEndPoint(IPAddress.IPv6Any, 16000);
        Console.WriteLine(ep);

        socket.Bind(ep);
        socket.Listen(10);
        Thread t = new Thread(() =>
        {
            byte[] buffer = new byte[10];
            while (true)
            {
                Socket client = socket.Accept();
                Console.WriteLine("Client connected");

                int recvBytes = client.Receive(buffer);
                client.Send(new byte[] { 1, 2, 3, 4 });
                client.Close();
            }
        });

        t.Start();
        t.Join();

        socket.Close();
    }
}

Docker Desktop for Windows의 컨테이너로 실행하면, 분명히 다음과 같이 16000 IPv6 LISTEN 상태의 서버 소켓을 확인할 수 있습니다.

$ netstat -an
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp6       0      0 :::16000                :::*                    LISTEN
...[생략]...

하지만, 지난번과 마찬가지로 컨테이너 내에서의 curl 등을 이용한 서버 소켓 연결은 실패합니다.

$ curl http://[::1]:16000
curl: (7) Failed to connect to ::1 port 16000 after 0 ms: Couldn't connect to server

그런데 이상한 건, 컨테이너 외부에서의 연결도 실패한다는 점입니다.

// Docker desktop을 호스팅하는 윈도우 측에서 접속

c:\temp> curl [::1]:32700
curl: (52) Empty reply from server

(왜 "Empty reply from server" 오류가 발생하는지에 대해선 이전 글에서 설명했습니다.)




이상하지 않나요? ^^ ASP.NET Core 프로젝트의 경우에는 적어도 외부에서 접근은 되었는데, 왜 우리가 만든 IPv6 서버 소켓은 그게 안 되는 것일까요?

이유는, ASP.NET Core가 IPv6 바인딩을 한 것이 아니고, Dual Mode 소켓을 바인딩했기 때문입니다. 예전에도 한 번 소개한 적이 있었죠? ^^

C# - IPv4, IPv6를 모두 지원하는 서버 소켓 생성 방법
; https://www.sysnet.pe.kr/2/0/13091

윈도우와 마찬가지로, 리눅스 역시 DualMode 바인딩을 지원하기 때문에 우리가 만든 소켓 프로그램도 다음과 같이 수정하면 됩니다.

// AddressFamily를 생략해 Dual Mode 소켓 바인딩 사용
Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
Console.WriteLine($"{nameof(socket.DualMode)}: {socket.DualMode}"); // 출력 결과: DualMode: True

IPEndPoint ep = new IPEndPoint(IPAddress.IPv6Any, 16000);
socket.Bind(ep); // IPv6와 IPv4 모두 바인딩




참고로, 아무리 DualMode 바인딩이라고 해도 Loopback 주소로 바인딩하면 이전에 설명한 "Cannot assign requested address" 예외가 발생합니다.

Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
Console.WriteLine($"{nameof(socket.DualMode)}: {socket.DualMode}"); // 출력 결과: DualMode: True

IPEndPoint ep = new IPEndPoint(IPAddress.IPv6Loopback, 16000);
socket.Bind(ep); 

/* 예외 발생: System.Net.Sockets.SocketException
  HResult=0x80004005
  Message=Cannot assign requested address
  Source=System.Net.Sockets
  StackTrace:
   at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.Sockets.Socket.Bind(EndPoint localEP)
   at ConsoleApp2.Program.Main(String[] args)
*/

ASP.NET Core 웹 앱에서도 발생했던 그 오류입니다.

// ...[생략]...
info: Microsoft.AspNetCore.Server.Kestrel[0]
      Unable to bind to http://localhost:8080 on the IPv6 loopback interface: 'Cannot assign requested address'.
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:8080
// ...[생략]...

그래도 ASP.NET Core가 저렇게 결국 바인딩이 되었다는 것은, 아마도 IPv6 DualMode 바인딩이 실패한 경우 IPv4로 다시 시도하는 코드로 작성되었을 거라고 예측할 수 있습니다.




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







[최초 등록일: ]
[최종 수정일: 3/6/2024]

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)
13490정성태12/19/20232402개발 환경 구성: 698. Golang - GLIBC 의존을 없애는 정적 빌드 방법
13489정성태12/19/20232178개발 환경 구성: 697. GoLand에서 ldflags 지정 방법
13488정성태12/18/20232115오류 유형: 884. HTTP 500.0 - 명령행에서 실행한 ASP.NET Core 응용 프로그램을 실행하는 방법
13487정성태12/16/20232417개발 환경 구성: 696. C# - 리눅스용 AOT 빌드를 docker에서 수행 [1]
13486정성태12/15/20232233개발 환경 구성: 695. Nuget config 파일에 값 설정/삭제 방법
13485정성태12/15/20232124오류 유형: 883. dotnet build/restore - error : Root element is missing
13484정성태12/14/20232202개발 환경 구성: 694. Windows 디렉터리 경로를 WSL의 /mnt 포맷으로 구하는 방법
13483정성태12/14/20232341닷넷: 2184. C# - 하나의 resource 파일을 여러 프로그램에서 (AOT 시에도) 사용하는 방법파일 다운로드1
13482정성태12/13/20233028닷넷: 2183. C# - eFriend Expert OCX 예제를 .NET Core/5+ Console App에서 사용하는 방법 [2]파일 다운로드1
13481정성태12/13/20232322개발 환경 구성: 693. msbuild - .NET Core/5+ 프로젝트에서 resgen을 이용한 리소스 파일 생성 방법파일 다운로드1
13480정성태12/12/20232719개발 환경 구성: 692. Windows WSL 2 + Chrome 웹 브라우저 설치
13479정성태12/11/20232377개발 환경 구성: 691. WSL 2 (Ubuntu) + nginx 환경 설정
13477정성태12/8/20232635닷넷: 2182. C# - .NET 7부터 추가된 Int128, UInt128 [1]파일 다운로드1
13476정성태12/8/20232322닷넷: 2181. C# - .NET 8 JsonStringEnumConverter의 AOT를 위한 개선파일 다운로드1
13475정성태12/7/20232420닷넷: 2180. .NET 8 - 함수 포인터에 대한 Reflection 정보 조회파일 다운로드1
13474정성태12/6/20232235개발 환경 구성: 690. 닷넷 코어/5+ 버전의 ilasm/ildasm 실행 파일 구하는 방법 - 두 번째 이야기
13473정성태12/5/20232513닷넷: 2179. C# - 값 형식(Blittable)을 메모리 복사를 이용해 바이트 배열로 직렬화/역직렬화파일 다운로드1
13472정성태12/4/20232251C/C++: 164. Visual C++ - InterlockedCompareExchange128 사용 방법
13471정성태12/4/20232363Copilot - To enable GitHub Copilot, authorize this extension using GitHub's device flow
13470정성태12/2/20232688닷넷: 2178. C# - .NET 8부터 COM Interop에 대한 자동 소스 코드 생성 도입파일 다운로드1
13469정성태12/1/20232457닷넷: 2177. C# - (Interop DLL 없이) CoClass를 이용한 COM 개체 생성 방법파일 다운로드1
13468정성태12/1/20232354닷넷: 2176. C# - .NET Core/5+부터 달라진 RCW(Runtime Callable Wrapper) 대응 방식파일 다운로드1
13467정성태11/30/20232457오류 유형: 882. C# - Unhandled exception. System.Runtime.InteropServices.COMException (0x800080A5)파일 다운로드1
13466정성태11/29/20232622닷넷: 2175. C# - DllImport 메서드의 AOT 지원을 위한 LibraryImport 옵션
13465정성태11/28/20232362개발 환경 구성: 689. MSBuild - CopyToOutputDirectory가 "dotnet publish" 시에는 적용되지 않는 문제파일 다운로드1
13464정성태11/28/20232496닷넷: 2174. C# - .NET 7부터 UnmanagedCallersOnly 함수 export 기능을 AOT 빌드에 통합파일 다운로드1
1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...