Microsoft MVP성태의 닷넷 이야기
Linux: 19. C# - .NET Core Unix Domain Socket 사용 예제 [링크 복사], [링크+제목 복사],
조회: 20535
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 8개 있습니다.)

C# - .NET Core Unix Domain Socket 사용 예제

Unix Domain Socket 방식이 .NET Core 2.1부터 추가되었습니다.

UnixDomainSocketEndPoint
; https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.unixdomainsocketendpoint?view=netstandard-2.1

Unix Domain Socket의 대표적인 특징은, 파일 경로가 EndPoint가 되어 동일한 시스템 안에서 IPC 수단으로 사용할 수 있다는 점입니다. (로컬 파일 시스템의 파일 경로를 지정하는 것이기 때문에 당연히 다른 시스템에서는 접근할 방법이 없습니다.)

사용법은 일반 Socket 통신과 동일한데, 단지 EndPoint만 IP 주소가 아니라 파일 경로를 지정하는 식입니다.

static string path = "/tmp/testd.sock";

[서버 측]
    using (var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP))
    {
        var unixEp = new UnixDomainSocketEndPoint(path);
        socket.Bind(unixEp);
        socket.Listen(5);
        using (Socket clntSocket = socket.Accept())
        {
            Console.WriteLine("[Server] ClientConencted");
            // ... 소켓 통신 ...
        }
    }

[클라이언트 측]
        var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
        var unixEp = new UnixDomainSocketEndPoint(path);

        socket.Connect(unixEp);
        // ... 소켓 통신 ...
        socket.Close();

별거 없죠? ^^ 이게 끝입니다.

(이 글의 예제 코드는 github - UnixDomainSocketSample에서 제공합니다.)




이러한 Unix Domain Socket의 특성상 다른 Socket 통신과 비교해 "포트" 고민은 안 해도 되지만, 파일 경로의 고민은 해야 합니다. 위의 예제에서는 "/tmp" 폴더를 선택했는데 아래의 글에서도 설명했지만,

.NET Core - System.PlatformNotSupportedException: The named version of this synchronization primitive is not supported on this platform.
; https://www.sysnet.pe.kr/2/0/11903

리눅스는 /tmp 폴더의 내용을 주기적으로 삭제하는 daemon 프로세스인,

Using /tmp/ And /var/tmp/ Safely
; https://systemd.io/TEMPORARY_DIRECTORIES.html

systemd-tmpfiles 또는 tmpwatch 등에 의해 /tmp는 보통 10일, /var/tmp는 30일 동안 해당 파일이 change 또는 read된 적이 없다면 정리한다고 하므로 이에 대해 주의를 해야 합니다. 여기서 문제는, Domain Socket 파일은 Socket Read/Write 시 날짜 변경이 이뤄지지 않습니다. 따라서 해당 기간 동안 응용 프로그램이 살아 있는 Daemon 형식의 프로세스라면 이것이 문제가 될 수 있습니다.

따라서 이런 부분이 염려가 된다면 다른 폴더를 지정해야 하는데, /var/run 디렉터리, 또는 그 하위에 응용 프로그램만의 디렉터리를 만들어 그 안에 Domain Socket용 파일을 생성하면 됩니다.

static string _unixSocket = "/var/run/yourappdir/testd.sock";

그런데 여기서 또다시 문제가 있는데, "/var/run" 디렉터리에는 일반 사용자 권한으로 쓰기가 금지되어 있다는 점입니다.

$ cd /var/run

$ echo "test" > test.txt
bash: test.txt: Permission denied

$ ls /var -l
total 0
...[생략]...
lrwxrwxrwx 1 root root     4 Sep 23  2017 run -> /run
...[생략]...

$ ls / -l
...[생략]...
drwxr-xr-x  1 root root    512 Jun 29 14:12 run
...[생략]...

따라서, 설치 프로그램 단계부터 이를 고려해 /var/run 하위에 일반 사용자 권한으로 쓰기가 가능한 디렉터리를 하나 생성하든가, 아니면 아예 tmp는 잊어버리고 해당 프로그램이 설치된 디렉터리 하위를 Domain Socket용 파일 경로로 쓰는 것이 좋습니다.




또 하나 알아야 할 점이 있다면, 당연히 소켓 자원의 해제에 상관없이 Domain 소켓의 EndPoint로 사용한 파일(이 글에서는 testd.sock)은 그대로 남아 있다는 점입니다. 만약 동일한 파일 명이 남아 다음번 소켓 사용 시 Bind 작업을 하면 이미 주소가 사용 중이라는 예외가 발생합니다.

System.Net.Sockets.SocketException (98): Address already in use
   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 testd.Program.threadFunc() in /home/tusr/testd/Program.cs:line 42

따라서 서버 측 소켓의 경우에는 Bind 전 파일 유무를 체크하는 것이 좋습니다.

if (File.Exists(path) == true)
{
    File.Delete(path); // unlink
}




그래도 또 하나 더 주의할 점이 있습니다. 파일 생성은 프로세스의 계정 권한을 따라가기 때문에 만약 root 사용자 권한에서 Unix Domain Socket을 생성했다면 일반 사용자 계정의 프로세스에서는 해당 소켓에 접속 시 권한 예외가 발생합니다.

System.Net.Sockets.SocketException (13): Permission denied
   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 testd.Program.threadFunc() in /home/tusr/testd/Program.cs:line 43

Unhandled Exception: System.Net.Internals.SocketExceptionFactory+ExtendedSocketException: Cannot assign requested address /var/run/testd.sock
   at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.Sockets.Socket.Connect(EndPoint remoteEP)
   at testd.Program.Main(String[] args) in /home/tusr/testd/Program.cs:line 25

