Exemplo n.º 1
1
 function processPacket($packetData)
 {
     $packet = new dhcpPacket();
     $packet->parse($packetData);
     $processor = new dhcpRequestProcessor($this, $this->packetProcessor, $this->storage, $packet);
     if ($responsePacket = $processor->getResponse()) {
         $responseData = $responsePacket->build();
         $this->verbosity && (print "Sending response" . "\n");
         $ciaddr = $packet->getClientAddress();
         if ($ciaddr == '0.0.0.0') {
             $this->verbosity && (print "Switching to broadcast address...\n");
             $ciaddr = '255.255.255.255';
         }
         $this->verbosity && (print "Attempting to send response packet to " . $ciaddr . "\n");
         $numBytesSent = socket_sendto($this->socket, $responseData, strlen($responseData), 0, $ciaddr, 68);
         if ($numBytesSent === FALSE) {
             $this->verbosity && (print "send failed for specific address, broadcast.\n");
             $numBytesSent = socket_sendto($this->socket, $responseData, strlen($responseData), 0, "255.255.255.255", 68);
             $numBytesSent === FALSE && $this->verbosity && printf('socket send error: %s\\n', socket_strerror(socket_last_error($this->socket)));
         }
         $numBytesSent && $this->verbosity && (print "Response packet sent.\n");
     } else {
         $this->verbosity && (print "Packet ignored\n");
     }
 }
Exemplo n.º 2
0
function print_sock_err($sock, $type)
{
    $errno = socket_last_error($sock);
    $errmsg = socket_strerror($errno);
    echo "{$type} ERROR:{$errno} - {$errmsg}" . PHP_EOL;
    socket_close($sock);
}
Exemplo n.º 3
0
 public function __construct(Server $server, $password, $port = 19132, $interface = "0.0.0.0", $threads = 1, $clientsPerThread = 50)
 {
     $this->server = $server;
     $this->workers = [];
     $this->password = (string) $password;
     $this->server->getLogger()->info("Starting remote control listener");
     if ($this->password === "") {
         $this->server->getLogger()->critical("RCON can't be started: Empty password");
         return;
     }
     $this->threads = (int) max(1, $threads);
     $this->clientsPerThread = (int) max(1, $clientsPerThread);
     $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     if ($this->socket === false or !socket_bind($this->socket, $interface, (int) $port) or !socket_listen($this->socket)) {
         $this->server->getLogger()->critical("RCON can't be started: " . socket_strerror(socket_last_error()));
         $this->threads = 0;
         return;
     }
     socket_set_block($this->socket);
     for ($n = 0; $n < $this->threads; ++$n) {
         $this->workers[$n] = new RCONInstance($this->socket, $this->password, $this->clientsPerThread);
     }
     socket_getsockname($this->socket, $addr, $port);
     $this->server->getLogger()->info("RCON running on {$addr}:{$port}");
 }
 public function connect()
 {
     $this->socketCon = socket_connect($this->socketVar, $this->ip, $this->port);
     if (!$this->socketCon) {
         die("Cannot Connnect: Exiting With Exception : " . socket_strerror(socket_last_error()) . PHP_EOL);
     }
 }
Exemplo n.º 5
0
 public function index()
 {
     error_reporting(E_ALL);
     set_time_limit(0);
     $service_port = 6005;
     $address = "203.130.45.233";
     $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     if ($socket < 0) {
         echo "socket_create() failed: reason: " . socket_strerror($socket) . "\n";
     }
     $result = socket_connect($socket, $address, $service_port);
     if ($result < 0) {
         echo "socket_connect() failed.\nReason: ({$result}) " . socket_strerror($result) . "\n";
     } else {
         echo "连接OK<br>";
     }
     $in = "1!";
     //1!是发给这个设备的指令
     $out = '';
     $out1 = '';
     if (!socket_write($socket, $in, strlen($in))) {
         echo "socket_write() failed: reason: " . socket_strerror($socket) . "\n";
     }
     while ($out = socket_read($socket, 8192)) {
         //$out=trim($out,"0xff");
         //$out=trim($out,"0x00");
         //$this->xieru($out,"sj");
         echo $out;
     }
     socket_close($socket);
 }
Exemplo n.º 6
0
 public function socketClose()
 {
     $this->sock_error = socket_strerror(socket_last_error($this->fsock));
     socket_clear_error();
     @socket_close($this->fsock);
     return $this;
 }
function refresh_user($discord_id)
{
    global $socket, $error;
    $so = socket_create(AF_UNIX, SOCK_DGRAM, 0);
    if ($so === false) {
        $msg = socket_strerror(socket_last_error());
        $error = "Socket failed: {$msg}";
    } else {
        $res = socket_connect($so, $socket);
        if ($res === false) {
            $msg = socket_strerror(socket_last_error());
            $error = "Connect failed: {$msg}";
        } else {
            $payload = json_encode(array('action' => 'refresh', 'user_id' => $discord_id));
            $res = socket_write($so, $payload);
            if ($res === false) {
                $error = "Socket send failed";
            } else {
                if ($res < strlen($payload)) {
                    $error = "Socket did not send all data";
                }
            }
            socket_shutdown($so);
            socket_close($so);
        }
    }
}
Exemplo n.º 8
0
 private static function _tcp_send_request($socket_write_json = null)
 {
     $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     if (false === $sock) {
         echo "sock create error!\n";
     }
     $address = Config::get("kgi.kgi_mid_server_ip");
     $port = Config::get("kgi.kgi_mid_server_port");
     try {
         $result = socket_connect($sock, $address, $port);
         if ($result === false) {
             echo "socket_connect() failed.\nReason: ({$result}) " . socket_strerror(socket_last_error($sock)) . "\n";
             exit;
             die;
         }
         socket_write($sock, $socket_write_json, strlen($socket_write_json));
         while ($out_str = socket_read($sock, 2048)) {
             //                echo "revice result\n";
             //                echo $out_str . "\n";
             $json_data = json_decode($out_str);
             break;
         }
         socket_close($sock);
     } catch (\ErrorException $e) {
         //echo $e->getMessage() . "\n";
     }
 }
Exemplo n.º 9
0
 /**
  * @param resource $socket
  * @return string
  */
 protected function getSocketError($socket = null)
 {
     if ($socket === null && $this->socket) {
         $socket = $this->socket;
     }
     return socket_strerror(socket_last_error($socket));
 }
Exemplo n.º 10
0
 private function await()
 {
     $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     if ($sock < 0) {
         echo "Error:" . socket_strerror(socket_last_error()) . "\n";
     }
     $ret = socket_bind($sock, $this->ip, $this->port);
     if (!$ret) {
         echo "BIND FAILED:" . socket_strerror(socket_last_error()) . "\n";
         exit;
     }
     echo "OK\n";
     $ret = socket_listen($sock);
     if ($ret < 0) {
         echo "LISTEN FAILED:" . socket_strerror(socket_last_error()) . "\n";
     }
     do {
         $new_sock = null;
         try {
             $new_sock = socket_accept($sock);
         } catch (Exception $e) {
             echo $e->getMessage();
             echo "ACCEPT FAILED:" . socket_strerror(socket_last_error()) . "\n";
         }
         try {
             $request_string = socket_read($new_sock, 1024);
             $response = $this->output($request_string);
             socket_write($new_sock, $response);
             socket_close($new_sock);
         } catch (Exception $e) {
             echo $e->getMessage();
             echo "READ FAILED:" . socket_strerror(socket_last_error()) . "\n";
         }
     } while (TRUE);
 }
Exemplo n.º 11
0
 protected function _checkClosedRequests()
 {
     foreach ($this->_clients as $key => $client) {
         if (in_array($client, $this->_read)) {
             $buf = @socket_read($client, 1024, PHP_NORMAL_READ);
             if ($buf === false) {
                 throw new Exception\Listener(socket_strerror(socket_last_error($client)));
             }
             $buf = trim($buf);
             if ($buf) {
                 switch ($buf) {
                     case 'quit':
                         print "Close connection\n";
                         unset($this->_clients[$key]);
                         $this->_requests[$key]->finished = true;
                         unset($this->_requests[$key]);
                         socket_close($client);
                         break;
                     case 'shutdown':
                         throw new Exception\Listener('Shutdown detected');
                 }
             }
         }
     }
     return true;
 }
Exemplo n.º 12
0
 private function mainLoop()
 {
     $changed_sockets = $this->allsockets;
     @socket_select($changed_sockets, $write = null, $exceptions = null, 0);
     foreach ($this->apps as $app) {
         $app->onTick();
     }
     foreach ($changed_sockets as $socket) {
         if ($socket == $this->master) {
             if (($rec = socket_accept($this->master)) < 0) {
                 $this->log("Error: Could not connect\n" . socket_strerror(socket_last_error($rec)));
                 continue;
             } else {
                 $this->log("New client connecting...");
                 $client = new Connection($this, $rec);
                 $this->clients[$rec] = $client;
                 $this->allsockets[] = $rec;
             }
         } else {
             $client = $this->clients[$socket];
             $bytes = @socket_recv($socket, $data, 4096, 0);
             if (!$bytes) {
                 $client->onDisconnect();
                 unset($this->clients[$socket]);
                 $index = array_search($socket, $this->allsockets);
                 unset($this->allsockets[$index]);
                 unset($client);
             } else {
                 $client->onData($data);
             }
         }
     }
 }
Exemplo n.º 13
0
function sendcmd($in, $address, $service_port)
{
    /* Create a TCP/IP socket. */
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if ($socket === false) {
        return "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
    }
    $result = socket_connect($socket, $address, $service_port);
    if ($result === false) {
        return "socket_connect() failed.\nReason: ({$result}) " . socket_strerror(socket_last_error($socket)) . "\n";
    }
    socket_write($socket, $in, strlen($in));
    $mess = "";
    /*$next = "";*/
    sleep(1);
    /*$next = socket_read($socket, 4096);*/
    while (0 != socket_recv($socket, $out, 4096, MSG_DONTWAIT)) {
        if ($out != null) {
            $mess .= $out;
        }
    }
    /*$mess .= $next;*/
    socket_close($socket);
    return $mess;
}
Exemplo n.º 14
0
function create_connection($host, $port)
{
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if (!is_resource($socket)) {
        echo 'Unable to create socket: ' . socket_strerror(socket_last_error()) . PHP_EOL;
    } else {
        echo "Socket created.\n";
    }
    if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
        echo 'Unable to set option on socket: ' . socket_strerror(socket_last_error()) . PHP_EOL;
    } else {
        echo "Set options on socket.\n";
    }
    if (!socket_bind($socket, $host, $port)) {
        echo 'Unable to bind socket: ' . socket_strerror(socket_last_error()) . PHP_EOL;
    } else {
        echo "Socket bound to port {$port}.\n";
    }
    if (!socket_listen($socket, SOMAXCONN)) {
        echo 'Unable to listen on socket: ' . socket_strerror(socket_last_error());
    } else {
        echo "Listening on the socket.\n";
    }
    while (true) {
        $connection = @socket_accept($socket);
        if ($connection) {
            echo "Client {$connection} connected!\n";
            send_data($connection);
        } else {
            echo "Bad connection.";
        }
    }
}
Exemplo n.º 15
0
function queryAPI($jsonQuery)
{
    $service_port = 12345;
    $address = "localhost";
    $msg = "{\n   \"array\": [\n";
    echo $msg;
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if ($socket === false) {
        die('{"type" : "error", "msg" : "connection error: ' . socket_strerror(socket_last_error()) . '"}]}');
    }
    $result = socket_connect($socket, $address, $service_port);
    if ($result === false) {
        die('{"type" : "error", "msg" : "connection error: ' . socket_strerror(socket_last_error($socket)) . '"}]}');
    }
    $in = stripslashes($jsonQuery);
    socket_write($socket, $in, strlen($in));
    socket_write($socket, ';', 1);
    $buffer = "";
    while ($out = socket_read($socket, 2048)) {
        echo $out;
        ob_flush();
        flush();
    }
    #JSON Array end
    $msg = "]\n }";
    echo $msg;
    echo PHP_EOL;
    ob_flush();
    flush();
    socket_close($socket);
}
Exemplo n.º 16
0
 public function __construct()
 {
     $this->socket = socket_create(AF_INET, SOCK_STREAM, 0);
     if ($this->socket < 0) {
         sendError('socket_create() failed: reason: ' . socket_strerror($this->socket));
     }
 }
Exemplo n.º 17
0
function server_loop($address, $port)
{
    global $__server_listening;
    // AF_UNIX AF_INET
    if (($sock = socket_create(AF_INET, SOCK_STREAM, 0)) < 0) {
        events("failed to create socket: " . socket_strerror($sock), __FUNCTION__, __LINE__);
        exit;
    }
    if (($ret = socket_bind($sock, $address, $port)) < 0) {
        events("failed to bind socket: " . socket_strerror($ret), __FUNCTION__, __LINE__);
        exit;
    }
    if (($ret = socket_listen($sock, 0)) < 0) {
        events("failed to listen to socket: " . socket_strerror($ret), __FUNCTION__, __LINE__);
        exit;
    }
    socket_set_nonblock($sock);
    events(count($GLOBALS["LOCAL_DOMAINS"]) . " internals domains...", __FUNCTION__, __LINE__);
    events("waiting for clients to connect", __FUNCTION__, __LINE__);
    while ($__server_listening) {
        $connection = @socket_accept($sock);
        if ($connection === false) {
            if ($GLOBALS["DebugArticaFilter"] == 1) {
                events("sleep", __FUNCTION__, __LINE__);
            }
            usleep(2000000);
        } elseif ($connection > 0) {
            handle_client($sock, $connection);
        } else {
            events("error: " . socket_strerror($connection), __FUNCTION__, __LINE__);
            die;
        }
    }
}
Exemplo n.º 18
0
function coop_send($message)
{
    if (!($sock = socket_create(AF_INET, SOCK_STREAM, 0))) {
        $errorcode = socket_last_error();
        $errormsg = socket_strerror($errorcode);
        die("Couldn't create socket: [{$errorcode}] {$errormsg} \n");
    }
    //Connect socket to remote server
    if (!socket_connect($sock, COOPSERVER, COOPPORT)) {
        $errorcode = socket_last_error();
        $errormsg = socket_strerror($errorcode);
        die("Could not connect: [{$errorcode}] {$errormsg} \n");
    }
    //Send the message to the server
    if (!socket_send($sock, $message, strlen($message), 0)) {
        $errorcode = socket_last_error();
        $errormsg = socket_strerror($errorcode);
        die("Could not send data: [{$errorcode}] {$errormsg} \n");
    }
    $buf = 'my buffer';
    if (false !== ($bytes = socket_recv($sock, $buf, 1024, 0))) {
        echo "Read {$bytes} bytes of socket_recv(). close socket ...";
    } else {
        echo "socket_recv() error; Reason: " . socket_strerror(socket_last_error($socket)) . "\n";
    }
    socket_close($sock);
    return $buf;
}
Exemplo n.º 19
0
 public function ajax()
 {
     //判断Socket模块是否加载
     if (!extension_loaded('sockets')) {
         die('php sockets extension not loaded!');
     }
     //判断websocket服务器是否已运行, 没有运行则执行下面的代码创建, 防止重复创建websocket
     if (!add_lock('welive')) {
         die('WEBSOCKET server is running ...');
     }
     // socket接受或发送的最大数据限制(字节) 128K
     define('WEBSOCKET_MAX', 1024 * 128);
     // 最大连接数(设置大些, 可能有仅连接不传送信息的非法连接, 无法关闭)
     define('WEBSOCKET_ONLINE', 2048);
     // 屏蔽错误代码
     error_reporting(0);
     // 设置超时时间
     @set_time_limit(0);
     @ignore_user_abort(true);
     //忽略用户断开连接, 服务器脚本仍运行
     // 设置当前脚本可使用的最大内存, 默认为1024M, 同时连接人数太多时,可能不够
     @ini_set('memory_limit', '1024M');
     $websocket = new Websocket(WS_HOST, WS_PORT);
     $websocket->domain = '';
     //允许的域名
     $websocket->run();
     echo socket_strerror($websocket->error());
 }
Exemplo n.º 20
0
function WakeOnLan($addr, $mac_address, $socket_number)
{
    $addr_byte = explode(':', $mac_address);
    $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 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, $ip_address, $socket_number)) {
                    echo "Magic Packet sent successfully!";
                    socket_close($s);
                    return TRUE;
                } else {
                    echo "Magic packet failed!";
                    return FALSE;
                }
            }
        }
    }
}
Exemplo n.º 21
0
function SendMail($email, $subject, $text)
{
    $address = 'mail.iptm.ru';
    // адрес smtp-сервера
    $port = 25;
    // порт (стандартный smtp - 25)
    // $from    = '=?utf-8?b?' . base64_encode('Конференция «Рентгеновская оптика»') . '?= <*****@*****.**>';  // адрес отправителя
    $from = '*****@*****.**';
    // адрес отправителя
    try {
        $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        // Создаем сокет
        if ($socket < 0) {
            throw new Exception('socket_create() failed: ' . socket_strerror(socket_last_error()) . "\n");
        }
        $result = socket_connect($socket, $address, $port);
        // Соединяем сокет к серверу
        if ($result === false) {
            throw new Exception('socket_connect() failed: ' . socket_strerror(socket_last_error()) . "\n");
        }
        read_smtp_answer($socket);
        // Читаем информацию о сервере
        write_smtp_response($socket, 'EHLO ' . $_SERVER['SERVER_NAME']);
        // Приветствуем сервер
        read_smtp_answer($socket);
        // ответ сервера
        write_smtp_response($socket, 'MAIL FROM:<' . $from . '> BODY=8BITMIME');
        // Задаем адрес отправителя
        read_smtp_answer($socket);
        // ответ сервера
        write_smtp_response($socket, 'RCPT TO:<' . $email . '>');
        // Задаем адрес получателя
        read_smtp_answer($socket);
        // ответ сервера
        write_smtp_response($socket, 'DATA');
        // Готовим сервер к приему данных
        read_smtp_answer($socket);
        // ответ сервера
        $header = "From: " . $from . "\r\n";
        $header .= "To: " . $email . "\r\n";
        $header .= "Subject: =?utf-8?b?" . base64_encode($subject) . "?=\r\n";
        $header .= "Content-Type: text/plain; charset=\"utf-8\"\r\n";
        $header .= "Content-Transfer-Encoding: base64\r\n";
        $header .= "Mime-Version: 1.0\r\n";
        $text = $header . base64_encode($text);
        write_smtp_response($socket, $text . "\r\n.");
        // Отправляем данные
        read_smtp_answer($socket);
        // ответ сервера
        write_smtp_response($socket, 'QUIT');
        // Отсоединяемся от сервера
        read_smtp_answer($socket);
        // ответ сервера
    } catch (Exception $e) {
        echo "\nError: " . $e->getMessage();
    }
    if (isset($socket)) {
        socket_close($socket);
    }
}
Exemplo n.º 22
0
 function call($command, $parameters = array(), $user = false)
 {
     if (empty($this->user) || empty($this->pass)) {
         return false;
     }
     if ($user == false) {
         $cmd = array($this->user, $this->pass);
     } else {
         $cmd = array($user, $this->user . ':' . $this->pass);
     }
     array_push($cmd, $command);
     array_push($cmd, $parameters);
     $this->write($this->itype->fromphp($cmd));
     $response = $this->read();
     if ($response === false) {
         Error::warn('Connection failure', array('Could not read from server', socket_strerror(socket_last_error())));
         return false;
     }
     $parsedResponse = $this->itype->parse($response);
     if ($parsedResponse[0] == 'empty') {
         Error::warn('Connection failure', array('Could not parse data delivered by server', $line));
         return false;
     }
     $response = $this->itype->flat($parsedResponse);
     if (is_a($response, 'itype_exception')) {
         $response = $response->getCode();
     }
     return $response;
 }
Exemplo n.º 23
0
 /**
  * Connects the TCP socket to the host with the given IP address and port number
  */
 public function connect(InetAddress $ipAddress, $portNumber)
 {
     $this->ipAddress = $ipAddress;
     $this->portNumber = $portNumber;
     if ($this->socketsEnabled) {
         if (!($this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) {
             $errorCode = socket_last_error($this->socket);
             throw new Exception("Could not create socket: " . socket_strerror($errorCode));
         }
         if (@(!socket_connect($this->socket, $ipAddress, $portNumber))) {
             $errorCode = socket_last_error($this->socket);
             throw new Exception("Could not connect socket: " . socket_strerror($errorCode));
         }
         if ($this->isBlocking) {
             socket_set_block($this->socket);
         } else {
             socket_set_nonblock($this->socket);
         }
     } else {
         if (!($this->socket = fsockopen("tcp://{$ipAddress}", $portNumber, $socketErrno, $socketErrstr, 2))) {
             throw new Exception("Could not create socket.");
         }
         stream_set_blocking($this->socket, $this->isBlocking);
     }
 }
Exemplo n.º 24
0
function sendsock($in)
{
    global $config;
    $service_port = $config['sockport'];
    $address = $config['sockhost'];
    if (!function_exists("socket_create")) {
        error_log(date("y-m-d H:i:s") . " 未启用socket模块\n", 3, "error.log");
        return null;
    }
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if ($socket === false) {
        error_log(date("y-m-d H:i:s") . "socket_create() failed, reason: " . socket_strerror(socket_last_error()) . "\n", 3, "error.log");
        return null;
    }
    $result = socket_connect($socket, $address, $service_port);
    if ($result === false) {
        error_log(date("y-m-d H:i:s") . "socket_connect() failed.\nReason: ({$result}) " . socket_strerror(socket_last_error($socket)) . "\n", 3, "error.log");
        return null;
    }
    socket_write($socket, $in, strlen($in));
    $result = socket_read($socket, 8192);
    $arr = unpack("C*", $result);
    socket_close($socket);
    return $arr;
}
Exemplo n.º 25
0
 public function run()
 {
     $ret = array();
     while (true) {
         $inArr = $this->get_files_by_ext($this->urlFilePath, 'url');
         if (!empty($inArr)) {
             sleep(2);
             foreach ($inArr as $in) {
                 if (!in_array($in, $ret)) {
                     $ret[] = $in;
                     exec("cp {$this->urlFilePath}{$in} {$this->backupFilePath}");
                     $fileContent = file_get_contents($this->urlFilePath . $in);
                     if (socket_write($this->socket, $fileContent, strlen($fileContent))) {
                         $this->addLog("发送到服务器信息成功!发送的内容为: {$fileContent}");
                         sleep(2);
                     } else {
                         $this->addLog("发送失败! reason :" . socket_strerror($this->socket));
                     }
                 }
             }
         } else {
             $this->addLog("无URL文件");
             sleep(1);
         }
     }
 }
Exemplo n.º 26
0
function getsock($port)
{
    $socket = null;
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if ($socket === false || $socket === null) {
        $error = socket_strerror(socket_last_error());
        $msg = "socket create({$port}) failed";
        echo "ERR: {$msg} '{$error}'\n";
        return NULL;
    }
    socket_set_nonblock($socket);
    $res = socket_connect($socket, API_HOST, $port);
    $timeout = 50;
    while ($res === false && $timeout > 0) {
        $err = socket_last_error($socket);
        echo ".";
        if ($timeout > 1 && ($err == 115 || $err == 114)) {
            $timeout--;
            usleep(50);
            $res = socket_connect($socket, API_HOST, $port);
            continue;
        }
        $error = socket_strerror($err);
        $msg = "socket connect({$port}) failed";
        echo "ERR: {$msg} '{$error}'\n";
        socket_close($socket);
        return NULL;
    }
    socket_set_block($socket);
    return $socket;
}
Exemplo n.º 27
0
 /**
  * Send message package to the socket server
  * Basic layer method
  * 
  * @return mixed
  */
 public function send($msg, $is_block = false)
 {
     if (!$this->host || !$this->port) {
         throw new Hush_Socket_Exception("Please set server's host and port first");
     }
     /* Create a TCP/IP socket. */
     $this->sock = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
     if ($this->sock < 0) {
         echo "socket_create() failed.\nReason: " . socket_strerror($this->sock) . "\n";
     }
     $result = @socket_connect($this->sock, $this->host, $this->port);
     if ($result < 0) {
         echo "socket_connect() failed.\nReason: ({$result}) " . socket_strerror($result) . "\n";
     }
     if ($is_block) {
         @socket_set_nonblock($this->sock);
     }
     // add suffix for socket msg
     $msg = trim($msg) . "\r\n";
     @socket_write($this->sock, $msg, strlen($msg));
     $result = @socket_read($this->sock, 2048);
     // unserialize data from socket server
     $result = unserialize(trim($result));
     return $result;
 }
Exemplo n.º 28
0
function getsock($addr, $port)
{
    $socket = null;
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if ($socket === false || $socket === null) {
        $error = socket_strerror(socket_last_error());
        $msg = "socket create(TCP) failed";
        echo "ERR: {$msg} '{$error}'\n";
        return null;
    }
    $res = socket_connect($socket, $addr, $port);
    if ($res === false) {
        $error = socket_strerror(socket_last_error());
        $msg = '<center class="alert alert-danger bs-alert-old-docs">CGMiner is not running...If it is not restart after minutes ,please try to reboot.</center>';
        socket_close($socket);
        echo $msg;
        @exec('sudo service cgminer stop ');
        @exec('sudo service cgminer stop ');
        @exec('sudo service cgminer stop ');
        $network = get_network();
        $gateway = $network['gateway_id'];
        @exec('sudo  route add default gw ' . $gateway);
        //sleep(3);
        //@exec('sudo service cgminer start &');
        //showmsg($msg,'?c=home&m=reboot','10000');
        //echo "ERR: $msg '$error'\n";
        //exit;
        return null;
    }
    return $socket;
}
Exemplo n.º 29
0
function execute_script($scriptid, $hostid)
{
    $res = 1;
    $command = script_make_command($scriptid, $hostid);
    $nodeid = id2nodeid($hostid);
    $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if (!$socket) {
        $res = 0;
    }
    if ($res) {
        global $ZBX_SERVER, $ZBX_SERVER_PORT;
        $res = socket_connect($socket, $ZBX_SERVER, $ZBX_SERVER_PORT);
    }
    if ($res) {
        $send = "Command­{$nodeid}­{$hostid}­{$command}\n";
        socket_write($socket, $send);
    }
    if ($res) {
        $res = socket_read($socket, 65535);
    }
    if ($res) {
        list($flag, $msg) = split("­", $res);
        $message["flag"] = $flag;
        $message["message"] = $msg;
    } else {
        $message["flag"] = -1;
        $message["message"] = S_CONNECT_TO_SERVER_ERROR . ' [' . $ZBX_SERVER . ':' . $ZBX_SERVER_PORT . '] [' . socket_strerror(socket_last_error()) . ']';
    }
    if ($socket) {
        socket_close($socket);
    }
    return $message;
}
Exemplo n.º 30
-1
function sendUSD($text, $pass_server = '000000')
{
    $address = gethostbyname('127.0.0.1');
    //IP Адрес вашего компьютера
    $service_port = 8000;
    //Порт
    //$pass_server='000000'; //Пароль
    $phone = preg_replace('/^\\+/', '', $phone);
    $socket = socket_create(AF_INET, SOCK_STREAM, 0);
    if ($socket < 0) {
        echo "socket create failed reason: " . socket_strerror($socket) . "\n";
    }
    $result = socket_connect($socket, $address, $service_port);
    if ($result < 0) {
        echo "socket connect failed.\nReason: ({$result}) " . socket_strerror($result) . "\n";
    }
    $text = iconv("UTF-8", "Windows-1251", $text);
    $in = base64_encode($pass_server . "#CMD#[USSD]" . $text);
    //Пример отправки смс
    //$in = base64_encode($pass_server."#CMD#[USSD]*102#"); //Пример запроса USSD команды
    $out = '';
    socket_write($socket, $in, strlen($in));
    //echo "Response:\n\n";
    $res = '';
    while ($out = socket_read($socket, 2048)) {
        $res .= $out;
    }
    socket_close($socket);
    $res = iconv("Windows-1251", "UTF-8", $res);
    if (preg_match('/USSD-RESPONSE\\[.+?\\]:(.+)/is', $res, $m)) {
        $res = $m[1];
    }
    return $res;
}