Microsoft MVP성태의 닷넷 이야기
Linux: 19. C# - .NET Core Unix Domain Socket 사용 예제 [링크 복사], [링크+제목 복사],
조회: 20537
글쓴 사람
정성태 (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)
13641정성태6/11/20248659Linux: 71. Ubuntu 20.04를 22.04로 업데이트
13640정성태6/10/20248831Phone: 21. C# MAUI - Android 환경에서의 파일 다운로드(DownloadManager)
13639정성태6/8/20248436오류 유형: 906. C# MAUI - Android Emulator에서 "Waiting For Debugger"로 무한 대기
13638정성태6/8/20248520오류 유형: 905. C# MAUI - 추가한 layout XML 파일이 Resource.Layout 멤버로 나오지 않는 문제
13637정성태6/6/20248446Phone: 20. C# MAUI - 유튜브 동영상을 MediaElement로 재생하는 방법
13636정성태5/30/20248087닷넷: 2264. C# - 형식 인자로 인터페이스를 갖는 제네릭 타입으로의 형변환파일 다운로드1
13635정성태5/29/20248936Phone: 19. C# MAUI - 안드로이드 "Share" 대상으로 등록하는 방법
13634정성태5/24/20249416Phone: 18. C# MAUI - 안드로이드 플랫폼에서의 Activity 제어 [1]
13633정성태5/22/20248943스크립트: 64. 파이썬 - ASGI를 만족하는 최소한의 구현 코드
13632정성태5/20/20248559Phone: 17. C# MAUI - Android 내에 Web 서비스 호스팅
13631정성태5/19/20249320Phone: 16. C# MAUI - /Download 등의 공용 디렉터리에 접근하는 방법 [1]
13630정성태5/19/20248863닷넷: 2263. C# - Thread가 Task보다 더 빠르다는 어떤 예제(?)
13629정성태5/18/20249160개발 환경 구성: 710. Android - adb.exe를 이용한 파일 전송
13628정성태5/17/20248540개발 환경 구성: 709. Windows - WHPX(Windows Hypervisor Platform)를 이용한 Android Emulator 가속
13627정성태5/17/20248603오류 유형: 904. 파이썬 - UnicodeEncodeError: 'ascii' codec can't encode character '...' in position ...: ordinal not in range(128)
13626정성태5/15/20248867Phone: 15. C# MAUI - MediaElement Source 경로 지정 방법파일 다운로드1
13625정성태5/14/20248924닷넷: 2262. C# - Exception Filter 조건(when)을 갖는 catch 절의 IL 구조
13624정성태5/12/20248720Phone: 14. C# - MAUI에서 MediaElement 사용파일 다운로드1
13623정성태5/11/20248418닷넷: 2261. C# - 구글 OAuth의 JWT (JSON Web Tokens) 해석파일 다운로드1
13622정성태5/10/20249205닷넷: 2260. C# - Google 로그인 연동 (ASP.NET 예제)파일 다운로드1
13621정성태5/10/20248636오류 유형: 903. IISExpress - Failed to register URL "..." for site "..." application "/". Error description: Cannot create a file when that file already exists. (0x800700b7)
13620정성태5/9/20248542VS.NET IDE: 190. Visual Studio가 node.exe를 경유해 Edge.exe를 띄우는 경우
13619정성태5/7/20248860닷넷: 2259. C# - decimal 저장소의 비트 구조파일 다운로드1
13618정성태5/6/20248653닷넷: 2258. C# - double (배정도 실수) 저장소의 비트 구조파일 다운로드1
13617정성태5/5/20249471닷넷: 2257. C# - float (단정도 실수) 저장소의 비트 구조파일 다운로드1
13616정성태5/3/20248617닷넷: 2256. ASP.NET Core 웹 사이트의 HTTP/HTTPS + Dual mode Socket (IPv4/IPv6) 지원 방법파일 다운로드1
1  2  3  4  5  6  7  8  9  10  11  [12]  13  14  15  ...