Microsoft MVP성태의 닷넷 이야기
.NET Framework: 942. C# - WOL(Wake On Lan) 구현 [링크 복사], [링크+제목 복사]
조회: 12788
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

C# - WOL(Wake On Lan) 구현

예전에 구현했던,

라즈베리 파이를 이용해 원격 컴퓨터의 전원 스위치 제어
; https://www.sysnet.pe.kr/2/0/11726

Synology NAS(DS216+II)에 FTDI 장치 연결 후 C#(.NET Core)으로 DTR 제어
; https://www.sysnet.pe.kr/2/0/11734

전원 스위치를 이용해 원격으로 잘 제어하던 PC를 교체했더니,

2020년 작업 PC ^^
; https://www.sysnet.pe.kr/0/0/522

다시 저 피복 벗기고 하는 식의 작업을 새 PC에 하는 것이 귀찮아졌습니다. 그래도 꽤 괜찮게 써먹었던 기능이라서 없으면 무척 아쉬울 것 같아 차선책으로 WoL(Wake on Lan) 기능으로 넘어갔는데요, 검색해 보면 아래의 글이 꽤 적절하게 잘 설명하고 있기 때문에,

Wake On Lan(WOL) : 원격으로 컴퓨터 켜기 설정 및 사용
; https://neoray.org/281

자세한 것은 넘어가고, 곧바로 소스 코드 구현을 보겠습니다. 검색해 보면 아주 많은 소스 코드를 볼 수 있지만, 사실 프로토콜 자체가 매우 쉬우므로 아래와 같이 간단하게 구현할 수 있습니다.

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text.RegularExpressions;

namespace wol
{
    class Program
    {
        const int WOL_PACKET_LEN = 102;

        // Wake-on-Lan (WoL) in C#
        // https://www.fluxbytes.com/csharp/wake-lan-wol-c/
        static void Main(string[] args)
        {
            byte[] wolBuffer = GetWolPacket(args[0]);

            UdpClient udp = new UdpClient();
            udp.EnableBroadcast = true;

            IPAddress ipAddress = IPAddress.Parse("255.255.255.255");
            udp.Send(wolBuffer, wolBuffer.Length, ipAddress.ToString(), 7);
            udp.Send(wolBuffer, wolBuffer.Length, ipAddress.ToString(), 9);
        }

        private static byte[] GetWolPacket(string macAddress)
        {
            byte[] datagram = new byte[WOL_PACKET_LEN];

            byte[] macBuffer = StringToBytes(macAddress);

            MemoryStream ms = new MemoryStream(datagram);
            BinaryWriter bw = new BinaryWriter(ms);

            // 6바이트의 0xff를 선두에 채우고,
            for (int i = 0; i < 6; i++)
            {
                bw.Write((byte)0xff);
            }

            // 이후 WoL로 깨울 PC가 소유한 Network Adapter의 MAC 주소를 16번 반복
            for (int i = 0; i < 16; i++)
            {
                bw.Write(macBuffer, 0, macBuffer.Length);
            }

            return datagram;
        }

        private static byte[] StringToBytes(string macAddress)
        {
            macAddress = Regex.Replace(macAddress, "[-|:]", ""); // Remove any semicolons or minus characters present in our MAC address
            byte[] buffer = new byte[macAddress.Length / 2];

            for (int i = 0; i < macAddress.Length; i += 2)
            {
                string digit = macAddress.Substring(i, 2);
                buffer[i / 2] = byte.Parse(digit, NumberStyles.HexNumber);
            }

            return buffer;
        }
    }
}

여기서 재미있는 것은 Port인데요, 여러 소스 코드들을 보면 0번, 3번, 7번, 9번 등을 사용해 다소 혼란스러울 수 있는데 아래의 문서를 보면,

Wake-on-LAN
; https://en.wikipedia.org/wiki/Wake-on-LAN#Magic_packet

although it is typically sent as a UDP datagram to port 0, 7 or 9, or directly over Ethernet as EtherType 0x0842.

