Exemplo n.º 1
3
 /**
  *  scans the local network for upnp devices
  *
  * @return array with discovered devices
  */
 function scan()
 {
     $this->checkCredentials();
     $result = array();
     $buffer = '';
     $tmp = '';
     $headers = "M-SEARCH * HTTP/1.1\r\nHost:239.255.255.250:1900\r\nST:" . $this->type . "\r\nMan:\"ssdp:discover\"\r\nMX:3\r\n\r\n";
     $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
     socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => 15, 'usec' => 10000));
     $i = 0;
     socket_sendto($socket, $headers, 1024, 0, '239.255.255.250', 1900);
     while (@socket_recvfrom($socket, $buffer, 1024, MSG_WAITALL, $tmp, $mp)) {
         $i++;
         $res = $this->decode($buffer);
         if (isset($res['location'])) {
             $res_details = $this->getDetails($res['location']);
             if ($res_details[0] == true) {
                 $res['details'] = $res_details[1];
             } else {
                 $res['details'] = false;
             }
         }
         $result[] = $res;
     }
     socket_close($socket);
     return array(true, $result);
 }
Exemplo n.º 2
0
 public static function create_socket_server($host = "0.0.0.0", $port = 3465)
 {
     //Create a UDP socket
     if (!($sock = socket_create(AF_INET, SOCK_DGRAM, 0))) {
         $errorcode = socket_last_error();
         $errormsg = socket_strerror($errorcode);
         die("Couldn't create socket: [{$errorcode}] {$errormsg} \n");
     }
     echo "Socket created \n";
     // Bind the source address
     if (!socket_bind($sock, $host, $port)) {
         $errorcode = socket_last_error();
         $errormsg = socket_strerror($errorcode);
         die("Could not bind socket : [{$errorcode}] {$errormsg} \n");
     }
     echo "Socket bind OK \n";
     // Connect to Redis.
     $redis = new \Predis\Client();
     // Do some communication, this loop can handle multiple clients
     while (true) {
         //Receive some data
         $r = socket_recvfrom($sock, $buf, Eventsd::MaxUDPPacket, 0, $remote_ip, $remote_port);
         $redis->rpush('events_que', $buf);
         unset($event, $buf, $remote_ip, $remote_port);
     }
     socket_close($sock);
 }
Exemplo n.º 3
0
 public function mServer()
 {
     $sock = socket_create(AF_INET, SOCK_DGRAM, getprotobyname('udp'));
     $mIP = '239.255.255.250';
     if (!socket_bind($sock, $mIP, 1900)) {
         $errorcode = socket_last_error();
         $errormsg = socket_strerror($errorcode);
         die("Could not bind socket : [{$errorcode}] {$errormsg} \n");
     }
     socket_set_option($sock, IPPROTO_IP, MCAST_JOIN_GROUP, array("group" => '239.255.255.250', "interface" => 0));
     while (1) {
         echo "Waiting for data ... \n";
         socket_recvfrom($sock, $buf, 512, 0, $remote_ip, $remote_port);
         echo "{$remote_ip} : {$remote_port} -- " . $buf;
         $query = $this->parseHeaders($buf);
         if (!isset($query["m-search"])) {
             continue;
         }
         $response = "HTTP/1.1 200 OK\r\n";
         $response .= "CACHE-CONTROL: max-age=1810\r\n";
         $response .= "DATE: " . date("r") . "\r\n";
         $response .= "EXT:\r\n";
         $response .= "LOCATION: http://192.168.7.123:9000/TMSDeviceDescription.xml\r\n";
         $response .= "SERVER: Linux/3.x, UPnP/1.1, fheME/0.6\r\n";
         $response .= "ST: urn:fheme.de:service:X_FIT_HomeAutomation:1\r\n";
         $response .= "USN: uuid:f6da16ab-0d1b-fe1c-abca-82aacf4afcac::urn:fheme.de:service:X_FIT_HomeAutomation:1\r\n";
         $response .= "Content-Length: 0\r\n";
         $response .= "\r\n";
         //Send back the data to the client
         socket_sendto($sock, $response, strlen($response), 0, $mIP, $remote_port);
     }
     socket_close($sock);
 }
Exemplo n.º 4
0
 private function get_peers_blocking($info_hash, $host = "router.bittorrent.com", $port = 6881)
 {
     //create a UDP socket to send commands through
     $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
     //Create Command Packet
     $packet = bencode::encode(array("id" => $this->get_unique_node_id(), "info_hash" => hex2bin($info_hash)), array("q" => "get_peers", "t" => $this->unique_id(), "y" => "q"));
     socket_sendto($socket, $packet, strlen($packet), 0, $host, $port);
     //set timeout
     $timeout = array('sec' => 5, 'usec' => 0);
     socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, $timeout);
     $time = time();
     //recieve data
     try {
         socket_recvfrom($socket, $buf, 12000, 0, $host, $port);
     } catch (Exception $e) {
         echo "Error";
         return FALSE;
     }
     //have to manually do the timeout, cant seem to get info from this socket
     if (time() - $time >= 4) {
         socket_close($socket);
         return FALSE;
     }
     //close socket so bad shit don't happen
     socket_close($socket);
     return nodeExtract::return_nodes(bencode::decode($buf));
 }
Exemplo n.º 5
0
 public function udp()
 {
     set_time_limit(0);
     $ip = '127.0.0.1';
     $port = 9527;
     $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
     socket_bind($socket, $ip, $port);
     $mem = init_mem();
     if ($mem == false) {
         return;
     }
     while (true) {
         socket_recvfrom($socket, $content, 1024, 0, $ip, $port);
         if (empty($content)) {
             continue;
         }
         //$this->log_data($content);
         $minute = (int) date("i");
         $datagram = $mem->get('datagram');
         if (empty($datagram)) {
             $datagram = array();
         }
         $datagram[$minute][] = $content;
         $mem->set('datagram', $datagram);
     }
     socket_close($socket);
     $mem->close();
 }
Exemplo n.º 6
0
 public function read(&$buf, &$source, &$port)
 {
     if ($this->connected === false) {
         return false;
     }
     return @socket_recvfrom($this->sock, $buf, 65535, 0, $source, $port);
 }
Exemplo n.º 7
0
 public function search($st = 'ssdp:all', $mx = 2, $man = 'ssdp:discover', $from = null, $port = null, $sockTimout = '2')
 {
     $request = 'M-SEARCH * HTTP/1.1' . "\r\n";
     $request .= 'HOST: 239.255.255.250:1900' . "\r\n";
     $request .= 'MAN: "' . $man . '"' . "\r\n";
     $request .= 'MX: ' . $mx . '' . "\r\n";
     $request .= 'ST: ' . $st . '' . "\r\n";
     $request .= 'USER-AGENT: ' . $this->user_agent . "\r\n";
     $request .= "\r\n";
     $socket = socket_create(AF_INET, SOCK_DGRAM, 0);
     socket_set_option($socket, SOL_SOCKET, SO_BROADCAST, true);
     socket_sendto($socket, $request, strlen($request), 0, '239.255.255.250', 1900);
     socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => $sockTimout, 'usec' => '0'));
     $response = array();
     do {
         $buf = null;
         socket_recvfrom($socket, $buf, 1024, MSG_WAITALL, $from, $port);
         if (!is_null($buf)) {
             $data = $this->parseSearchResponse($buf);
             $response[$data['usn']] = $data;
         }
     } while (!is_null($buf));
     socket_close($socket);
     return $response;
 }
Exemplo n.º 8
0
 /**
  * Does a TFTP Check by connecting to $host looking for $filename
  * @author http://www.php.net/manual/en/function.socket-create.php#43057
  * @param string $host
  * @param string $filename
  * @return mixed file contents 
  */
 function tftp_fetch($host, $filename)
 {
     //first off let's check if this is installed or disabled
     $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
     // create the request packet
     $packet = chr(0) . chr(1) . $filename . chr(0) . 'octet' . chr(0);
     // UDP is connectionless, so we just send on it.
     socket_sendto($socket, $packet, strlen($packet), 0x100, $host, 69);
     $buffer = '';
     $port = '';
     $ret = '';
     $time = time();
     do {
         $new_time = time() - $time;
         if ($new_time > 5) {
             break;
         }
         // $buffer and $port both come back with information for the ack
         // 516 = 4 bytes for the header + 512 bytes of data
         socket_recvfrom($socket, $buffer, 516, 0, $host, $port);
         // add the block number from the data packet to the ack packet
         $packet = chr(0) . chr(4) . substr($buffer, 2, 2);
         // send ack
         socket_sendto($socket, $packet, strlen($packet), 0, $host, $port);
         // append the data to the return variable
         // for large files this function should take a file handle as an arg
         $ret .= substr($buffer, 4);
     } while (strlen($buffer) == 516);
     // the first non-full packet is the last.
     return $ret;
 }
Exemplo n.º 9
0
 /**
  * Perform an M-SEARCH multicast request for detecting UPnP-devices in network.
  *
  * @todo Allow unicasting.
  * @todo Sort arguments better.
  */
 public function mSearch($st = 'ssdp:all', $mx = 2, $man = 'ssdp:discover', $from = null, $port = null, $sockTimout = '5')
 {
     // BUILD MESSAGE
     $msg = 'M-SEARCH * HTTP/1.1' . "\r\n";
     $msg .= 'HOST: 239.255.255.250:1900' . "\r\n";
     $msg .= 'MAN: "' . $man . '"' . "\r\n";
     $msg .= 'MX: ' . $mx . "\r\n";
     $msg .= 'ST:' . $st . "\r\n";
     $msg .= 'USER-AGENT: ' . static::USER_AGENT . "\r\n";
     $msg .= '' . "\r\n";
     // MULTICAST MESSAGE
     $sock = socket_create(AF_INET, SOCK_DGRAM, 0);
     $opt_ret = socket_set_option($sock, 1, 6, TRUE);
     $send_ret = socket_sendto($sock, $msg, strlen($msg), 0, '239.255.255.250', 1900);
     // SET TIMEOUT FOR RECIEVE
     socket_set_option($sock, SOL_SOCKET, SO_RCVTIMEO, array('sec' => $sockTimout, 'usec' => '0'));
     // RECIEVE RESPONSE
     $response = array();
     do {
         $buf = null;
         @socket_recvfrom($sock, $buf, 1024, MSG_WAITALL, $from, $port);
         if (!is_null($buf)) {
             $response[] = $this->parseMSearchResponse($buf);
         }
     } while (!is_null($buf));
     // CLOSE SOCKET
     socket_close($sock);
     return $response;
 }
Exemplo n.º 10
0
 public function doTick()
 {
     $this->lastmeasure = microtime(true);
     $timeout = 50000;
     while (!$this->shutdown and $timeout >= 0) {
         $address = $port = $buffer = null;
         if (@socket_recvfrom($this->socket, $buffer, 65535, 0, $address, $port) > 0) {
             isset($this->banlist[(string) $address]) ? $this->loginfo((int) $this->banlist[$address] . ' ' . time()) : false;
             if (!isset($this->banlist[$address]) or (int) $this->banlist[$address] < time()) {
                 switch ($buffer[0]) {
                     case Info::PKHEAD_DATA:
                         $this->pushMainQueue(new DataPacket($address, $port, $buffer));
                         break;
                     case Info::PKHEAD_BASE64:
                         $this->pushMainQueue(new Base64Packet($address, $port, $buffer));
                         break;
                     case Info::PKHEAD_ENUM:
                         $this->pushMainQueue(new EnumPacket($address, $port, $buffer));
                         break;
                     default:
                         $this->pushMainQueue($pk - new InvalidPacket($address, $port, $buffer));
                         $this->logInfo("Custompacket received packet with invalid header! Printing dump...");
                         $pk->printDump();
                 }
             }
         }
         $timeout = $this->lastmeasure - microtime(true);
     }
 }
Exemplo n.º 11
0
 private function _read($sock, $len, $timeout)
 {
     $data = '';
     $size = 0;
     while ($size < $len) {
         $r = array($sock);
         $w = array();
         $e = array();
         $n = socket_select($r, $w, $e, $timeout);
         if ($n === false) {
             throw new Bert_Rpc_Error_ConnectionError($this->_svc->host, $this->_svc->port, socket_strerror(socket_last_error()));
         } elseif ($n === 0) {
             throw new Bert_Rpc_Error_ReadTimeoutError($this->_svc->host, $this->_svc->port, $this->_svc->timeout);
         }
         $bytes = socket_recvfrom($sock, $msg, $len - $size, 0, $name, $port);
         if ($bytes === false) {
             throw new Bert_Rpc_Error_ConnectionError($this->_svc->host, $this->_svc->port, socket_strerror(socket_last_error()));
         } elseif ($bytes === 0) {
             throw new Bert_Rpc_Error_ReadError($this->_svc->host, $this->_svc->port);
         }
         $size += $bytes;
         $data .= $msg;
     }
     return $data;
 }
