Skip to content

Instantly share code, notes, and snippets.

@jbe2277
Created October 15, 2017 17:59
Show Gist options
  • Save jbe2277/5f61564407396a235824026defa8c11b to your computer and use it in GitHub Desktop.
Save jbe2277/5f61564407396a235824026defa8c11b to your computer and use it in GitHub Desktop.
Wake On Lan command line application
using System;
using System.Diagnostics;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
namespace WakeOnLan
{
internal class Program
{
private static int Main(string[] args)
{
var exitCode = MainCore(args);
if (Debugger.IsAttached) Console.ReadLine();
return exitCode;
}
private static int MainCore(string[] args)
{
if (args.Length < 1 || args.Length > 2)
{
Console.Error.WriteLine("Error: Wrong number of parameters.\n");
PrintHelp();
return -1;
}
try
{
var mac = PhysicalAddress.Parse(args[0]);
var endPoint = args.Length == 2 ? IPAddress.Parse(args[1]) : IPAddress.Broadcast;
SendWakeOnLanPackage(mac, endPoint);
}
catch (Exception ex)
{
Console.Error.WriteLine("Error: " + ex);
return -2;
}
return 0;
}
private static void SendWakeOnLanPackage(PhysicalAddress mac, IPAddress endPoint)
{
var client = new UdpClient();
// WOL packet contains a 6-bytes trailer and 16 times a 6-bytes sequence containing the MAC address.
var packet = new byte[17 * 6];
// Trailer of 6 times 0xFF.
for (int i = 0; i < 6; i++)
{
packet[i] = 0xFF;
}
// Body of magic packet contains 16 times the MAC address.
var macBytes = mac.GetAddressBytes();
for (int i = 1; i <= 16; i++)
{
for (int j = 0; j < 6; j++)
{
packet[i * 6 + j] = macBytes[j];
}
}
client.Send(packet, packet.Length, new IPEndPoint(endPoint, 40000)); // Use hard-coded port
}
private static void PrintHelp()
{
Console.WriteLine($"Usage: {AppDomain.CurrentDomain.SetupInformation.ApplicationName} mac [broadcastAddress]");
Console.WriteLine(" mac The MAC address of the ethernet adapter which is responsible to wake up the device.");
Console.WriteLine(" [broadcastAddress] Optional: A subnet-directed broadcast IP address.");
Console.WriteLine("\nSamples:");
Console.WriteLine($" {AppDomain.CurrentDomain.SetupInformation.ApplicationName} 32-A8-F1-5F-F3-C2");
Console.WriteLine($" {AppDomain.CurrentDomain.SetupInformation.ApplicationName} 32-A8-F1-5F-F3-C2 192.168.255.255");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment