using BytecodeApi.Extensions;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
namespace BytecodeApi.IO;
///
/// Provides a set of methods for network operations.
///
public static class Network
{
///
/// Sends a Wake-on-LAN magic packet containing the specified to UDP broadcast on port 9.
/// Packet bytes: FF FF FF FF FF FF | 16 repetitions of
/// Total number of bytes: 102.
///
/// The which is contained within the UDP broadcast packet.
public static void WakeOnLan(PhysicalAddress physicalAddress)
{
WakeOnLan(physicalAddress, null);
}
///
/// Sends a Wake-on-LAN magic packet containing the specified to UDP broadcast on port 9 including a password.
/// Packet bytes: FF FF FF FF FF FF | 16 repetitions of | contents of
/// Total number of bytes: 102.
///
/// The which is contained within the UDP broadcast packet.
/// The binary representation of the password. must either contain 4 or 6 bytes, or be .
public static void WakeOnLan(PhysicalAddress physicalAddress, byte[]? password)
{
Check.ArgumentNull(physicalAddress);
Check.Argument(password?.Length is null or 4 or 6, nameof(password), "The password must be either 4 or 6 bytes long, or null.");
byte[] packet = Enumerable
.Repeat(0xff, 6)
.Concat(Enumerable.Repeat(physicalAddress.GetAddressBytes(), 16).SelectMany())
.Concat(password ?? [])
.ToArray();
using UdpClient client = new();
client.Connect(IPAddress.Broadcast, 9);
client.Send(packet, packet.Length);
}
}