ts
// wake-on-lan.ts
import { createSocket, Socket } from 'node:dgram';
/**
* 发送 Wake-on-LAN 魔术包
* @param macAddress 目标设备的 MAC 地址(格式如 "AA:BB:CC:DD:EE:FF" 或 "AA-BB-CC-DD-EE-FF")
* @param targetIp 目标子网的广播地址或 IP(如 "192.168.1.255" 或路由器的公网 IP)
* @param port 目标端口(默认 9)
*/
async function sendMagicPacket(
macAddress: string,
targetIp: string = '255.255.255.255',
port: number = 9,
): Promise {
const normalizedMac = macAddress.replace(/[^0-9A-Fa-f]/g, '');
if (normalizedMac.length !== 12) {
throw new Error('Invalid MAC address');
}
const macBuffer = Buffer.from(normalizedMac, 'hex');
const magicPacket = Buffer.concat([
Buffer.from('FFFFFFFFFFFF', 'hex'),
...Array(16).fill(macBuffer),
]);
const socket: Socket = createSocket('udp4');
return new Promise((resolve, reject) => {
// 绑定 Socket 到本地随机端口(0 表示系统自动分配)
socket.bind(0, () => {
try {
// 关键步骤:绑定后再设置广播
socket.setBroadcast(true);
} catch (err) {
reject(new Error('Failed to set broadcast'));
socket.close();
return;
}
// 发送魔术包
socket.send(magicPacket, port, targetIp, (err) => {
socket.close();
err ? reject(err) : resolve();
});
});
socket.on('error', (err) => {
socket.close();
reject(err);
});
});
}
const MAC = 'C3-G5-E7-17-DF-2A'; // 替换为目标 MAC
const TARGET_IP = '192.168.1.255'; // 目标子网广播地址
const PORT = 9; // WoL 默认端口
sendMagicPacket(MAC, TARGET_IP, PORT)
.then(() => console.log('Magic packet sent!'))
.catch((err) => console.error('Error:', err.message));