Skip to content

Instantly share code, notes, and snippets.

@AlexKorsakov
Created December 18, 2016 20:49
Show Gist options
  • Save AlexKorsakov/76d515918c191094f29a463aa69d5649 to your computer and use it in GitHub Desktop.
Save AlexKorsakov/76d515918c191094f29a463aa69d5649 to your computer and use it in GitHub Desktop.
Second C# Wake On Lan Program
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
namespace WakeOnLan2
{
public class WakeOnLan
{
public static void Send(string TargetMac, string SourceIp)
{
PhysicalAddress target = PhysicalAddress.Parse(TargetMac.ToUpper());
IPAddress senderAddress = IPAddress.Parse(SourceIp);
byte[] payload = new byte[102]; // 6 bytes of ff, plus 16 repetitions of the 6-byte target
byte[] targetMacBytes = target.GetAddressBytes();
// Set first 6 bytes to ff
for (int i = 0; i < 6; i++)
payload[i] = 0xff;
// Repeat the target mac 16 times
for (int i = 6; i < 102; i += 6)
targetMacBytes.CopyTo(payload, i);
// Create a socket to send the packet, and send it
using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
sock.Bind(new IPEndPoint(senderAddress, 0));
sock.SendTo(payload, new IPEndPoint(IPAddress.Broadcast, 7));
}
}
}
}
@AlexKorsakov
Copy link
Author

Example: WakeOnLan.Send("f0-4d-a2-c0-fd-45", "192.168.1.55");

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