魔术包唤醒睡眠中的电脑
2023年11月12日
预计阅读:1min
有时候需要链接家里远程电脑做一些事情,但是家里电脑一直开着也浪费电,于是写了给电脑发送魔术包的小工具核心代码如下:
const dgram = require('dgram');
const wakeOnLAN = (mac, options) => {
const address = options.address || '255.255.255.255'
const port = options.port || 9;
// 创建UDP包
const createMagicPacket = mac => {
const macFormat = mac.replaceAll('-', '');
const bufMac = Buffer.from(macFormat, 'hex');
const bufFirst = Buffer.alloc(6, 0xff);
return Buffer.concat([bufFirst, Buffer.alloc(16 * bufMac.length, bufMac)]);
};
return new Promise((resolve, reject) => {
const packet = createMagicPacket(mac);
const client = dgram.createSocket('udp4');
client.on('listening', () => {
// 开启广播模式
client.setBroadcast(true);
console.log(client.address())
})
client.send(packet, 0, packet.length, port, address, err => {
client.close();
if (err) return reject(err);
resolve('success');
},);
client.on('error', err => {
client.close();
reject(err);
});
});
};
在线体验地址:https://wol.hackshen.com/