The internet with local broadcasting - some routers permit a packet received from the internet to be broadcast to the entire LAN [26]; the default TCP or UDP ports preconfigured to relay WOL requests are usually ports 7 (Echo Protocol) and/or 9 (Discard Protocol). This proxy setting must be enabled in the router, and port forwarding rules may need to be configured in its embedded firewall in order to accept magic packets coming from the internet side to these restricted port numbers, and to allow rebroadcasting them on the local network (normally to the same ports and the same TCP or UDP protocol). Such routers may also be configurable to use different port numbers for this proxying service.


Router의 영향을 고려해 7번 또는 9번을 사용하는 것이 좋아 보입니다. (이 글의 소스 코드에서는 2개 모두 사용했습니다.) 또한, 255.255.255.255 자체의 Broadcasting에 대한 제약을 따져 봤을 때,

UDP 브로드캐스트 주소 255.255.255.255와 192.168.0.255의 차이점과 이를 고려한 C# UDP 서버/클라이언트 예제
; https://www.sysnet.pe.kr/2/0/11368

모든 어댑터를 통해 보낼 수 있도록 Send 부분을 다음과 같이 변경해 주면 더 좋을 것입니다.

foreach (IPAddress ipAddress in GetDirectedBroadcastAddresses())
{
    udp.Send(wolBuffer, wolBuffer.Length, ipAddress.ToString(), port);
}

private static IPAddress[] GetDirectedBroadcastAddresses()
{
    List<IPAddress> list = new List<IPAddress>();

    foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces())
    {
        if (item.NetworkInterfaceType == NetworkInterfaceType.Loopback)
        {
            continue;
        }

        if (item.OperationalStatus != OperationalStatus.Up)
        {
            continue;
        }

        UnicastIPAddressInformationCollection unicasts = item.GetIPProperties().UnicastAddresses;

        foreach (UnicastIPAddressInformation unicast in unicasts)
        {
            IPAddress ipAddress = unicast.Address;

            if (ipAddress.AddressFamily != AddressFamily.InterNetwork)
            {
                continue;
            }

            byte[] addressBytes = ipAddress.GetAddressBytes();
            byte[] subnetBytes = unicast.IPv4Mask.GetAddressBytes();

            if (addressBytes.Length != subnetBytes.Length)
            {
                continue;
            }

            byte[] broadcastAddress = new byte[addressBytes.Length];
            for (int i = 0; i < broadcastAddress.Length; i++)
            {
                broadcastAddress[i] = (byte)(addressBytes[i] | (subnetBytes[i] ^ 255));
            }

            list.Add(new IPAddress(broadcastAddress));
        }
    }

    return list.ToArray();
}

Github에도 소스 코드 및 빌드된 바이너리를 올려두었습니다.

stjeong / Utilities / wol
; https://github.com/stjeong/Utilities/tree/master/wol

Utilities.zip - wol.exe
; https://github.com/stjeong/Utilities/releases/

참고로, 컴퓨터를 끄는 것은 "작업 스케줄러"에 "shutdown /h" 명령어를 원하는 시간에 실행하도록 등록하면 됩니다.




직접 실습을 해보니까, 제가 테스트한 4대의 컴퓨터 중에 구형 컴퓨터 2대(각각 11년, 8년)는 BIOS 설정과 윈도우의 Adapter 속성창에서 WoL 관련 설정을 했지만 동작하지 않았습니다. 반면 4년 된 컴퓨터와 새로 구매한 컴퓨터는 정상 동작했습니다. (그러고 보니, 저 4대의 컴퓨터가 모두 ASUS 보드군요. ^^)




검색하다가 낚인 것이 있어 ^^ 공유해 봅니다. 아래의 글에 대한 제목만 보면 Hyper-V의 가상 머신(VM)을 WoL 방식으로 깨우는 호스트 측의 기능이 있을 것 같은데요,

Wake on LAN for Hyper-V Guests
; https://deploymentpros.wordpress.com/2016/11/28/wake-on-lan-for-hyper-v-guests/

PowerShell Script (psHyper-V_WoL.ps1)
; https://gallery.technet.microsoft.com/scriptcenter/Wake-on-LAN-for-Hyper-V-21578819

