Skip to content

Instantly share code, notes, and snippets.

@learosema
Last active January 30, 2019 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save learosema/c01600aa6452eb562f62 to your computer and use it in GitHub Desktop.
Save learosema/c01600aa6452eb562f62 to your computer and use it in GitHub Desktop.
Quick and dirty wake on lan script

Simple php script that broadcasts a magic wake on lan packet with a given mac address. The accepted formattings of the mac adress parameter are xx:xx:xx:xx:xx:xx or xx-xx-xx-xx-xx-xx or without :/-.

##License

            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
                    Version 2, December 2004

 Copyright (C) 2019 Lea Rosema

 Everyone is permitted to copy and distribute verbatim or modified
 copies of this license document, and changing it is allowed as long
 as the name is changed.

          DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
 TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. You just DO WHAT THE FUCK YOU WANT TO.
#!/usr/bin/php -q
<?php
// default options (change to your needs)
$destip = "192.168.0.255";
$port = 9;
if ($argc < 2) {
echo "terabaud's magic packet sender.\nUsage: $argv[0] mac-address [destination-ip[:port]]\n";
return;
}
if ($argc >= 3) {
$idx = strpos($argv[2], ':');
if ($idx > -1) {
$destip = substr($argv[2], 0, $idx);
$port = intval(substr($argv[2], $idx + 1));
} else {
$destip = $argv[2];
}
}
send_magic_packet($argv['1'], $destip, $port);
return;
function mac_to_bin($h)
{
$numbers= "0123456789abcdef";
$result = '';
if (! preg_match("/^(([0-9a-fA-F]{2}-){5}([0-9a-fA-F]{2})|([0-9a-fA-F]{2}:){5}([0-9a-fA-F]{2}))$/", $h)) {
return FALSE;
}
$h = strtolower(preg_replace('/[:-]/','', $h));
if ($h == '000000000000') {
return FALSE;
}
for ($i = 0; $i < strlen($h); $i+=2) {
$p1 = strpos($numbers, $h[$i]);
$p2 = strpos($numbers, $h[$i+1]);
if ($p1 === FALSE || $p2 === FALSE) {
return FALSE;
}
$result .= chr($p1 * 16 + $p2);
}
return $result;
}
function create_magic_packet($mac)
{
$buf = "\xff\xff\xff\xff\xff\xff";
$macbin = mac_to_bin($mac);
if ($macbin === FALSE) {
return FALSE;
}
for ($i = 0 ; $i < 16; $i++)
{
$buf .= $macbin;
}
return $buf;
}
function send_magic_packet($mac, $ip, $port)
{
$buf = create_magic_packet($mac);
if ($buf === FALSE) {
echo "Invalid mac address.\n";
return;
}
$s = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_set_option($s, SOL_SOCKET, SO_BROADCAST, 1);
if (socket_sendto($s, $buf, strlen($buf), 0, $ip, $port) < 0)
{
echo socket_last_error($s);
socket_close($s);
return;
}
socket_close($s);
echo "Package sent.\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment