NodeJS通過魔術封包喚醒局域網計算機實例

今天分享下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);
    }
);

以上就是NodeJS通過魔術封包喚醒局域網計算機實例的詳細內容,更多關於NodeJS喚醒局域網計算機的資料請關註WalkonNet其它相關文章!

推薦閱讀: