魔法包
魔法包是用16进制表示的数据包,它是由固定的前缀数据(FFFFFFFFFFFF)以及固定重复次数(16次)的目标主机MAC地址组成。
假设目标主机的MAC地址是:"50:eb:f6:27:ae:a8"
那么魔法包就是[FFFFFFFFFFFF50EBF627AEA850EBF627AEA850EBF627AEA850EBF627AEA850EBF627AEA850EBF627AEA850EBF627AEA850EBF627AEA850EBF627AEA850EBF627AEA850EBF627AEA850EBF627AEA850EBF627AEA850EBF627AEA850EBF627AEA850EBF627AEA8]
实现代码
import 'dart:io';void sendWOLPacket(String host, String mac) async {// 将MAC地址转换为字节序列List<int> macBytes = mac.split(':').map((s) => int.parse(s, radix: 16)).toList();// 构造魔术包List<int> packet = List.filled(6, 0xFF) + List<int>.generate(16 * macBytes.length, (index) => macBytes[index % macBytes.length]);RawDatagramSocket? _socket;try {_socket = await RawDatagramSocket.bind(InternetAddress.anyIPv4, 0);// 创建UDP Socket并发送魔术包_socket.broadcastEnabled = true;for (var i = 0; i < 5; i++) {_socket.send(packet, InternetAddress(host), 0);await Future.delayed(const Duration(milliseconds: 150));_socket.send(packet, InternetAddress(host), 7);await Future.delayed(const Duration(milliseconds: 150));_socket.send(packet, InternetAddress(host), 9);await Future.delayed(const Duration(milliseconds: 150));}print("success", "发送完成");} catch (e) {print("error", "出错了;$e");}_socket?.close();
}