Skip to content

Instantly share code, notes, and snippets.

@AlexKorsakov
Created December 18, 2016 20:48
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save AlexKorsakov/53e1d9a224218b57e7fe280cab6c320e to your computer and use it in GitHub Desktop.
Save AlexKorsakov/53e1d9a224218b57e7fe280cab6c320e to your computer and use it in GitHub Desktop.
C# Wake On Lan Program
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Globalization;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
WakeFunction("AA:EE:CC:DD:FF"); //change me
}
//we derive our class from a standart one
public class WOLClass : UdpClient
{
public WOLClass() : base()
{ }
//this is needed to send broadcast packet
public void SetClientToBrodcastMode()
{
if (this.Active)
this.Client.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.Broadcast, 0);
}
}
//now use this class
//MAC_ADDRESS should look like '013FA049'
private void WakeFunction(string MAC_ADDRESS)
{
WOLClass client = new WOLClass();
client.Connect(new
IPAddress(0xffffffff), //255.255.255.255 i.e broadcast
0x2fff); // port=12287 let's use this one
client.SetClientToBrodcastMode();
//set sending bites
int counter = 0;
//buffer to be send
byte[] bytes = new byte[1024]; // more than enough :-)
//first 6 bytes should be 0xFF
for (int y = 0; y < 6; y++)
bytes[counter++] = 0xFF;
//now repeate MAC 16 times
for (int y = 0; y < 16; y++)
{
int i = 0;
for (int z = 0; z < 6; z++)
{
bytes[counter++] =
byte.Parse(MAC_ADDRESS.Substring(i, 2), NumberStyles.HexNumber);
i += 2;
}
}
//now send wake up packet
int reterned_value = client.Send(bytes, 1024);
}
}
}
@satosCZ
Copy link

satosCZ commented Sep 7, 2021

Thank you, this will help me. I'll try it later. Remote shutdown and restart for me is allready solved. I used server-client, where user send request to shutdown in type of some message eg. "Shutdown-123". Other pc will receive the message and by request it will start command in cmd (all in background > "shutdown -s -f" / "shutdown -r -f"). It's lightway solution which didn't need admin permision. Once again thank you for WOL.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment