-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathUrbanTerrorServer.php
90 lines (68 loc) · 2.32 KB
/
UrbanTerrorServer.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php
/**
* Author: Abu Ashraf Masnun
* URL: http://masnun.me
*/
class UrbanTerrorServer
{
private $host;
private $port;
private $queryMessage = "\377\377\377\377getstatus";
public function __construct($host, $port)
{
$this->host = $host;
$this->port = $port;
}
public function getStatus()
{
$response = $this->_getRawResponse();
$lines = explode("\n", $response);
$serverData = explode("\\", $lines[1]);
$serverConfigs = array();
for ($i = 1; $i < count($serverData); $i = $i + 2) {
$key = strtolower(trim($serverData[$i]));
$val = trim($serverData[$i + 1]);
$serverConfigs[$key] = $val;
}
$players = array();
for ($i = 2; $i < count($lines); $i++) {
if (!empty($lines[$i])) {
$playerInfo = explode(' ', $lines[$i]);
$name = "";
for ($j = 2; $j < count($playerInfo); $j++) {
$name .= " {$playerInfo[$j]}";
}
$players[] = array(
"name" => str_replace('"', '', $name),
"score" => $playerInfo[0],
"ping" => $playerInfo[1]
);
}
}
$data = array(
'server_configs' => $serverConfigs,
'players' => $players
);
return $data;
}
private function _getRawResponse()
{
// Create UDP Socket
if (!($sock = socket_create(AF_INET, SOCK_DGRAM, 0))) {
throw new Exception(socket_strerror(socket_last_error()));
}
socket_set_option($sock, SOL_SOCKET, SO_RCVTIMEO, array('sec' => 1, 'usec' => 0));
socket_set_option($sock, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 1, 'usec' => 0));
// Send the status query
if (!socket_sendto($sock, $this->queryMessage, strlen($this->queryMessage), 0, $this->host, $this->port)) {
throw new Exception(socket_strerror(socket_last_error()));
}
//Now receive reply from server and return it
if (socket_recv($sock, $reply, 2045, MSG_WAITALL) === FALSE) {
throw new Exception(socket_strerror(socket_last_error()));
} else {
socket_close($sock);
return $reply;
}
}
}