따라서 이런 경우에는 서버 측 소켓에서 Bind 후, 해당 파일의 권한을 일반 사용자 권한도 접근할 수 있도록 조정을 해야 합니다.

==== Linux 환경 ====
$ chmod 766 /var/run/myapp/testd.sock

// C#
Process.Start("chmod", "766 /var/run/myapp/testd.sock"); // srwxrw-rw-

==== Windows 환경 ====
FileSecurity securityRules = new FileSecurity();
var sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);

securityRules.AddAccessRule(new FileSystemAccessRule(sid, FileSystemRights.FullControl, AccessControlType.Allow));
securityRules.AddAccessRule(new FileSystemAccessRule(sid, FileSystemRights.ChangePermissions, AccessControlType.Allow));

File.SetAccessControl("...tested.sock_file_path...", securityRules);




Windows 10부터 Unix Domain Socket이 지원된다는 소식이 있었습니다.

AF_UNIX comes to Windows
; https://devblogs.microsoft.com/commandline/af_unix-comes-to-windows/

사용법은 위에서 소개한 것과 다르지 않고 단지 파일 경로만 조정해 주면 됩니다. Linux와는 달리 temp 폴더를 주기적으로 삭제하는 프로그램이 없긴 해도 사용자에 의해 언제든 삭제될 수 있으므로 %TEMP% 폴더를 사용하는 것은 주의를 해야 합니다. (도메인 소켓 파일은 잠겨 있지 않으므로 삭제가 됩니다.)




.NET Core 2.1부터, Unix Domain Socket 통신 방식이 제공되지만 2.0 이하에서도 다음의 글에 추가된,

How to connect to a Unix Domain Socket in .NET Core in C#
; https://stackoverflow.com/questions/40195290/how-to-connect-to-a-unix-domain-socket-in-net-core-in-c-sharp

UnixEndPoint 타입을 추가하면 동일하게 구현할 수 있습니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 8/2/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)
13667정성태7/7/20246608닷넷: 2273. C# - 리눅스 환경에서의 Hyper-V Socket 연동 (AF_VSOCK)파일 다운로드1
13666정성태7/7/20247686Linux: 74. C++ - Vsock 예제 (Hyper-V Socket 연동)파일 다운로드1
13665정성태7/6/20247863Linux: 73. Linux 측의 socat을 이용한 Hyper-V 호스트와의 vsock 테스트파일 다운로드1
13663정성태7/5/20247470닷넷: 2272. C# - Hyper-V Socket 통신(AF_HYPERV, AF_VSOCK)의 VMID Wildcards 유형파일 다운로드1
13662정성태7/4/20247478닷넷: 2271. C# - WSL 2 VM의 VM ID를 알아내는 방법 - Host Compute System API파일 다운로드1
13661정성태7/3/20247398Linux: 72. g++ - 다른 버전의 GLIBC로 소스코드 빌드
13660정성태7/3/20247504오류 유형: 912. Visual C++ - Linux 프로젝트 빌드 오류
13659정성태7/1/20247843개발 환경 구성: 715. Windows - WSL 2 환경의 Docker Desktop 네트워크
13658정성태6/28/20248219개발 환경 구성: 714. WSL 2 인스턴스와 호스트 측의 Hyper-V에 운영 중인 VM과 네트워크 연결을 하는 방법 - 두 번째 이야기
13657정성태6/27/20247901닷넷: 2270. C# - Hyper-V Socket 통신(AF_HYPERV, AF_VSOCK)을 위한 EndPoint 사용자 정의
13656정성태6/27/20248068Windows: 264. WSL 2 VM의 swap 파일 위치
13655정성태6/24/20247843닷넷: 2269. C# - Win32 Resource 포맷 해석파일 다운로드1
13654정성태6/24/20247787오류 유형: 911. shutdown - The entered computer name is not valid or remote shutdown is not supported on the target computer.
13653정성태6/22/20247925닷넷: 2268. C# 코드에서 MAKEINTREOURCE 매크로 처리
13652정성태6/21/20249236닷넷: 2267. C# - Linux 환경에서 (Reflection 없이) DLL AssemblyFileVersion 구하는 방법파일 다운로드2
13651정성태6/19/20248472닷넷: 2266. C# - (Reflection 없이) DLL AssemblyFileVersion 구하는 방법파일 다운로드1
13650정성태6/18/20248397개발 환경 구성: 713. "WSL --debug-shell"로 살펴보는 WSL 2 VM의 리눅스 환경
13649정성태6/18/20247947오류 유형: 910. windbg - !py 확장 명령어 실행 시 "failed to find python interpreter" (2)
13648정성태6/17/20248264오류 유형: 909. C# - DynamicMethod 사용 시 System.TypeAccessException
13647정성태6/16/20249324개발 환경 구성: 712. Windows - WSL 2의 네트워크 통신 방법 - 세 번째 이야기 (같은 IP를 공유하는 WSL 2 인스턴스) [1]
13646정성태6/14/20247744오류 유형: 908. Process Explorer - "Error configuring dump resources: The system cannot find the file specified."
13645정성태6/13/20248197개발 환경 구성: 711. Visual Studio로 개발 시 기본 등록하는 dev tag 이미지로 Docker Desktop k8s에서 실행하는 방법
13644정성태6/12/20248855닷넷: 2265. C# - System.Text.Json의 기본적인 (한글 등에서의) escape 처리 [1]
13643정성태6/12/20248303오류 유형: 907. MySqlConnector 사용 시 System.IO.FileLoadException 오류
13642정성태6/11/20248196스크립트: 65. 파이썬 - asgi 버전(2, 3)에 따라 달라지는 uvicorn 호스팅
13641정성태6/11/20248659Linux: 71. Ubuntu 20.04를 22.04로 업데이트
1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...