50 lines
1.3 KiB
JavaScript
50 lines
1.3 KiB
JavaScript
import dgram from "node:dgram"
|
|
import { exec } from "node:child_process";
|
|
|
|
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();
|
|
});
|
|
});
|
|
});
|
|
}
|
|
|
|
export function ping(ip) {
|
|
return new Promise(resolve => {
|
|
exec(`ping -c 1 -W 1 ${ip}`, err => {
|
|
resolve(!err);
|
|
});
|
|
});
|
|
} |