Skip to content

Instantly share code, notes, and snippets.

@QuiltMeow
Created October 31, 2024 17:07
Show Gist options
  • Select an option

  • Save QuiltMeow/081763ec12ed9176f136cb385368da6a to your computer and use it in GitHub Desktop.

Select an option

Save QuiltMeow/081763ec12ed9176f136cb385368da6a to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
namespace WakeOnLAN
{
public static class Program
{
public static void sendBroadcastPacket(byte[] data, int port)
{
IPEndPoint ip = new IPEndPoint(IPAddress.Broadcast, port);
NetworkInterface[] adapterList = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in adapterList)
{
if (!adapter.Supports(NetworkInterfaceComponent.IPv4))
{
continue;
}
IPInterfaceProperties property = adapter.GetIPProperties();
foreach (UnicastIPAddressInformation unicast in property.UnicastAddresses)
{
IPAddress local = unicast.Address;
if (local.AddressFamily == AddressFamily.InterNetwork)
{
try
{
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
socket.Bind(new IPEndPoint(local, 0));
socket.SendTo(data, ip);
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"發送封包時發生例外狀況 : {ex.Message}");
}
}
}
}
}
public static void sendWakeOnLanPacket(PhysicalAddress target)
{
IEnumerable<byte> header = Enumerable.Repeat(byte.MaxValue, 6);
IEnumerable<byte> data = Enumerable.Repeat(target.GetAddressBytes(), 16).SelectMany(mac => mac);
byte[] magicPacket = header.Concat(data).ToArray();
const int WAKE_ON_LAN_PORT = 9;
sendBroadcastPacket(magicPacket, WAKE_ON_LAN_PORT);
}
public static void Main(string[] args)
{
if (args.Length <= 0)
{
Console.WriteLine("參數說明 : [MAC 位址 1] [MAC 位址 2] [MAC 位址 3] ...");
}
else
{
foreach (string macString in args)
{
try
{
PhysicalAddress mac = PhysicalAddress.Parse(macString);
sendWakeOnLanPacket(mac);
Console.WriteLine($"Wake On LAN 封包已發送至 {BitConverter.ToString(mac.GetAddressBytes())}");
}
catch (Exception ex)
{
Console.Error.WriteLine($"發生例外狀況 : {ex.Message}");
}
}
}
Console.Write("請按任意鍵繼續 ...");
Console.ReadKey(true);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment