ajaxCall('$g_name','$address','$mac','$port','$ip'); "; } } //////////////////////////////////////////////////////////////////////// // // PHP Functions // /////////////////////////////////////////////////////////////////////// //pingIP attempts to connect to the specified IP and port for a time specified by timeout, at which point it returns false //if it succeeds before this time, it returns true. This is used to checl the status of our server function pingIP($l_ip,$l_timeout,$l_port){ $file = @fsockopen($l_ip,$l_port,$errno,$errstr,$l_timeout); if($file) return true; else return false; } /////////////////////////////////////// //This function sends the magic packet and then waits for the server to come online, before //returning the ajax call to let the browser know the server is online (hopefully)! function wakeOnLan($l_ip,$l_port,$l_mac,$l_timeout){ //echo $l_port.'....'.$l_mac.'....'.$l_ip.'....'.$l_timeout.'......'; //Send magic packet magicPacket($l_ip,$l_mac,$l_port); //keep pinging until server comes online(or php times out). Echo will return from ajax call. echo pingIP($l_ip,$l_timeout,$l_port); } /////////////////////////////////////// //This function sends the magic packet to the PC // //The structure of the magic packet is: //00 ff ff ff ff ff ff //xx xx xx xx xx xx xx //xx xx xx xx xx xx xx // //xxxx=...16 repetitions of mac address (decimal) of the interface looking for the WoL packet // //Our packet will be sent as an ascii string. Therefore we must ensure that the ascii charactwers used //map to the correct hex codes (currently our mac address is an ascii representation of hex codes, wheras we want the ascii characters //represented by those hex codes. So we first convert the hex to its decimal equivalent, and then find the ascii character this represents //(we do it is two stages since the chr function needs decimal values to lookup) function magicPacket($addr,$mac,$socket_number) { //split up the mac address based upon the colons in the string $addr_byte = explode(':', $mac); $hw_addr = ''; for ($a=0; $a <6; $a++) $hw_addr .=chr(hexdec($addr_byte[$a])); //convert the hex to its decimal equivalent, encode as a character, and repeat 16 times $msg = str_repeat(chr(255),6); //FF in decimal is 255, which is then encoded as a char as with our mac address for ($a = 1; $a <= 16; $a++) $msg .= $hw_addr; $s = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); //create our socket if ($s == false) { echo "Error creating socket!\n"; echo "Error code is '".socket_last_error($s)."'- " . socket_strerror(socket_last_error($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 false; } if(socket_sendto($s, $msg, strlen($msg), 0, $addr,$socket_number)) { socket_close($s); return true; } else { return false; } } } ?>