-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
67 lines (66 loc) · 1.85 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
const net = require('net');
const udp = require('dgram');
/**
* [createMagicPacket]
* @param {[type]} mac [description]
* @return {[type]} [description]
* @wiki https://en.wikipedia.org/wiki/Wake-on-LAN
* @docs http://support.amd.com/TechDocs/20213.pdf
*/
function createMagicPacket(mac){
const MAC_REPEAT = 16;
const MAC_LENGTH = 0x06;
const PACKET_HEADER = 0x06;
const parts = mac.match(/[0-9a-fA-F]{2}/g);
if(!parts || parts.length != MAC_LENGTH)
throw new Error(`malformed MAC address "${mac}"`);
var buffer = Buffer.alloc(PACKET_HEADER);
var bufMac = Buffer.from(parts.map(p => parseInt(p, 16)));
buffer.fill(0xff);
for(var i = 0; i < MAC_REPEAT; i++){
buffer = Buffer.concat([ buffer, bufMac ]);
}
return buffer;
};
/**
* [wake on lan]
* @param {[type]} mac [description]
* @param {[type]} options [description]
* @param {Function} callback [description]
* @return {[type]} [description]
*/
function wake(mac, options, callback){
options = options || {};
if(typeof options == 'function'){
callback = options;
}
const { address, port } = Object.assign({
address : '255.255.255.255',
port : 9
}, options);
// create magic packet
var magicPacket = createMagicPacket(mac);
var socket = udp.createSocket(
net.isIPv6(address) ? 'udp6' : 'udp4'
).on('error', function(err){
socket.close();
callback && callback(err);
}).once('listening', function(){
socket.setBroadcast(true);
});
return new Promise((resolve, reject) => {
socket.send(
magicPacket, 0, magicPacket.length,
port, address, function(err, res){
let result = res == magicPacket.length;
if(err) reject(err);
else resolve(result);
callback && callback(err, result);
socket.close();
});
});
};
module.exports = {
wake,
createMagicPacket
};