Microsoft MVP성태의 닷넷 이야기
Linux: 19. C# - .NET Core Unix Domain Socket 사용 예제 [링크 복사], [링크+제목 복사],
조회: 13034
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




... 46  47  48  49  [50]  51  52  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12394정성태11/3/20208123오류 유형: 676. cacls - The Recycle Bin on ... is corrupted. Do you want to empty the Recycle Bin for this drive?
12393정성태11/3/20208619오류 유형: 675. Visual Studio - 닷넷 응용 프로그램 디버깅 시 Disassembly 창에서 BP 설정할 때 "Error while processing breakpoint." 오류
12392정성태11/2/202012702.NET Framework: 959. C# 9.0 - (9) 레코드(Records) [4]파일 다운로드1
12390정성태11/1/202010989디버깅 기술: 173. windbg - System.Configuration.ConfigurationErrorsException 예외 분석 방법
12389정성태11/1/202010725.NET Framework: 958. C# 9.0 - (8) 정적 익명 함수 (static anonymous functions)파일 다운로드1
12388정성태10/29/202010166오류 유형: 674. 어느 순간부터 닷넷 응용 프로그램 실행 시 System.Configuration.ConfigurationErrorsException 예외가 발생한다면?
12387정성태10/28/202010949.NET Framework: 957. C# - static 필드의 정보가 GC Heap에 저장될까요? [3]파일 다운로드1
12386정성태10/28/202011168Linux: 34. 사용자 정보를 함께 출력하는 리눅스의 ps 명령어 사용 방법
12385정성태10/28/20209002오류 유형: 673. openssl - req: No value provided for Subject Attribute CN, skipped
12384정성태10/27/202010214오류 유형: 672. AllowPartiallyTrustedCallers 특성이 적용된 어셈블리의 struct 멤버 메서드를 재정의하면 System.Security.VerificationException 예외 발생
12383정성태10/27/202011103.NET Framework: 956. C# 9.0 - (7) 패턴 일치 개선 사항(Pattern matching enhancements) [3]파일 다운로드1
12382정성태10/26/20208764오류 유형: 671. dotnet build - The local source '...' doesn't exist
12381정성태10/26/202010471VC++: 137. C++ stl map의 사용자 정의 타입을 key로 사용하는 방법 [1]파일 다운로드1
12380정성태10/26/20207893오류 유형: 670. Visual Studio - Squash_FailureCommitsReset
12379정성태10/21/202010900.NET Framework: 955. .NET 메서드의 Signature 바이트 코드 분석 [1]파일 다운로드2
12378정성태10/15/202010352.NET Framework: 954. C# - x86/x64 환경에 따라 달라지는 P/Invoke 함수의 export 이름파일 다운로드1
12377정성태10/15/202011644디버깅 기술: 172. windbg - 파일 열기 시점에 bp를 걸어 파일명 알아내는 방법(Managed/Unmanaged)
12376정성태10/15/20208351오류 유형: 669. windbg - sos의 name2ee 명령어 실행 시 "Failed to request module list." 오류
12375정성태10/15/20209705Windows: 177. 윈도우 탐색기에서 띄우는 cmd.exe 창의 디렉터리 구분 문자가 'Yen(¥)' 기호로 나오는 경우 [1]
12374정성태10/14/202014342.NET Framework: 953. C# 9.0 - (6) 함수 포인터(Function pointers) [1]파일 다운로드2
12373정성태10/14/20209564.NET Framework: 952. OpCodes.Box와 관련해 IL 형식으로 직접 코딩 시 유의할 점
12372정성태10/13/202011473.NET Framework: 951. C# 9.0 - (5) 로컬 함수에 특성 지정 가능(Attributes on local functions)파일 다운로드1
12371정성태10/13/202010233개발 환경 구성: 519. Visual Studio의 Ctrl+Shift+U (Edit.MakeUppercase) 단축키가 동작하지 않는 경우
12370정성태10/13/202011106Linux: 33. Linux - nmcli를 이용한 고정 IP 설정
12369정성태10/12/202013923Windows: 176. Raymond Chen이 한글날에 밝히는 윈도우의 한글 자모 분리 현상 [3]
12368정성태10/12/20209984오류 유형: 668. VSIX 확장 빌드 - The "GetDeploymentPathFromVsixManifest" task failed unexpectedly.
... 46  47  48  49  [50]  51  52  53  54  55  56  57  58  59  60  ...