New IT forum Follow us on Twitter
23 May 2012, 04:39:36 pm *
Welcome, Guest. Please login or register.
Did you miss your activation email?

Login with username, password and session length
News: EFIKA MX now in stock!
 
   Home   SHOP Help Search Login Register  
Pages: [1]
  Print  
Author Topic: Wake On LAN example code  (Read 2587 times)
NewIT_Marcus
Administrator
Hero Member
*****
Posts: 960


« on: 02 November 2009, 12:07:24 am »

Here's some PHP code that would enable you to send Wake On Lan packets to selected devices. You could make this available on a plug running PHP and a web server.

The configurable parts are at the top of the code listing; set the names / IP addresses / MAC addresses according to your needs. The IP address element and the links section are optional.

You can remove the password protection for the web page by changing $my_password = '123'; to: $my_password = '';


<?php

/* ============================== Configuration settings ====================================== */

/* List of PCs that may be woken */
$config_network_data_array[] = array("name" => "PC #1", "MAC" => "00:00:13:00:C3:A0", "IP" => "192.168.1.14", "WakeIP" =>
"192.168.1.255");
$config_network_data_array[] = array("name" => "PC #2", "MAC" => "00:00:13:00:C3:A1", "IP" => "192.168.1.15", "WakeIP" =>
"192.168.1.255");
$config_network_data_array[] = array("name" => "PC #3", "MAC" => "00:00:13:00:C3:5E", "IP" => "192.168.1.16", "WakeIP" =>
"192.168.1.255");

/* Optional list of URLs associated with the devices listed above */
$config_network_links_array['PC #1'] = array("webmin" => "https://192.168.1.14:10000");
$config_network_links_array['PC #2'] = array("website" => "http://192.168.1.15", "forum" => "http://192.168.1.15/forum");

// Port number where the computer is listening. Usually, any number between 1-50000 will do. Normally people choose 7 or 9.
$socket_number = "7";

$my_password = '123';
// If you don't want to password-protect:
$my_password = '';

$html_title = '<H2>My Wake On LAN devices</H2>';

$config_table_columns = array('name', 'IP', 'MAC', 'links');

# The following function is copied (with some edits, to suppress output and return TRUE or an error message) from:
# http://www.hackernotcracker.com/2006-04/wol-wake-on-lan-tutorial-with-bonus-php-script.html

# Wake on LAN - (c) HotKey@spr.at, upgraded by Murzik
# Modified by Allan Barizo http://www.hackernotcracker.com

flush();

function WakeOnLan($addr, $mac,$socket_number) {

   $separator = ':';
   if (strstr ( $mac, '-' ) ) {
      $separator = '-';
   }
   $addr_byte = explode($separator, $mac);

   $hw_addr = '';
   for ($a=0; $a <6; $a++) $hw_addr .= chr(hexdec($addr_byte[$a]));
   $msg = chr(255).chr(255).chr(255).chr(255).chr(255).chr(255);
   for ($a = 1; $a <= 16; $a++) $msg .= $hw_addr;
   // send it to the broadcast address using UDP
   // SQL_BROADCAST option isn't help!!
   $s = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
   if ($s == false) {
//      echo "Error creating socket!\n";
//      echo "Error code is '".socket_last_error($s)."' - " . socket_strerror(socket_last_error($s));
      return "Error creating socket!\nError code is '".socket_last_error($s)."' - " . socket_strerror(socket_last_erro
($s));
//      return FALSE;
      }
   else {
      // setting a broadcast option to socket:
      $opt_ret = socket_set_option($s, 1, 6, TRUE);
      if($opt_ret <0) {
//         echo "setsockopt() failed, error: " . strerror($opt_ret) . "\n";
         return "setsockopt() failed, error: " . strerror($opt_ret) . "\n";
//         return FALSE;
         }
      if(socket_sendto($s, $msg, strlen($msg), 0, $addr, $socket_number)) {
//         echo "Magic Packet sent successfully!";
         socket_close($s);
         return TRUE;
         }
      else {
//         echo "Magic packet failed!";
         return "Magic packet failed!";
//         return FALSE;
         }
      }
   }

/* ============================== some predefined texts ====================================== */

$display_sent = 'Magic Packet sent successfully!';
$button_text = 'Wake!';
$button_text2 = 'Wake all selected';

$password_element = "<P>password: <input type=\"text\" name=\"password\" /><input type=\"submit\" name=\"submit\" value = \"procee
\" />";

$table_html = "<TABLE border=\"2\">\n";
$logout_html = '';

/* ========================= Test for password protection ==================================== */
$wake_MAC_array = array();

if (!isset ($_POST['logout'])) {
   $input_password = $_POST['password'];
}

if (($input_password === $my_password) or ($my_password === '')) {
   $logged_in = TRUE;
   $hidden_login = "<input type=\"hidden\" name=\"password\" value=\"$my_password\"/>";
   if ($my_password !== '') {
      $logout_html = "\n<P><input type=\"submit\" name=\"logout\" value=\"Log Out\"/>\n";
   }
   if ( (isset ($_POST['tickbox'])) and (is_array($_POST['tickbox']) ) ) {
      $checkbox_array = $_POST['tickbox'];
      foreach ($checkbox_array as $mac_address => $tickbox_setting) {
         $wake_MAC_array[$mac_address] = $tickbox_setting;
      }

   }

} else {
   $logged_in = FALSE;
   $hidden_login = '';
   $table_html = $password_element;
}

/* ================================ LOGGED-IN users only ===================================== */
/* ======================= construct table for listing of devices ============================ */

if ($logged_in == TRUE) {
   $table_row = "\n<TR>";
   foreach ($config_table_columns as $key => $column_heading) {
      $table_row .= '<TD>' . $column_heading . '</TD>';
   }
   $table_row .= '<TD>Wake Up!</TD>';
   $table_row .= '<TD>status</TD>';
   $table_html .= $table_row . "</TR>\n";
   foreach ($config_network_data_array as $device_key => $device_values) {
      $table_row = "\n<TR>";
      $mac = $device_values['MAC'];
      $device_name = $device_values['name'];
      $status_cell = '<TD>&nbsp;</TD>';
      foreach ($config_table_columns as $key => $column_heading) {
         if (isset ( $device_values[$column_heading])) {
            $value = $device_values[$column_heading];
            if ($column_heading == 'MAC') {
/* special coding for MAC address column; prepare clickable button */
               $this_MAC = $value;
               $value = "<input type=\"submit\" name=\"wake_MAC\" value = \"$value\" />";

               if (( $_POST['wake_MAC'] === $this_MAC ) or (array_key_exists ($this_MAC,
$wake_MAC_array))) {
                  $status = WakeOnLan ($device_values['WakeIP'], $this_MAC, $socket_number) ;
                  if ( $status === TRUE ) {
                     $status = $display_sent;
                  }
                  $status_cell = "<TD>$status</TD>";
               }
            }
         } elseif ($column_heading == 'links') {
/* special coding for links column; prepare clickable links from $config_network_links_array */
            $value = '';
            if (isset ( $config_network_links_array[$device_name])) {
               foreach ($config_network_links_array[$device_name] as $link_title => $link_URL) {
                  if ( $value !== '') {
                     $value .= '<BR />';
                  }
                  $value .= '<A HREF="' . $link_URL . '">' . $link_title . '</A>';
               }
            }
         } else {
            $value = '';
         }
      if ($value === '') {
         $value = '&nbsp;';
      }
      $table_row .= '<TD>' . $value . '</TD>';
      }
/* now add a checkbox to wake up this device */
      $table_row .= '<TD>' . "<input type=\"checkbox\" name=\"tickbox[$this_MAC]\" />" . '</TD>';
/* now add the status message (if applicable) for the attempt to send a packet to this device */
      $table_row .= $status_cell;
      $table_html .= $table_row . "</TR>\n";
   }
   $table_html .= "</TABLE>\n";
   $table_html .= "<P><input type=\"submit\" name=\"wake all\" value = \"$button_text2\" />\n";
}
/* =========================================================================================== */
/* ======================= Now output the html that we've built ============================== */

echo $html_title;

echo "<FORM name=\"input\" action=\"" .$_SERVER['PHP_SELF'] . "\" method=\"post\">";
echo '<P>';
echo $table_html;
echo $hidden_login;
echo $logout_html;
echo "</FORM>\n";
 
?>


See also:
http://www.hackernotcracker.com/2006-04/wol-wake-on-lan-tutorial-with-bonus-php-script.html
http://www.dd-wrt.com/wiki/index.php/WOL



** Edited 2009-11-05 to fix a stupid error in the code for testing whether or not a password is set, and whether or not the logout button appears when there is no password **
« Last Edit: 05 November 2009, 05:52:43 pm by NewIT_Marcus » Logged
NewIT_Marcus
Administrator
Hero Member
*****
Posts: 960


« Reply #1 on: 03 November 2009, 06:18:30 pm »

We should definitely add that there is a package named wakeonlan in the Sheevaplug / Ubuntu repository.

You could use the wakeonlan package if you intended to log in remotely (via ssh, for instance), then send wake on lan commands from the command line (using scripts named after each device name, perhaps, or a script that could take a device name as parameter). Or you could schedule the sending of wake-up commands at predefined times of day, or based on checks for predefined events.

The point of creating this php script is to provide a visual interface rather than a command line interface. But there are of course lots of prerequisites to this visual / php method, ie the web server components. So this solution is just one way of doing it.
Logged
Pages: [1]
  Print  
 
Jump to:  

Powered by MySQL Powered by PHP Powered by SMF 1.1.16 | SMF © 2011, Simple Machines Valid XHTML 1.0! Valid CSS!