Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

UWP 앱에서 한 컴퓨터(localhost, 127.0.0.1) 내에서의 소켓 연결

아래의 질문이 있길래,

uwp에서 TcpListener를 사용할 수 없나요?
; https://www.sysnet.pe.kr/3/0/5089

저도 테스트를 해봤습니다. ^^ UWP에서 제공하는 2가지 TCP 소켓 방식을 모두 사용해 대기해 봤는데요,

namespace App1
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            ServerTest1();
            ServerTest2();
        }

        Windows.Networking.Sockets.StreamSocketListener _streamSocketListener;

        private async void ServerTest1()
        {
            _streamSocketListener = new Windows.Networking.Sockets.StreamSocketListener();
            _streamSocketListener.ConnectionReceived += this.StreamSocketListener_ConnectionReceived;
            await _streamSocketListener.BindServiceNameAsync("2345");
        }

        private async void StreamSocketListener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            Debug.WriteLine("StreamSocketListener_ConnectionReceived");
            sender.Dispose();
        }

        private async void ServerTest2()
        {
            TcpListener server = new TcpListener(IPAddress.Any, 2346);
            server.Start();

            Debug.WriteLine("서버 시작");
            var client = await server.AcceptTcpClientAsync();
            Debug.WriteLine("서버 성공");
        }
    }
}

다음의 권한도 함께 줘 실행한 경우,

<Capability Name="privateNetworkClientServer" />

결론은, 질문자의 상황과 같았습니다.

.NET 서버 <-> .NET 클라이언트 = 성공
.NET 서버 <-> UWP 클라이언트 = 성공
UWP 서버 <-> UWP 클라이언트 = 실패
UWP 서버 <-> .NET 클라이언트 = 실패

즉, 같은 PC 내에서는 UWP 앱에서 TCP 서버를 만들어 제공할 수는 없었습니다. 단지, 다른 PC로부터 접속하는 경우라면 다음의 권한을 추가만 해주면,

<Capability Name="internetClientServer" />

TCP 서버로써 정상적인 역할을 합니다.




이 기능에 관한 이력은 알 수 없으나 검색해 보면, 초기에는 같은 PC 내에서도 UWP 앱 측에서 TCP 서버로 기능을 했던 것 같습니다. 단지 이후에 보안상의 이유로 막았다는 것 같은데요, 그런데 아래의 문서를 읽어보면,

Docs/Windows/UWP/Develop/Networking and web services/앱 개발/통신/네트워킹 및 웹 서비스/소켓
; https://learn.microsoft.com/ko-kr/windows/uwp/networking/sockets

네트워크 격리의 결과로 Windows는 로컬 루프백 주소(127.0.0.0)를 통해서나 로컬 IP 주소를 명시적으로 지정하여 동일한 시스템에서 실행 중인 UWP 앱 두 개 사이의 소켓 연결(소켓 또는 WinSock) 설정을 허용하지 않습니다. UWP 앱이 서로 통신할 수 있도록 하는 메커니즘에 대한 자세한 내용은 앱 간 통신을 참조하세요.


"UWP 앱 두 개 사이의 소켓 연결"이라고 하는 것에서 왠지 일반 데스크톱이라면 가능하지 않을까? 라는 여지를 갖게 합니다. 물론 테스트를 해보면 (관리자 권한일지라도) 데스크톱 응용 프로그램 역시 UWP 앱에서 열어 놓은 TCP 서버에는 접속할 수 없습니다.

그런데 저 문서뿐만 아니라 "CheckNetIsolation" 프로그램에 대한 설정도 왠지 개발자를 혼란에 빠뜨리게 합니다.

Enabling Loopback for MS Edge with Windows 10
; https://www.ibm.com/support/knowledgecenter/en/SSPH29_9.0.3/com.ibm.help.common.infocenter.aps/r_LoopbackForEdge.html

Package.appxmanifest의 "Packaging" 탭에 있는 "Package family name" 값(이 글에서는 "7e74130d-0dde-409b-adc1-44dc4c5137fc_2846pq4653gqa")으로 다음과 같이 CheckNetIsolation을 실행하고,

CheckNetIsolation LoopbackExempt -a -n="7e74130d-0dde-409b-adc1-44dc4c5137fc_2846pq4653gqa"

권한까지 주면,

<Capability Name="privateNetworkClientServer" />

해당 UWP 앱은 localhost로의 접속이 가능합니다. 따라서, 이 방법을 사용하면 같은 PC 내의 UWP 앱에서 제공하는 TCP Server에도 접속할 것 같은 느낌이 드는데요, 그래도 접속할 수 없는 것은 마찬가지입니다. 즉, 이 옵션을 주면 같은 PC 내의 비-UWP 응용 프로그램이 열어 놓은 TCP 서버로 접속 가능한 것입니다.




참고로, CheckNetIsolation으로 이미 설정된 목록을 -s 옵션으로 볼 수 있습니다.

C:\Windows\System32>CheckNetIsolation LoopbackExempt -s

List Loopback Exempted AppContainers

[1] -----------------------------------------------------------------
    Name: e3874fef-6298-4f36-92d0-c3dee93a0af9_8wekyb3d8bbwe
    SID:  S-1-15-7-1540256326-2870764848-967293167-2470951913-2147672149-3757691537-2504242156

[2] -----------------------------------------------------------------
    Name: da29541c-1efc-4ba7-9e7e-af73c818513e_2846pq4653gqa
    SID:  S-1-15-7-3297226826-4264591352-2292705388-1537415806-1543069546-1598715701-2109803276

[3] -----------------------------------------------------------------
    Name: 36f6fa81-5827-46e0-afc6-2974a316a715_2846pq4653gqa
    SID:  S-1-15-7-704375632-1530588768-762434507-3187168021-1340731922-1574151383-1637619547

[4] -----------------------------------------------------------------
    Name: microsoft.microsoftedge_8wekyb3d8bbwe
    SID:  S-1-15-7-3624051432-2155758914-1422191567-1740899205-1073925389-3762572162-737981394

[5] -----------------------------------------------------------------
    Name: AppContainer NOT FOUND
    SID:  S-1-15-7-3624051432-2155758914-1422191567-1740899205-1073925389-3762572162-737981394-4043415302-551583165-304772019-4009825106

OK.

위의 출력 결과에서 "Name" 필드는 "Package family name"이므로 삭제 시에는 이를 참조해 -d 옵션을 주면 됩니다. 가령, 3번 항목을 삭제하고 싶다면 이렇게 실행합니다.

CheckNetIsolation.exe LoopbackExempt ?d ?n="36f6fa81-5827-46e0-afc6-2974a316a715_2846pq4653gqa"

그런데, "AppContainer NOT FOUND"라고 나오면서 "Package family name"을 확인할 수 없는 항목도 있는데 이런 경우에는 SID를 기준으로 삭제할 수 있도록 -p 옵션이 제공됩니다. 따라서 5번 항목을 삭제하고 싶다면 다음과 같이 실행하면 됩니다.

CheckNetIsolation LoopbackExempt -d -p="S-1-15-7-3624051432-2155758914-...[생략]...-551583165-304772019-4009825106"

마지막으로, 4번 항목을 보면 이름이 "microsoft.microsoftedge_8wekyb3d8bbwe"라고 바로 그 "Microsoft Edge" 웹 브라우저를 의미합니다. 즉, UWP 앱 모드의 Edge 브라우저도 저 항목을 등록해 두었기 때문에 (개발 시에 IISEXPRESS가 열어놓은 ASP.NET 사이트를) localhost로 접근할 수 있었던 것입니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 11/9/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)
12207정성태4/2/20208951스크립트: 19. Windows PowerShell의 NonInteractive 모드
12206정성태4/2/202011245오류 유형: 613. 파일 잠금이 바로 안 풀린다면? - The process cannot access the file '...' because it is being used by another process.
12205정성태4/2/20208638스크립트: 18. Powershell에서는 cmd.exe의 명령어를 지원하진 않습니다.
12204정성태4/1/20208441스크립트: 17. Powershell 명령어에 ';' (semi-colon) 문자가 포함된 경우
12203정성태3/18/202010477오류 유형: 612. warning: 'C:\ProgramData/Git/config' has a dubious owner: '...'.
12202정성태3/18/202013094개발 환경 구성: 486. .NET Framework 프로젝트를 위한 GitLab CI/CD Runner 구성
12201정성태3/18/202010888오류 유형: 611. git-credential-manager.exe: Using credentials for username "Personal Access Token". [1]
12200정성태3/18/202011329VS.NET IDE: 145. NuGet + Github 라이브러리 디버깅 관련 옵션 3가지 - "Enable Just My Code" / "Enable Source Link support" / "Suppress JIT optimization on module load (Managed only)"
12199정성태3/17/20209182오류 유형: 610. C# - CodeDomProvider 사용 시 Unhandled Exception: System.IO.DirectoryNotFoundException: Could not find a part of the path '...\f2_6uod0.tmp'.
12198정성태3/17/202011922오류 유형: 609. SQL 서버 접속 시 "Cannot open user default database. Login failed."
12197정성태3/17/202011068VS.NET IDE: 144. .NET Core 콘솔 응용 프로그램을 배포(publish) 시 docker image 자동 생성 - 두 번째 이야기 [1]
12196정성태3/17/20208996오류 유형: 608. The ServicedComponent being invoked is not correctly configured (Use regsvcs to re-register).
12195정성태3/16/202010709.NET Framework: 902. C# - 프로세스의 모든 핸들을 열람 - 세 번째 이야기
12194정성태3/16/202013029오류 유형: 607. PostgreSQL - Npgsql.NpgsqlException: sorry, too many clients already
12193정성태3/16/20209715개발 환경 구성: 485. docker - SAP Adaptive Server Enterprise 컨테이너 실행 [1]
12192정성태3/14/202012154개발 환경 구성: 484. docker - Sybase Anywhere 16 컨테이너 실행
12191정성태3/14/202012529개발 환경 구성: 483. docker - OracleXE 컨테이너 실행 [1]
12190정성태3/14/20208647오류 유형: 606. Docker Desktop 업그레이드 시 "The process cannot access the file 'C:\Program Files\Docker\Docker\resources\dockerd.exe' because it is being used by another process."
12189정성태3/13/202013489개발 환경 구성: 482. Facebook OAuth 처리 시 상태 정보 전달 방법과 "유효한 OAuth 리디렉션 URI" 설정 규칙
12188정성태3/13/202015793Windows: 169. 부팅 시점에 실행되는 chkdsk 결과를 확인하는 방법
12187정성태3/12/20208465오류 유형: 605. NtpClient was unable to set a manual peer to use as a time source because of duplicate error on '...'.
12186정성태3/12/20209539오류 유형: 604. The SysVol Permissions for one or more GPOs on this domain controller and not in sync with the permissions for the GPOs on the Baseline domain controller.
12185정성태3/11/202010234오류 유형: 603. The browser service was unable to retrieve a list of servers from the browser master...
12184정성태3/11/202011641오류 유형: 602. Automatic certificate enrollment for local system failed (0x800706ba) The RPC server is unavailable. [3]
12183정성태3/11/202010009오류 유형: 601. Warning: DsGetDcName returned information for \\[...], when we were trying to reach [...].
12182정성태3/11/202011216.NET Framework: 901. C# Windows Forms - Vista/7 이후의 Progress Bar 업데이트가 느린 문제파일 다운로드1
... 46  47  48  49  50  51  52  53  54  55  56  [57]  58  59  60  ...