HomeController 控制器,添加网络唤醒的接口,代码如下:
using HomeCloud.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using System.Diagnostics;
using System.Net.Sockets;
namespace HomeCloud.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult WOL(string mac)
{
WakeUpCore(FormatMac(mac));
return Json(new { ret = true });
}
private static void WakeUpCore(byte[] mac)
{
//发送方法是通过UDP
using UdpClient client = new UdpClient();
//Broadcast内容为:255,255,255,255.广播形式,所以不需要IP
client.Connect(System.Net.IPAddress.Broadcast, 50000);
//下方为发送内容的编制,6遍“FF”+17遍mac的byte类型字节。
byte[] packet = new byte[17 * 6];
for (int i = 0; i < 6; i++)
packet[i] = 0xFF;
for (int i = 1; i <= 16; i++)
for (int j = 0; j < 6; j++)
packet[i * 6 + j] = mac[j];
//唤醒动作
int result = client.Send(packet, packet.Length);
}
private static byte[] FormatMac(string macInput)
{
byte[] mac = new byte[6];
string str = macInput;
//消除MAC地址中的“-”符号
string[] sArray = str.Split('-');
//mac地址从string转换成byte
for (var i = 0; i < 6; i++)
{
var byteValue = Convert.ToByte(sArray[i], 16);
mac[i] = byteValue;
}
return mac;
}
}
}