실상은 Hyper-V 호스트가 VM에 대한 WoL을 지원하는 것은 아닙니다. 단지, 위의 스크립트가 UDP 소켓을 만들어 Receive로 대기하고 있다가 VM이 소유한 네트워크 어댑터의 WoL 신호가 들어오면 Start-VM 명령어를 이용하는 역할을 하는 것입니다.




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







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

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)
13378정성태6/22/20233172오류 유형: 868. docker - build 시 "CANCELED ..." 뜨는 문제
13377정성태6/22/20236991오류 유형: 867. 파이썬 mysqlclient 2.2.x 설치 시 "Specify MYSQLCLIENT_CFLAGS and MYSQLCLIENT_LDFLAGS env vars manually" 오류
13376정성태6/21/20233370.NET Framework: 2129. C# - Polly를 이용한 클라이언트 측의 요청 재시도파일 다운로드1
13375정성태6/20/20233051스크립트: 50. Transformers (신경망 언어모델 라이브러리) 강좌 - 2장 코드 실행 결과
13374정성태6/20/20233170오류 유형: 866. 파이썬 - <class 'AttributeError'> module 'flask.json' has no attribute 'JSONEncoder'
13373정성태6/19/20234456오류 유형: 865. 파이썬 - pymssql 설치 관련 오류 정리
13372정성태6/15/20233175개발 환경 구성: 682. SQL Server TLS 통신을 위해 사용되는 키 길이 확인 방법
13371정성태6/15/20233201개발 환경 구성: 681. openssl - 인증서 버전(V1 / V3)
13370정성태6/14/20233354개발 환경 구성: 680. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 - TLS 1.2 지원
13369정성태6/13/20233172개발 환경 구성: 679. PyCharm(을 비롯해 JetBrains에 속한 여타) IDE에서 내부 Window들의 탭이 없어진 경우
13368정성태6/13/20233319개발 환경 구성: 678. openssl로 생성한 인증서를 SQL Server의 암호화 인증서로 설정하는 방법
13367정성태6/10/20233421오류 유형: 864. openssl로 만든 pfx 인증서를 Windows Server 2016 이하에서 등록 시 "The password you entered is incorrect" 오류 발생
13366정성태6/10/20233195.NET Framework: 2128. C# - 윈도우 시스템에서 지원하는 암호화 목록(Cipher Suites) 나열파일 다운로드1
13365정성태6/8/20232941오류 유형: 863. MODIFY FILE encountered operating system error 112(failed to retrieve text for this error. Reason: 15105)
13364정성태6/8/20233748.NET Framework: 2127. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 [1]
13363정성태6/7/20233316스크립트: 49. 파이썬 - "Transformers (신경망 언어모델 라이브러리) 강좌" - 1장 2절 코드 실행 결과
13362정성태6/1/20233236.NET Framework: 2126. C# - 서버 측의 요청 제어 (Microsoft.AspNetCore.RateLimiting)파일 다운로드1
13361정성태5/31/20233696오류 유형: 862. Facebook - ASP.NET/WebClient 사용 시 graph.facebook.com/me 호출에 대해 403 Forbidden 오류
13360정성태5/31/20233065오류 유형: 861. WSL/docker - failed to start shim: start failed: io.containerd.runc.v2: create new shim socket
13359정성태5/19/20233397오류 유형: 860. Docker Desktop - k8s 초기화 무한 반복한다면?
13358정성태5/17/20233708.NET Framework: 2125. C# - Semantic Kernel의 Semantic Memory 사용 예제 [1]파일 다운로드1
13357정성태5/16/20233502.NET Framework: 2124. C# - Semantic Kernel의 Planner 사용 예제파일 다운로드1
13356정성태5/15/20233827DDK: 10. Device Driver 테스트 설치 관련 오류 (Code 37, Code 31) 및 인증서 관련 정리
13355정성태5/12/20233755.NET Framework: 2123. C# - Semantic Kernel의 ChatGPT 대화 구현 [1]파일 다운로드1
13354정성태5/12/20234013.NET Framework: 2122. C# - "Use Unicode UTF-8 for worldwide language support" 설정을 한 경우, 한글 입력이 '\0' 문자로 처리
13352정성태5/12/20233647.NET Framework: 2121. C# - Semantic Kernel의 대화 문맥 유지파일 다운로드1
1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...