feat: add MAC based POST and GET endpoints
This commit is contained in:
41
wol.js
Normal file
41
wol.js
Normal file
@@ -0,0 +1,41 @@
|
||||
import dgram from "node:dgram"
|
||||
|
||||
export function createWolPacket(mac) {
|
||||
const parts = mac.split(/[:-]/);
|
||||
if (parts.length !== 6) throw new Error("Invalid MAC address")
|
||||
const hex = parts.map(p => {
|
||||
const n = parseInt(p, 16);
|
||||
if (isNaN(n)) throw new Error("Invalid MAC address");
|
||||
return n;
|
||||
});
|
||||
|
||||
const packet = Buffer.alloc(102);
|
||||
// Fill the first 6 bytes with 0xFF
|
||||
packet.fill(0xFF, 0, 6);
|
||||
|
||||
// Repeat the MAC address 16 times
|
||||
for(let i = 0; i < 16; i++) {
|
||||
hex.forEach((byte, index) => {
|
||||
packet[6 + (i * 6) + index] = byte;
|
||||
});
|
||||
}
|
||||
|
||||
return packet;
|
||||
}
|
||||
|
||||
export async function sendWolPacket(mac, broadcast = "255.255.255.255", port = 9) {
|
||||
const packet = createWolPacket(mac);
|
||||
const socket = dgram.createSocket("udp4");
|
||||
|
||||
await new Promise((resolve, reject) => {
|
||||
socket.once("error", reject);
|
||||
socket.bind(() => {
|
||||
socket.setBroadcast(true);
|
||||
socket.send(packet, port, broadcast, err => {
|
||||
socket.close();
|
||||
if (err) reject(err);
|
||||
else resolve();
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user