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

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 타입을 추가하면 동일하게 구현할 수 있습니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/7/2023]

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)
13597정성태4/15/2024286닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/2024506닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/2024494닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/2024709닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/2024919닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241185C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241152닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241067Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241131닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241184닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신파일 다운로드1
13587정성태3/27/20241131오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241259Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241087Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241042개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241143Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241217Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
13581정성태3/18/20241362개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
13580정성태3/15/20241131닷넷: 2231. C# - ReceiveTimeout, SendTimeout이 적용되지 않는 Socket await 비동기 호출파일 다운로드1
13579정성태3/13/20241493오류 유형: 899. HTTP Error 500.32 - ANCM Failed to Load dll
13578정성태3/11/20241619닷넷: 2230. C# - 덮어쓰기 가능한 환형 큐 (Circular queue)파일 다운로드1
13577정성태3/9/20241850닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx)
13576정성태3/8/20241539닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
13575정성태3/7/20241661닷넷: 2227. 최신 C# 문법을 .NET Framework 프로젝트에 쓸 수 있을까요?
13574정성태3/6/20241552닷넷: 2226. C# - "Docker Desktop for Windows" Container 환경에서의 IPv6 DualMode 소켓
13573정성태3/5/20241560닷넷: 2225. Windbg - dumasync로 분석하는 async/await 호출
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...