1 #!/usr/bin/php5 -q
2 <?php
4 error_reporting(E_ALL);
6 //IP to bind to, use 0 for all
7 $bind_ip = 0;
9 // Port to bind
10 $bind_port = 10000;
12 // Max clients
13 $max_clients = 3;
15 // Rijndal encrypt key
16 $enable_encryption = TRUE;
17 $encrypt_key = "ferdinand_frostferdinand_frostfe";
19 /* Create Socket -
20 * AF_INET means IPv4 Socket
21 * SOCK_STREAM means Fullduplex TCP
22 * SOL_TCP - Protocol type TCP
23 */
24 $socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
26 /* Enable reuse of local address */
27 socket_set_option($socket,SOL_SOCKET,SO_REUSEADDR,1);
29 /* Bind to socket */
30 socket_bind($socket,$bind_ip,$bind_port);
31 socket_listen($socket,$max_clients);
33 $clients = array('0' => array('socket' => $socket));
35 echo "\nServer startet on port : $bind_port\n";
38 /* Open the cipher */
39 $td = mcrypt_module_open('rijndael-128', '', 'cbc', '');
41 /* Create the IV and determine the keysize length */
42 $iv = substr(md5('GONICUS GmbH'),0, mcrypt_enc_get_iv_size($td));
43 $ks = mcrypt_enc_get_key_size($td);
44 echo "IV-Size: ".mcrypt_enc_get_iv_size($td)."\n";
46 /* Create key */
47 $key = substr(md5('ferdinand_frost'), 0, $ks);
48 echo "Key: $key\n";
50 /* Intialize encryption */
51 mcrypt_generic_init($td, $key, $iv);
53 /* Accept connections till server is killed */
54 while(TRUE) {
56 /* Create an array of sockets to read from */
57 $read[0] = $socket;
58 for($i=1;$i<count($clients)+1;$i++) {
59 if(isset($clients[$i] ) && $clients[$i] != NULL) {
60 $read[$i+1] = $clients[$i]['socket'];
61 }
62 }
64 $ready = socket_select($read,$write=NULL,$except=NULL,0);
66 /* Handle incoming connections / Incoming data */
67 if(in_array($socket,$read)) {
69 /* Check each client slot for a new connection */
70 for($i=1;$i<$max_clients+1;$i++) {
72 /* Accept new connections */
73 if(!isset($clients[$i])) {
74 $clients[$i]['socket'] = socket_accept($socket);
75 socket_getpeername($clients[$i]['socket'],$ip);
76 $clients[$i]['ipaddy'] = $ip;
78 echo("New client connected: " . $clients[$i]['ipaddy'] . " \n");
79 break;
80 }
81 elseif($i == $max_clients - 1) {
82 echo("To many Clients connected! \n");
83 }
84 if($ready < 1) {
85 continue;
86 }
87 }
88 }
90 /* Check if there is data to read from the client sockets */
91 for($i=1;$i<$max_clients+1;$i++) {
93 /* Check if socket has send data to the server */
94 if(isset($clients[$i]) && in_array($clients[$i]['socket'],$read)) {
96 /* Read socket data */
97 $data = @socket_read($clients[$i]['socket'],1024000, PHP_NORMAL_READ);
99 /* Client disconnected */
100 if ($data === FALSE) {
101 unset($clients[$i]);
102 echo "Client disconnected!\n";
103 continue;
104 }
106 $data = mdecrypt_generic($td, trim($data));
107 echo "Client (".$clients[$i]['ipaddy'].") sent: ".$data."... \n";
109 echo "Sending reply... \n";
110 socket_write($clients[$i]['socket'],mcrypt_generic($td, $data));
112 @socket_close($clients[$i]);
113 }
114 }
115 }
117 ?>