Exemplo n.º 12
0
Arquivo: net.php Projeto: pshreez/PHP
 /**
 		Send ICMP echo request to specified host; Return array containing
 		minimum/average/maximum round-trip time (in millisecs) and number of
 		packets received, or FALSE if host is unreachable
 			@return mixed
 			@param $addr string
 			@param $dns boolean
 			@param $count integer
 			@param $wait integer
 			@param $ttl integer
 			@public
 	**/
 static function ping($addr, $dns = FALSE, $count = 3, $wait = 3, $ttl = 30)
 {
     // ICMP transmit socket
     $tsocket = socket_create(AF_INET, SOCK_RAW, 1);
     // Set TTL
     socket_set_option($tsocket, 0, PHP_OS != 'Linux' ? 4 : 2, $ttl);
     // ICMP receive socket
     $rsocket = socket_create(AF_INET, SOCK_RAW, 1);
     // Bind to all network interfaces
     socket_bind($rsocket, 0, 0);
     // Initialize counters
     list($rtt, $rcv, $min, $max) = array(0, 0, 0, 0);
     for ($i = 0; $i < $count; $i++) {
         // Send ICMP header and payload
         $data = uniqid();
         $payload = self::hexbin('0800000000000000') . $data;
         // Recalculate ICMP checksum
         if (strlen($payload) % 2) {
             $payload .= self::hexbin('00');
         }
         $bits = unpack('n*', $payload);
         $sum = array_sum($bits);
         while ($sum >> 16) {
             $sum = ($sum >> 16) + ($sum & 0xffff);
         }
         $payload = self::hexbin('0800') . pack('n*', ~$sum) . self::hexbin('00000000') . $data;
         // Transmit ICMP packet
         @socket_sendto($tsocket, $payload, strlen($payload), 0, $addr, 0);
         // Start timer
         $time = microtime(TRUE);
         $rset = array($rsocket);
         $tset = NULL;
         $xset = NULL;
         // Wait for incoming ICMP packet
         socket_select($rset, $tset, $xset, $wait);
         if ($rset && @socket_recvfrom($rsocket, $reply, 255, 0, $host, $port)) {
             $elapsed = 1000.0 * (microtime(TRUE) - $time);
             // Socket didn't timeout; Record round-trip time
             $rtt += $elapsed;
             if ($elapsed > $max) {
                 $max = $elapsed;
             }
             if (!($min > 0) || $elapsed < $min) {
                 $min = $elapsed;
             }
             // Count packets received
             $rcv++;
             if ($host) {
                 $addr = $host;
             }
         }
     }
     socket_close($tsocket);
     socket_close($rsocket);
     return $rcv ? array('host' => $dns ? gethostbyaddr($addr) : $addr, 'min' => (int) round($min), 'max' => (int) round($max), 'avg' => (int) round($rtt / $rcv), 'packets' => $rcv) : FALSE;
 }
Exemplo n.º 13
0
 public function __construct()
 {
     // Send our packet and receive whatever the server has to send back to us.
     if ($socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP)) {
         socket_sendto($socket, $this->packet, strlen($this->packet), 0, $this->ip, $this->port);
         $r = socket_recvfrom($socket, $buf, $this->bufferSize, 0, $this->ip, $this->port);
         // Remove first 23 bytes, we don't need it.
         $this->buffer = array_slice(str_split(bin2hex($buf), 2), 23);
     }
 }
Exemplo n.º 14
0
 public function recvfrom(&$ip)
 {
     $int = @socket_recvfrom($this->socket, $line, 1500, 0, $from, $port);
     if ($int) {
         $ip = $from . ":" . $port;
         return $line;
     } else {
         usleep(1000);
     }
 }
 function listen($callback, $max_packets = 0, $message_types = array())
 {
     set_time_limit(0);
     $current_packet = 1;
     while (socket_recvfrom($this->socket, $buffer, 4096, 0, $host, $port) && (!$max_packets || $current_packet <= $max_packets)) {
         $result = $this->decodePacket($buffer, $host, $port);
         if (!$message_types || in_array($result['message']['type'], $message_types)) {
             call_user_func($callback, $result);
             $current_packet++;
         }
     }
 }
Exemplo n.º 16
0
 /**
  * @todo fix mixed return types!
  * @param integer|null $length
  * @return string|boolean
  */
 public function read(int $length = null)
 {
     $length = $length === null ? $this->bufferLength : $length;
     if (!$length) {
         return false;
     }
     if (!@socket_recvfrom($this->socket, $buffer, $length, MSG_DONTWAIT, $src, $spt)) {
         return false;
     }
     if (!$this->allowBroadcast && ($this->host !== $src || $this->port !== $spt)) {
         return false;
     }
     return $buffer;
 }
Exemplo n.º 17
0
 public function onReadyToReceive()
 {
     print "Something received from UDP\n";
     $datalen = @socket_recvfrom($this->_socket, $data, 1500, 0, $fromip, $fromport);
     while ($datalen > 0) {
         $srvdata = ServerList::getServer($fromip, $fromport);
         if ($srvdata === NULL) {
             print "Received UDP packet from unknown server: {$fromip}:{$fromport}\n";
         } else {
             print "Received UDP packet from {$fromip}:{$fromport}\n";
             $srvdata->touch();
         }
         $datalen = @socket_recvfrom($udpsock, $data, 1500, 0, $fromip, $fromport);
     }
 }
Exemplo n.º 18
0
 /**
  * @return self
  */
 protected function workOnMasterSocket()
 {
     if (@socket_recvfrom($this->masterSocket, $buffer, $this->bufferLength, MSG_DONTWAIT, $src, $spt)) {
         $client = $this->getClientByIpAndPort($src, $spt);
         if (!$client instanceof ServerClient) {
             $client = new ServerClient();
             $client->setHost($src);
             $client->setPort($spt);
             $this->clients[$client->getId()] = $client;
             $this->onConnect($client);
         }
         $client->setAttribute('timeout', microtime(true) + $this->timeoutSeconds + $this->timeoutUSeconds / 1000);
         $this->onIncoming($client, $buffer);
     }
     return $this;
 }
Exemplo n.º 19
0
 public function discover()
 {
     //Send discover packet
     socket_sendto($this->sock, DISCOVER_PACKET, DISCOVER_PACKET_SIZE, 0, '255.255.255.255', SQUEEZECENTER_PORT);
     $quit = false;
     while (!$quit) {
         if (@socket_recvfrom($this->sock, &$buf, 512, 0, &$remote_ip, &$remote_port)) {
             $sc = $this->parsePacket($buf, $remote_ip);
             if ($sc !== false) {
                 $this->servers[] = $sc;
             }
         } else {
             $quit = true;
         }
     }
 }
Exemplo n.º 20
0
 private function smi_read()
 {
     unset($this->hdrs);
     unset($this->body);
     socket_set_option($this->sock, SOL_SOCKET, SO_RCVTIMEO, array("sec" => $this->sto, "usec" => $this->uto));
     $ret = @socket_recvfrom($this->sock, $rcvbuf, BUFFER_SIZE, 0, $faddr, $fport);
     if ($ret < 0) {
         return false;
     }
     $lines = explode("\n", $rcvbuf);
     $this->hdrs[] = $lines[0];
     for ($i = 1; $i < count($lines); $i++) {
         $this->body[] = $lines[$i];
     }
     return true;
 }
Exemplo n.º 21
0
Arquivo: Socket.php Projeto: eix/core
 public function read()
 {
     $data = "";
     // Checks if there is something in the buffer, so a call
     // to read with an empty buffer does not block.
     $bufferLength = @socket_recvfrom($this->socket, $buffer, $this->bufferSize, 2, $this->host, $this->port);
     // If there is, retrieve it.
     if ($bufferLength > 0) {
         socket_recv($this->socket, $data, $bufferLength, 0);
         if ($data === false) {
             Logger::get()->error(socket_strerror(socket_last_error()));
             throw new Exception('Socket read error: ' . socket_strerror(socket_last_error()));
         }
     }
     Logger::get()->debug("[From socket] {$data}");
     return $data;
 }
Exemplo n.º 22
0
 /**
  * 接收数据,UD包不能分2次读,recv后会清除数据包,所以必须要一次性读完
  *
  * @param int $length 接收数据的长度
  * @param bool $waitall 等待接收到全部数据后再返回,注意waitall=true,超过包长度会阻塞住
  */
 function recv($length = 65535, $waitall = 0)
 {
     if ($waitall) {
         $waitall = MSG_WAITALL;
     }
     $ret = socket_recvfrom($this->sock, $data, $length, $waitall, $this->remote_host, $this->remote_port);
     if ($ret === false) {
         $this->set_error();
         //重试一次,这里为防止意外,不使用递归循环
         if ($this->errCode == 4) {
             socket_recvfrom($this->sock, $data, $length, $waitall, $this->remote_host, $this->remote_port);
         } else {
             return false;
         }
     }
     return $data;
 }
Exemplo n.º 23
0
function dhtping()
{
    $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
    //socket_bind($socket, '0.0.0.0', 6881);
    $packet = "d1:ad2:id20:abcdefghij0123456789e1:q4:ping1:t2:aa1:y1:qe";
    //$packet = "{\"t\":\"aa\", \"y\":\"q\", \"q\":\"ping\", \"a\":{\"id\":\"abcdefghij0123456789\"}}";
    $host = "router.bittorrent.com";
    $port = 6881;
    socket_sendto($socket, $packet, strlen($packet), 0, $host, $port);
    try {
        socket_recvfrom($socket, $buf, 12000, 0, $host, $port);
    } catch (Exception $e) {
        echo "";
    }
    socket_close($socket);
    echo $buf;
}
Exemplo n.º 24
0
 protected function init()
 {
     // This sleep should be removed ASAP. It's here because of a bug. Comment
     // out this line, and run your game a couple of times, and you should
     // notice a problem.
     sleep(1);
     $this->running = true;
     // Will be used later for getting the $dt (delta-time)
     $oldTime = microtime(true);
     $drawTime = 0;
     $frameLimit = 1 / 60;
     // Send Config Details
     Game::send_config();
     // Game Loop
     while ($this->running) {
         // Deltatime
         $newTime = microtime(true);
         $dt = $newTime - $oldTime;
         $oldTime = $newTime;
         // Handle Events sent from the client implementation to here
         $data = "";
         $from = "";
         $port = 0;
         socket_recvfrom(self::$sock, $data, 50, 0, $from, $port);
         if ($data) {
             $data = json_decode($data);
             if ($data->e == self::$protocol["keyPressed"]) {
                 $this->key_pressed($data->k);
             }
             if ($data->e == self::$protocol["keyReleased"]) {
                 $this->key_released($data->k);
             }
         }
         // Update
         $this->update($dt);
         // Draw
         $drawTime += $dt;
         if ($drawTime > $frameLimit) {
             // echo "$drawTime\n";
             $this->draw();
             Game::send();
             $drawTime = 0;
         }
         sleep(0.001);
     }
 }
 function listen()
 {
     $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
     socket_bind($socket, '0.0.0.0', 50000);
     while (true) {
         $buf = $from = $port = '';
         if (socket_recvfrom($socket, $buf, 1024, 0, $from, $port)) {
             list($event, $serial, $name) = explode("\n", $buf);
             if ($event == 'RFID' && $name) {
                 $this->doorOpened($serial, $name);
             } elseif ($event == 'RFID' && !$name) {
                 $this->unknownCard($serial);
             } elseif ($event == 'BELL') {
                 $this->doorbell();
             }
         }
     }
 }
Exemplo n.º 26
0
function zkdisconnect($self)
{
    $command = CMD_EXIT;
    $command_string = '';
    $chksum = 0;
    $session_id = $self->session_id;
    $u = unpack('H2h1/H2h2/H2h3/H2h4/H2h5/H2h6/H2h7/H2h8', substr($self->data_recv, 0, 8));
    $reply_id = hexdec($u['h8'] . $u['h7']);
    $buf = $self->createHeader($command, $chksum, $session_id, $reply_id, $command_string);
    socket_sendto($self->zkclient, $buf, strlen($buf), 0, $self->ip, $self->port);
    try {
        socket_recvfrom($self->zkclient, $self->data_recv, 1024, 0, $self->ip, $self->port);
        return $self->checkValid($self->data_recv);
    } catch (ErrorException $e) {
        return FALSE;
    } catch (Exception $e) {
        return FALSE;
    }
}
Exemplo n.º 27
0
function receive_msg($time_out)
{
    $r = 0;
    if (!($sock = socket_create(AF_INET, SOCK_DGRAM, 0))) {
        return array("msg" => "fail to create socket", "ip" => 'none');
    }
    socket_set_option($sock, SOL_SOCKET, SO_RCVTIMEO, array("sec" => $time_out, "usec" => 0));
    $buf = 'M信息接收超时!';
    if (!@socket_bind($sock, "0.0.0.0", 20480)) {
        $r = 2;
        $buf = "a端口绑定失败,请等 10 秒后再试。\n(点拍摄后要等待2分钟)";
    }
    $remote_ip = '无';
    $remote_port = 'null';
    if (!$r) {
        socket_recvfrom($sock, $buf, 1024, 0, $remote_ip, $remote_port);
    }
    socket_close($sock);
    return array("ip" => $remote_ip, "msg" => substr($buf, 1));
}
Exemplo n.º 28
0
 /**
  * Send a command to an haproxy socket.
  *
  * @param string $command 
  *
  * @return string
  */
 private function socketCommand($msg)
 {
     $msg = $msg . "\n";
     // Create the socket
     $socket = @socket_create(AF_UNIX, SOCK_STREAM, 0);
     $sock = @socket_connect($socket, $this->path);
     // Measure the length
     $len = strlen($msg);
     // Send the msg above
     // socket_sendto works on bsd, not linux
     @socket_send($socket, $msg, $len, 0);
     // Accept the response
     if (@socket_recvfrom($socket, $response, 1024000, MSG_WAITALL, $sock)) {
         @socket_shutdown($socket, 0);
         @socket_close($socket);
         return $response;
     } else {
         throw new \RuntimeException("Could not connect to socket.");
     }
     return false;
 }
Exemplo n.º 29
0
function zkpinwidth($self)
{
    $command = CMD_DEVICE;
    $command_string = '~PIN2Width';
    $chksum = 0;
    $session_id = $self->session_id;
    $u = unpack('H2h1/H2h2/H2h3/H2h4/H2h5/H2h6/H2h7/H2h8', substr($self->data_recv, 0, 8));
    $reply_id = hexdec($u['h8'] . $u['h7']);
    $buf = $self->createHeader($command, $chksum, $session_id, $reply_id, $command_string);
    socket_sendto($self->zkclient, $buf, strlen($buf), 0, $self->ip, $self->port);
    try {
        socket_recvfrom($self->zkclient, $self->data_recv, 1024, 0, $self->ip, $self->port);
        $u = unpack('H2h1/H2h2/H2h3/H2h4/H2h5/H2h6', substr($self->data_recv, 0, 8));
        $self->session_id = hexdec($u['h6'] . $u['h5']);
        return substr($self->data_recv, 8);
    } catch (ErrorException $e) {
        return FALSE;
    } catch (exception $e) {
        return False;
    }
}
Exemplo n.º 30
0
function zkgettime($self)
{
    $command = CMD_GET_TIME;
    $command_string = '';
    $chksum = 0;
    $session_id = $self->session_id;
    $u = unpack('H2h1/H2h2/H2h3/H2h4/H2h5/H2h6/H2h7/H2h8', substr($self->data_recv, 0, 8));
    $reply_id = hexdec($u['h8'] . $u['h7']);
    $buf = $self->createHeader($command, $chksum, $session_id, $reply_id, $command_string);
    socket_sendto($self->zkclient, $buf, strlen($buf), 0, $self->ip, $self->port);
    try {
        socket_recvfrom($self->zkclient, $self->data_recv, 1024, 0, $self->ip, $self->port);
        $u = unpack('H2h1/H2h2/H2h3/H2h4/H2h5/H2h6', substr($self->data_recv, 0, 8));
        $self->session_id = hexdec($u['h6'] . $u['h5']);
        return decode_time(hexdec(reverseHex(bin2hex(substr($self->data_recv, 8)))));
    } catch (ErrorException $e) {
        return FALSE;
    } catch (exception $e) {
        return False;
    }
}