Created
June 4, 2021 09:57
-
-
Save FinlayDaG33k/21117b208becd6972800157291a1ea8a to your computer and use it in GitHub Desktop.
Just a quick WoL sender for Deno I wrote a while ago (may be broken nowadays)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Author: Aroop Roelofs <[email protected]> | |
* License: Do Whatever You Want With it | |
*/ | |
import { Buffer } from "https://deno.land/std/io/mod.ts"; | |
interface IWolOptions { | |
recipient?: IRecipient; | |
} | |
interface IRecipient { | |
address: string; | |
port: number; | |
} | |
export default class WakeOnLan { | |
private packet: any; | |
constructor(mac: string){ | |
this.packet = this.magic(mac); | |
} | |
/** | |
* Create our magic packet. | |
* | |
* @param mac | |
* @returns unknown | |
*/ | |
private magic(mac: string) { | |
// Define some constants | |
const macRepeat = 16; | |
const macLength = 0x06; | |
const header = 0x06; | |
//Make sure our MAC is valid | |
const parts = mac.match(/[0-9a-f-A-F]{2}/g); | |
if(!parts || parts.length !== macLength) throw new Error(`MAC address "${mac} is malformed!`); | |
// Create a new buffer for our packet and add our header to it | |
let packet = Buffer.alloc(header); | |
// Create a new buffer from our MAC | |
const macBuf = Buffer.from(parts.map((p: any) => parseInt(p, 16))); | |
// Fill our packet with ones | |
packet.fill(0xff); | |
// Add all bytes of our MAC to the packet | |
for(let i = 0; i < macRepeat; i++) { | |
packet = Buffer.concat([packet, macBuf]); | |
} | |
// Return our packet | |
return packet; | |
} | |
/** | |
* Send our WOL packet to whom it may concern | |
* | |
* @param options | |
*/ | |
public wake(options: IWolOptions = {}) { | |
// Assign our address and port | |
// Broadcast if no recipient address or port are specified | |
const { address, port } = Object.assign({ | |
address: '255.255.255.255', | |
port: 9 | |
}, options.recipient); | |
// Create a UDP socket | |
const socket = Deno.listenDatagram({port: port, transport: "udp"}); | |
// Add event handlers to our socket | |
socket.on('error', (err: Error) => { | |
socket.close(); | |
throw err; | |
}); | |
// Enable broadcasting | |
socket.once('listening', () => { | |
socket.setBroadcast(true); | |
}); | |
// Send our packet | |
socket.send( | |
this.packet, | |
0, | |
this.packet.length, | |
port, | |
address, | |
(err: any, res: any) => { | |
if(res !== this.packet.length) throw new Error(`Result and packet length mismatch!`); | |
if(err) throw err; | |
socket.close(); | |
} | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment