Skip to content

Instantly share code, notes, and snippets.

@seanbecker15
Created June 21, 2024 17:25
Show Gist options
  • Save seanbecker15/456ddec169eb68aa7e48d38234bb5283 to your computer and use it in GitHub Desktop.
Save seanbecker15/456ddec169eb68aa7e48d38234bb5283 to your computer and use it in GitHub Desktop.
NodeJS Script to Wake LG on LAN
import dgram from "dgram";
const IP = "192.168.X.X";
const PORT = "9922";
const MAC = "XX:XX:XX:XX:XX:XX";
let sanitizedMac = MAC;
// remove filling from MAC
const CharsToRemove = ["\\.", ":", "-"];
for (let j = 0; j < CharsToRemove.length; j++) {
sanitizedMac = sanitizedMac.replace(new RegExp(CharsToRemove[j], "g"), "");
}
// Build a magic packet (6 x 0xFF followed by 16 x MAC) and broadcast it
if (sanitizedMac.length === 12) {
const Message = new Uint8Array(102);
const MACstr = new Uint8Array(6);
for (let j = 0; j < 6; j++) {
Message[j] = 0xff;
MACstr[j] = parseInt(sanitizedMac.substr(j * 2, 2), 16);
}
for (let j = 1; j <= 16; j++) {
Message.set(MACstr, j * 6);
}
// Send Wake On LAN packet
const LANDestination = {
address: IP,
port: parseInt(PORT, 10),
};
const buffer = Buffer.from(Message);
const socket = dgram.createSocket("udp4");
console.log(
"Sending Wake On LAN packet to",
LANDestination.address,
"on port",
LANDestination.port
);
socket.send(
buffer,
0,
buffer.length,
LANDestination.port,
LANDestination.address,
(err) => {
if (err) {
console.error("Error sending Wake On LAN packet:", err);
} else {
console.log("Wake On LAN packet sent successfully");
}
socket.close();
}
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment