WakeOnLan/WakeOnLan/Network.cs
2022-05-14 22:00:08 +09:00

69 lines
1.7 KiB
C#

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
namespace WakeOnLan
{
public class Network
{
public Network()
{
}
public void Send(string macAddr)
{
Send(IPAddress.Broadcast, 9, macAddr);
}
public void Send(byte[] macAddr)
{
Send(IPAddress.Broadcast, 9, macAddr);
}
public void Send(IPAddress ipAddr, int port, string macAddr)
{
string[] macTmp = macAddr.Split(':');
if (macTmp.Length != 6)
{
Console.WriteLine("Macアドレスが正しくありません。");
return;
}
byte[] mac = new byte[6];
for (int i = 0; i < macTmp.Length; i++)
{
mac[i] = Convert.ToByte(macTmp[i], 16);
}
Send(ipAddr, port, mac);
}
public void Send(IPAddress ipAddr, int port, byte[] macAddress)
{
using (MemoryStream stream = new MemoryStream())
{
using (BinaryWriter writer = new BinaryWriter(stream))
{
for (int i = 0; i < 6; i++)
{
writer.Write((byte)0xff);
}
for (int i = 0; i < 16; i++)
{
writer.Write(macAddress);
}
using (UdpClient client = new UdpClient())
{
client.EnableBroadcast = true;
client.Send(stream.ToArray(), (int) stream.Position, new IPEndPoint(ipAddr, port));
}
}
}
}
}
}