Last active
August 29, 2015 14:06
-
-
Save jkelin/35b2428a4b01f4335eb3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function loadCache(){ | |
if (file_exists('cache.json')) { | |
$fh = fopen('cache.json', 'a'); | |
fwrite($fh, ''); | |
} else { | |
$fh = fopen('cache.json', 'w'); | |
fwrite($fh, ''); | |
} | |
fclose($fh); | |
$stuff = file_get_contents('cache.json'); | |
//die($stuff); | |
$a =json_decode($stuff,true); | |
if($a == null)return Array('kokot'); | |
return $a; | |
} | |
function saveCache($cache){ | |
file_put_contents('cache.json', json_encode($cache)); | |
} | |
function getServerInfo($ip, $port){ | |
//$host = '94.225.105.70'; | |
//$port = 777; | |
$text = "\\basic\\"; | |
if ($sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP)) | |
{ | |
error_reporting(E_ERROR | E_PARSE); | |
try { | |
//stream_set_timeout($sock,5); | |
socket_set_option($sock,SOL_SOCKET,SO_RCVTIMEO,array('sec'=>5,'usec'=>5000)); | |
if( ! socket_sendto($sock, $text , strlen($text) , 0 , $ip , $port)) | |
{ | |
$errorcode = socket_last_error(); | |
$errormsg = socket_strerror($errorcode); | |
die("Could not send data: [$errorcode] $errormsg \n"); | |
} | |
//Now receive reply from server and print it | |
//socket_set_nonblock($sock); | |
$a = socket_recv($sock, $reply, 2048, 0); | |
if(0 == $a || $a == FALSE) | |
{ | |
$errorcode = socket_last_error(); | |
$errormsg = socket_strerror($errorcode); | |
return json_encode(Array('error'=>$errorcode)); | |
} | |
//die("test"); | |
$chunks = explode('\\', $reply); | |
$o = array(); | |
for ($i = 1; $i < count($chunks); $i=$i + 2) { | |
$o[$chunks[$i]] = $chunks[$i + 1]; | |
} | |
return json_encode($o); | |
} catch (Exception $e) { | |
return json_encode(Array('error'=>$e)); | |
} | |
} | |
else die("bs"); | |
} | |
function tryGettingFromCache($ip, $port, $cache){ | |
if(array_key_exists($ip.$port,$cache)){ | |
$t1 = strtotime($cache[$ip.$port]['time']); | |
$t2 = strtotime(date("Y-m-d H:i:s")); | |
if($t2 - $t1 < 10)return $cache[$ip.$port]['stuff']; | |
} | |
return null; | |
} | |
$cache = loadCache(); | |
//die(json_encode($cache)); | |
$stuff = tryGettingFromCache($_GET['ip'],$_GET['port'],$cache); | |
if($stuff == null)$stuff = getServerInfo($_GET['ip'],$_GET['port']); | |
header("Content-type: application/json"); | |
header("Access-Control-Allow-Origin: *"); | |
echo $stuff; | |
$cache[$_GET['ip'].$_GET['port']] = []; | |
$cache[$_GET['ip'].$_GET['port']]['time'] = date("Y-m-d H:i:s"); | |
$cache[$_GET['ip'].$_GET['port']]['stuff'] = $stuff; | |
saveCache($cache); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment