warning: 这篇文章距离上次修改已过225天,其中的内容可能已经有所变动。
国庆假期就这么过去了,今天分享下NodeJS如何通过魔术封包唤醒局域网计算机的代码吧。
/**
* 通过魔术封包唤醒局域网计算机
* @author 若海 <[email protected]>
* @website http://www.rehiy.com
* @wiki https://en.wikipedia.org/wiki/Wake-on-LAN
* @docs http://support.amd.com/TechDocs/20213.pdf
*/
const net = require('net');
const udp = require('dgram');
/**
* 创建魔术封包
* @param {string} mac 网卡MAC地址
* @returns {Buffer}
*/
function createMagicPacket(mac) {
mac = mac.replace(/[^0-9a-fA-F]/g, '');
if (mac.length != 12) {
throw new Error(`Bad MAC address "${mac}"`);
}
const bufMac = Buffer.from(mac, 'hex');
let bufRes = Buffer.alloc(6, 0xff);
for (let i = 0; i < 16; i++) {
bufRes = Buffer.concat([bufRes, bufMac]);
}
return bufRes;
}
/**
* 通过网络唤醒
* @param {string} mac 网卡MAC地址
* @param {object} options 可选项
* @returns {Promise<boolean>}
*/
function wakeOnLAN(mac, options) {
options = Object.assign({
address: '255.255.255.255',
port: 7
}, options);
return new Promise((resolve, reject) => {
const packet = createMagicPacket(mac);
const socket = udp.createSocket(
net.isIPv6(options.address) ? 'udp6' : 'udp4'
);
socket.on('error', function (err) {
socket.close();
reject(err);
});
socket.once('listening', function () {
socket.setBroadcast(true);
});
socket.send(
packet,
0,
packet.length,
options.port,
options.address,
function (err, res) {
socket.close();
if (err) {
return reject(err);
}
resolve(res == packet.length);
}
);
});
}
来个例子~
wakeOnLAN('30:9C:FF:FF:FF:FF').then(
res => {
console.log(res);
},
err => {
console.log(err.message);
}
);
正文完