(C#) Wake on LAN

C#/Winform 2017. 7. 11. 14:35
728x90
728x170

원격으로 PC 를 켜기위해 알아보다

찾은 내용입니다.

일단 내부 망에서는 잘 동작하는데 외부망을 통해서는 안되네요 ㅜㅠ

공유기가 iptime 라서 안된다고는 하는데 혹 성공하게 되면 또 공유하겠습니다.

WakeFunction 호출 시 켜고자 하는 PC 의 mac 주소를 넣으면됩니다. (- 는 제거)

using System;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            //string hostname = "naver.com";
            //IPAddress[] addresslist = Dns.GetHostAddresses(hostname);

            //foreach (IPAddress theaddress in addresslist)
            //{
            //    Console.WriteLine(theaddress.ToString());
            //}

            // 40-8D-9C-A8-0B-D9
            WakeFunction("408D9CA80BD9");
        }

        private void WakeFunction(string macAddress)
        {
            WOLClass client = new WOLClass();
            client.Connect(
               IPAddress.Parse("255.255.255.255"),  // 포트를 적습니다. (255.255.255.255 는 브로드케스팅)
               1010); // 포트를 적습니다. (내부망에서는 의미없음)
            client.SetClientToBrodcastMode();
           
            int counter = 0;
            byte[] bytes = new byte[1024];

            // 처음 6자리는 0xFF 으로 채워져 있어야합니다.
            for (int y = 0; y < 6; y++)
            {
                bytes[counter++] = 0xFF;
            }

            // 맥 주소를 바이트화 합니다.
            for (int y = 0; y < 16; y++)
            {
                int i = 0;
                for (int z = 0; z < 6; z++)
                {
                    bytes[counter++] =
                        byte.Parse(macAddress.Substring(i, 2),
                        NumberStyles.HexNumber);
                    i += 2;
                }
            }

            // 매직패킷을 보냅니다.
            int reterned_value = client.Send(bytes, 1024);
        }
    }

    public class WOLClass : UdpClient
    {
        public WOLClass() : base() { }
       
        public void SetClientToBrodcastMode()
        {
            if (this.Active)
                this.Client.SetSocketOption(SocketOptionLevel.Socket,
                                          SocketOptionName.Broadcast, 0);
        }
    }
}

 

참고

http://dotnet-snippets.com/snippet/wake-on-lan/1698
https://www.codeproject.com/Articles/5315/Wake-On-Lan-sample-for-C

728x90
그리드형

'C# > Winform' 카테고리의 다른 글

개발 관련 eBook - 링크  (0) 2017.07.13
(ASP.NET) ComboBox - 링크  (0) 2017.07.11
(Visual Studio) Error - Git failed with a fatal error.  (0) 2017.07.05
(NuGet) NuGet 패키지 복원 하는 방법  (0) 2017.06.15
개발자가 읽어야할 책  (0) 2017.06.09
Posted by kjun
,