|
#!/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"; |
|
} |