function http_request($host, $data) { if (!($socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) { echo "socket_create() error!\r\n"; exit; } if (!socket_set_option($socket, SOL_SOCKET, SO_BROADCAST, 1)) { echo "socket_set_option() error!\r\n"; exit; } if (!socket_connect($socket, $host, 80)) { echo "socket_connect() error!\r\n"; exit; } if (!socket_write($socket, $data, strlen($data))) { echo "socket_write() errror!\r\n"; exit; } while ($get = socket_read($socket, 1024, PHP_NORMAL_READ)) { $content .= $get; } socket_close($socket); $array = array('HTTP/1.1 404 Not Found', 'HTTP/1.1 300 Multiple Choices', 'HTTP/1.1 301 Moved Permanently', 'HTTP/1.1 302 Found', 'HTTP/1.1 304 Not Modified', 'HTTP/1.1 400 Bad Request', 'HTTP/1.1 401 Unauthorized', 'HTTP/1.1 402 Payment Required', 'HTTP/1.1 403 Forbidden', 'HTTP/1.1 405 Method Not Allowed', 'HTTP/1.1 406 Not Acceptable', 'HTTP/1.1 407 Proxy Authentication Required', 'HTTP/1.1 408 Request Timeout', 'HTTP/1.1 409 Conflict', 'HTTP/1.1 410 Gone', 'HTTP/1.1 411 Length Required', 'HTTP/1.1 412 Precondition Failed', 'HTTP/1.1 413 Request Entity Too Large', 'HTTP/1.1 414 Request-URI Too Long', 'HTTP/1.1 415 Unsupported Media Type', 'HTTP/1.1 416 Request Range Not Satisfiable', 'HTTP/1.1 417 Expectation Failed', 'HTTP/1.1 Retry With'); for ($i = 0; $i <= count($array); $i++) { if (eregi($array[$i], $content)) { return "{$array[$i]}\r\n"; break; } else { return "{$content}\r\n"; break; } } }
/** * {@inheritdoc} */ public function flushAll() { if ($this->currentOnly) { return apc_clear_cache('user') && apc_clear_cache(); } $result = true; foreach ($this->servers as $server) { if (count(explode('.', $server['ip'])) == 3) { $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); } else { $socket = socket_create(AF_INET6, SOCK_STREAM, SOL_TCP); } // generate the raw http request $command = sprintf("GET %s HTTP/1.1\r\n", $this->getUrl()); $command .= sprintf("Host: %s\r\n", $server['domain']); if ($server['basic']) { $command .= sprintf("Authorization: Basic %s\r\n", $server['basic']); } $command .= "Connection: Close\r\n\r\n"; // setup the default timeout (avoid max execution time) socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 2, 'usec' => 0)); socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => 2, 'usec' => 0)); socket_connect($socket, $server['ip'], $server['port']); socket_write($socket, $command); $content = ''; do { $buffer = socket_read($socket, 1024); $content .= $buffer; } while (!empty($buffer)); if ($result) { $result = substr($content, -2) == 'ok'; } } return $result; }
function wol($host, $mac) { //get the broadcast addr $range = $this->iprange($host, 24); $broadcast = $range['last_ip']; $mac_array = explode(':', $mac); $hwaddr = ''; foreach ($mac_array as $octet) { $hwaddr .= chr(hexdec($octet)); } // Create Magic Packet $packet = ''; for ($i = 1; $i <= 6; $i++) { $packet .= chr(255); } for ($i = 1; $i <= 16; $i++) { $packet .= $hwaddr; } $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); if ($sock) { $options = socket_set_option($sock, 1, 6, true); if ($options >= 0) { $e = socket_sendto($sock, $packet, strlen($packet), 0, $broadcast, 9); socket_close($sock); } } }
function __construct($options) { $this->reset($options); pcntl_signal(SIGTERM, array("JAXLHTTPd", "shutdown")); pcntl_signal(SIGINT, array("JAXLHTTPd", "shutdown")); $options = getopt("p:b:"); foreach ($options as $opt => $val) { switch ($opt) { case 'p': $this->settings['port'] = $val; break; case 'b': $this->settings['maxq'] = $val; default: break; } } $this->httpd = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_set_option($this->httpd, SOL_SOCKET, SO_REUSEADDR, 1); socket_bind($this->httpd, 0, $this->settings['port']); socket_listen($this->httpd, $this->settings['maxq']); $this->id = $this->getResourceID($this->httpd); $this->clients = array("0#" . $this->settings['port'] => $this->httpd); echo "JAXLHTTPd listening on port " . $this->settings['port'] . PHP_EOL; }
public function flushAll() { $result = true; foreach ($this->servers as $server) { if (count(explode('.', $server['ip']) == 3)) { $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); } else { $socket = socket_create(AF_INET6, SOCK_STREAM, SOL_TCP); } // generate the raw http request $command = sprintf("GET %s HTTP/1.1\r\n", $this->router->generate('sonata_page_apc_cache', array('token' => $this->token))); $command .= sprintf("Host: %s\r\n", $server['domain']); $command .= "Connection: Close\r\n\r\n"; // setup the default timeout (avoid max execution time) socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 2, 'usec' => 0)); socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => 2, 'usec' => 0)); socket_connect($socket, $server['ip'], $server['port']); socket_write($socket, $command); $content = socket_read($socket, 1024); if ($result) { $result = substr($content, -2) == 'ok' ? true : false; } } return $result; }
public function __construct($host, $port) { $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_connect($this->socket, $host, $port); socket_set_option($this->socket, SOL_TCP, 1, 1); //socket_set_option ( $this->socket, SOL_TCP, SO_SNDBUF, 1024 * 1024 ); }
private function _openConnection($debug = null) { $connection = false; if (function_exists('socket_create') && function_exists('socket_connect') && function_exists('socket_strerror') && function_exists('socket_last_error') && function_exists('socket_set_block') && function_exists('socket_read') && function_exists('socket_write') && function_exists('socket_close')) { $this->_sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if (function_exists('socket_set_option')) { socket_set_option($this->_sock, SOL_SOCKET, SO_RCVTIMEO, ['sec' => 5, 'usec' => 0]); socket_set_option($this->_sock, SOL_SOCKET, SO_SNDTIMEO, ['sec' => 5, 'usec' => 0]); } @($connection = socket_connect($this->_sock, $this->_serverIP, $this->_serverRconQueryPort)); if ($debug == '-d') { echo '[DEBUG]: ' . socket_strerror(socket_last_error()) . ".\n"; } if ($connection) { socket_set_block($this->_sock); } $this->_sockType = 1; } else { if (function_exists('fsockopen')) { if ($debug == '-d') { @($this->_sock = fsockopen('tcp://' . $this->_serverIP, $this->_serverRconQueryPort, $errno, $errstr, 10)); if (!$this->_sock) { echo '[DEBUG]: ' . $errno . ' - ' . $errstr . "\n"; } } else { @($this->_sock = fsockopen('tcp://' . $this->_serverIP, $this->_serverRconQueryPort)); } $connection = $this->_sock; $this->_sockType = 2; } } return $connection; }
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; } } } } }
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; }
/** * Gets the OrientSocket, and establishes the connection if required. * * @return \PhpOrient\Protocols\Binary\OrientSocket * * @throws SocketException * @throws PhpOrientWrongProtocolVersionException */ public function connect() { if (!$this->connected) { if (empty($this->hostname) && empty($this->port)) { throw new SocketException('Can not initialize a connection ' . 'without connection parameters'); } if (!extension_loaded("sockets")) { throw new SocketException('Can not initialize a connection ' . 'without socket extension enabled. Please check you php.ini'); } $this->_socket = @socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp')); socket_set_block($this->_socket); socket_set_option($this->_socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => self::READ_TIMEOUT, 'usec' => 0)); socket_set_option($this->_socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => self::WRITE_TIMEOUT, 'usec' => 0)); $x = @socket_connect($this->_socket, $this->hostname, $this->port); if (!is_resource($this->_socket) || $x === false) { throw new SocketException($this->getErr() . PHP_EOL); } $protocol = Reader::unpackShort($this->read(2)); if ($protocol > $this->protocolVersion) { throw new PhpOrientWrongProtocolVersionException('Protocol version ' . $protocol . ' is not supported.'); } //protocol handshake $this->protocolVersion = $protocol; $this->connected = true; } return $this; }
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."; } } }
public function commit($intLogID, $strQueueName, $strOperation, $arrOperationBody) { if ($this->_check_conntect()) { $sendArray = array(); $sendArray['__QUEUE_NAME__'] = $strQueueName; $sendArray['__OPERATION__'] = $strOperation; $sendArray['__OPERATION_BODY__'] = $arrOperationBody; $jsonstr = json_encode($sendArray); $FORMAT_XHEAD = "Ilogid/a16hiname/Iversion/Ireserved/Idetail_len"; $binaryData = pack("Ia16III", $intLogID, "ccphp", 0, 0, strlen($jsonstr)); $binaryData .= $jsonstr; // var_dump(unpack($FORMAT_XHEAD, $binaryData)); socket_set_option($this->m_sock, SOL_SOCKET, SO_RCVTIMEO, array("sec" => 1, "usec" => 0)); socket_set_option($this->m_sock, SOL_SOCKET, SO_SNDTIMEO, array("sec" => 1, "usec" => 0)); socket_write($this->m_sock, $binaryData); $rstr = socket_read($this->m_sock, 32); if (32 != strlen($rstr)) { $len = strlen($rstr); Clogger::warning("socket_read error len: " . $len . " queuename: " . $strQueueName . " operation: " . $strOperation); return FALSE; } $retArray = unpack($FORMAT_XHEAD, $rstr); Clogger::notice("ciqueue queuename: " . $strQueueName . " operation: " . $strOperation . " response: " . json_encode($retArray)); // var_dump($retArray); return $retArray["reserved"] == 0; } else { Clogger::warning("connect error queuename: " . $strQueueName . " operation: " . $strOperation); return FALSE; } }
public function wake($mac, $ip) { global $l; //looking for values of wol config $wol_info = look_config_default_values('WOL_PORT'); if (!isset($wol_info['name']['WOL_PORT'])) { $this->wol_send = $l->g(1321); } else { $wol_port = explode(',', $wol_info['tvalue']['WOL_PORT']); } foreach ($wol_port as $k => $v) { if (is_numeric($v)) { $s = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); if (!$s) { @socket_close($s); $this->wol_send = $l->g(1322); } else { $s_opt = socket_set_option($s, SOL_SOCKET, SO_BROADCAST, true); socket_sendto($s, $this->pacquet($mac), strlen($this->pacquet($mac)), 0, "255.255.255.255", $v); socket_close($s); $this->wol_send = $l->g(1282); } } } // $this->wol_send='toto'; //return $wol_send; }
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); }
/** * Initializes a TCP stream resource. * * @param ParametersInterface $parameters Initialization parameters for the connection. * * @return resource */ protected function tcpStreamInitializer(ParametersInterface $parameters) { $uri = "tcp://{$parameters->host}:{$parameters->port}"; $flags = STREAM_CLIENT_CONNECT; if (isset($parameters->async_connect) && (bool) $parameters->async_connect) { $flags |= STREAM_CLIENT_ASYNC_CONNECT; } if (isset($parameters->persistent) && (bool) $parameters->persistent) { $flags |= STREAM_CLIENT_PERSISTENT; $uri .= strpos($path = $parameters->path, '/') === 0 ? $path : "/{$path}"; } $resource = @stream_socket_client($uri, $errno, $errstr, (double) $parameters->timeout, $flags); if (!$resource) { $this->onConnectionError(trim($errstr), $errno); } if (isset($parameters->read_write_timeout)) { $rwtimeout = (double) $parameters->read_write_timeout; $rwtimeout = $rwtimeout > 0 ? $rwtimeout : -1; $timeoutSeconds = floor($rwtimeout); $timeoutUSeconds = ($rwtimeout - $timeoutSeconds) * 1000000; stream_set_timeout($resource, $timeoutSeconds, $timeoutUSeconds); } if (isset($parameters->tcp_nodelay) && function_exists('socket_import_stream')) { $socket = socket_import_stream($resource); socket_set_option($socket, SOL_TCP, TCP_NODELAY, (int) $parameters->tcp_nodelay); } return $resource; }
public function init() { if ($this->initialized) { return NULL; } $this->socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($this->socket === false) { $this->setError($this->getSocketError("Failed creating socket"), LOG_ERR); return false; } if (!socket_set_option($this->socket, SOL_SOCKET, SO_REUSEADDR, 1)) { $this->setError($this->getSocketError("Failed setting SO_REUSEADDR on socket"), LOG_ERR); return false; } if (!@socket_bind($this->socket, $this->server_address, $this->server_port)) { $this->setError($this->getSocketError("Failed binding socket to " . $this->server_address . ":" . $this->server_port), LOG_ERR); return false; } if (!@socket_listen($this->socket, 5)) { $this->setError($this->getSocketError("Failed starting to listen on socket"), LOG_ERR); return false; } socket_set_nonblock($this->socket); return $this->initialized = true; }
function SetOptions() { socket_set_option($this->Socket, SOL_SOCKET, SO_KEEPALIVE, 0); socket_set_option($this->Socket, SOL_SOCKET, SO_REUSEADDR, 1); socket_set_timeout($this->Socket, 2); socket_set_nonblock($this->Socket); }
/** * Waits for incoming connections. */ public function connect(array $connections, $options) { $dummy = array(); $connections[] = $this->sock; $ready = @socket_select($connections, $dummy, $dummy, $options['poll_interval']); if ($ready === false) { throw new StupidHttp_NetworkException("Failed to monitor incoming connections."); } if ($ready == 0) { return null; } // Check for a new connection. $i = array_search($this->sock, $connections); if ($i !== false) { // Remove our socket from the connections and replace it // with the file-descriptor for the new client. unset($connections[$i]); if (($msgsock = @socket_accept($this->sock)) === false) { throw new StupidHttp_NetworkException("Failed accepting connection: " . socket_strerror(socket_last_error($this->sock))); } if (@socket_set_option($msgsock, SOL_SOCKET, SO_REUSEADDR, 1) === false) { throw new StupidHttp_NetworkException("Failed setting address re-use option: " . socket_strerror(socket_last_error($msgsock))); } $timeout = array('sec' => $options['timeout'], 'usec' => 0); if (@socket_set_option($msgsock, SOL_SOCKET, SO_RCVTIMEO, $timeout) === false) { throw new StupidHttp_NetworkException("Failed setting timeout value: " . socket_strerror(socket_last_error($msgsock))); } $connections[] = $msgsock; } return $connections; }
public function create() { $socket = null; if (($socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) < 0) { $errno = socket_last_error(); throw new RuntimeException('socket_create: ' . socket_strerror($errno), $errno); } $ret = socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 1); $ret = socket_get_option($socket, SOL_SOCKET, SO_KEEPALIVE); if ($ret === false) { $errno = socket_last_error($socket); throw new RuntimeException('socket_get_option SO_KEEPALIVE: ' . socket_strerror($errno), $errno); } $ret = socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1); $ret = socket_get_option($socket, SOL_SOCKET, SO_REUSEADDR); if ($ret === false) { $errno = socket_last_error($socket); throw new RuntimeException('socket_get_option SO_REUSEADDR: ' . socket_strerror($errno), $errno); } $ret = socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => 5, 'usec' => 0)); $ret = socket_get_option($socket, SOL_SOCKET, SO_RCVTIMEO); if ($ret === false) { $errno = socket_last_error($socket); throw new RuntimeException('socket_get_option SO_RCVTIMEO: ' . socket_strerror($errno), $errno); } $ret = socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 5, 'usec' => 0)); $ret = socket_get_option($socket, SOL_SOCKET, SO_SNDTIMEO); if ($ret === false) { $errno = socket_last_error($socket); throw new RuntimeException('socket_get_option SO_SNDTIMEO: ' . socket_strerror($errno), $errno); } socket_set_nonblock($socket); return $socket; }
public function send($data) { $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($socket == null) { return false; } socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => $this->timeout, 'usec' => 0)); if (!socket_connect($socket, $this->host, $this->port)) { return false; } $packed = json_encode($data); echo $packed; //Write Header socket_write($socket, "ZBXD"); //Write Data length $length = strlen($packed); socket_write($socket, pack("V*", $length, $length >> 32)); socket_write($socket, $packed); $return_header = socket_read($socket, 5); $return_length = unpack("V*", socket_read($socket, 8)); $return_length = $return_length[1] + ($return_length[2] << 32); $return_data = socket_read($socket, $return_length); $return_data = json_decode($return_data); socket_close($socket); return $return_data; }
/** * Começa a escutar conexões e processar as demais funcionalidades * @param int $port número da porta * @throws EndPointException */ public function listen($port) { $this->port = $port; /* @var resource cria o socket que escutará conexões */ $this->serverSocket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('TCP')); if (!socket_set_option($this->serverSocket, SOL_SOCKET, SO_REUSEADDR, 1)) { echo socket_strerror(socket_last_error($this->serverSocket)); exit; } /* seta o host e a porta */ if (!@socket_bind($this->serverSocket, 0, $this->port)) { throw new EndPointException("socket_bind() falhou: resposta: " . socket_strerror(socket_last_error($this->serverSocket))); } /* inicia a escuta de conexões */ if (!@socket_listen($this->serverSocket)) { throw new EndPointException("socket_listen() falhou: resposta: " . socket_strerror(socket_last_error($this->serverSocket))); } /* cria um array de sockets e adiciona o serverSocket no array */ $this->sockets = array($this->serverSocket); $this->loopPrincipal(); /* Fecha todos os sockets e encerra a aplicação */ foreach ($this->sockets as $socket) { if (get_resource_type($socket) == "Socket") { socket_close($socket); } } }
public function __construct($host, $port) { $ipAddr = self::DEFAULT_IPADDR; if (false === ip2long($host)) { $ipAddr = gethostbyname($host); } else { $ipAddr = $host; } $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if (false === $socket) { throw new PhpBuf_RPC_Socket_Exception('socket creation fail:' . socket_strerror(socket_last_error())); } $connected = socket_connect($socket, $ipAddr, $port); if (false === $connected) { throw new PhpBuf_RPC_Socket_Exception('socket connection fail:' . socket_strerror(socket_last_error())); } socket_set_nonblock($socket); // socket_set_timeout($socket, 5); socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, array('sec' => 5, 'usec' => 0)); socket_set_option($socket, SOL_SOCKET, SO_LINGER, array('l_onoff' => 1, 'l_linger' => 1)); socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1); socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 1); if (defined('TCP_NODELAY')) { socket_set_option($socket, SOL_SOCKET, TCP_NODELAY, 1); } $this->socket = $socket; }
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)); }
public function createReceiver($address) { if (!defined('MCAST_JOIN_GROUP')) { throw new BadMethodCallException('MCAST_JOIN_GROUP not defined (requires PHP 5.4+)'); } if (!function_exists('socket_import_stream')) { throw new BadMethodCallException('Function socket_import_stream missing (requires ext-sockets and PHP 5.4+)'); } $parts = parse_url('udp://' . $address); $stream = @stream_socket_server('udp://0.0.0.0:' . $parts['port'], $errno, $errstr, STREAM_SERVER_BIND); if ($stream === false) { throw new RuntimeException('Unable to create receiving socket: ' . $errstr, $errno); } $socket = socket_import_stream($stream); if ($stream === false) { throw new RuntimeException('Unable to access underlying socket resource'); } // allow multiple processes to bind to the same address $ret = socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1); if ($ret === false) { throw new RuntimeException('Unable to enable SO_REUSEADDR'); } // join multicast group and bind to port $ret = socket_set_option($socket, IPPROTO_IP, MCAST_JOIN_GROUP, array('group' => $parts['host'], 'interface' => 0)); if ($ret === false) { throw new RuntimeException('Unable to join multicast group'); } return new DatagramSocket($this->loop, $stream); }
static function send($broadcast, $mac) { $mac_array = split(':', $mac); $hwaddr = ''; foreach ($mac_array as $octet) { $hwaddr .= chr(hexdec($octet)); } // Create Magic Packet $packet = ''; for ($i = 1; $i <= 6; $i++) { $packet .= chr(255); } for ($i = 1; $i <= 16; $i++) { $packet .= $hwaddr; } $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); if ($sock) { $options = socket_set_option($sock, 1, 6, true); if ($options >= 0) { echo "sended"; $e = socket_sendto($sock, $packet, strlen($packet), 0, $broadcast, 7); socket_close($sock); } } }
/** * 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; }
public function listen($port, $host = '127.0.0.1', $protocol = 'tcp') { if (strpos($host, ':') !== false) { // enclose IPv6 addresses in square brackets before appending port $host = '[' . $host . ']'; } $opts = ['socket' => ['backlog' => 1024, 'so_reuseport' => 1]]; $flags = $protocol == 'udp' ? STREAM_SERVER_BIND : STREAM_SERVER_BIND | STREAM_SERVER_LISTEN; $context = stream_context_create($opts); $this->master = @stream_socket_server("{$protocol}://{$host}:{$port}", $errorCode, $errorMessage, $flags, $context); if (false === $this->master) { $message = "Could not bind to tcp://{$host}:{$port}: {$errorMessage}"; throw new ConnectionException($message, $errorCode); } // Try to open keep alive for tcp and disable Nagle algorithm. if (function_exists('socket_import_stream') && $protocol == 'tcp') { $socket = socket_import_stream($this->master); @socket_set_option($socket, SOL_SOCKET, SO_KEEPALIVE, 1); @socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1); } stream_set_blocking($this->master, 0); $this->loop->addReadStream($this->master, function ($master) { $newSocket = stream_socket_accept($master, 0, $remote_address); if (false === $newSocket) { $this->notifyError(new \RuntimeException('Error accepting new connection')); return; } $this->handleConnection($newSocket); }); return $this; }
function __construct($host, $port, $root_pw = false) { ob_start(); $this->admin_id = false; $this->host = $host; $this->port = $port; if ($root_pw === false) { $this->root_pw = uniqid(); } else { $this->root_pw = $root_pw; } $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1); if (!is_resource($socket)) { $this->console("socket_create() failed: " . socket_strerror(socket_last_error()), true); exit; } if (!socket_bind($socket, $this->host, $this->port)) { $this->console("socket_bind() failed: " . socket_strerror(socket_last_error()), true); exit; } if (!socket_listen($socket, 20)) { $this->console("socket_listen() failed: " . socket_strerror(socket_last_error()), true); exit; } $this->master = $socket; $this->sockets = array($socket); $this->mem = new Memcached(); $this->mem->addServer('127.0.0.1', 11211, 1); $this->mem->set('notification-stack', array()); }
function Ping($dst_addr, $timeout = 5, $percision = 3) { // lets catch dumb people if ((int) $timeout <= 0) { $timeout = 5; } if ((int) $percision <= 0) { $percision = 3; } // set the timeout socket_set_option($this->icmp_socket, SOL_SOCKET, SO_RCVTIMEO, array("sec" => $timeout, "usec" => 0)); if ($dst_addr) { if (@socket_connect($this->icmp_socket, $dst_addr, NULL)) { } else { $this->errstr = "Cannot connect to {$dst_addr}"; return FALSE; } $this->Build_Packet(); $this->start_time(); socket_write($this->icmp_socket, $this->request, $this->request_len); if (@socket_recv($this->icmp_socket, &$this->reply, 256, 0)) { $this->time = $this->get_time($percision); return $this->time; } else { $this->errstr = "Timed out"; return FALSE; } } else { $this->errstr = "Destination address not specified"; return FALSE; } }
public function __construct($addr, $port, $bufferLength = 2048) { $this->maxBufferSize = $bufferLength; try { $this->master = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); } catch (Exception $e) { $this->stdout($e . 'Failed: socket_create()'); } try { socket_set_option($this->master, SOL_SOCKET, SO_REUSEADDR, 1); } catch (Exception $e) { $this->stdout($e . 'Failed: socket_option()'); } try { socket_bind($this->master, $addr, $port); } catch (Exception $e) { $this->stdout($e . 'Failed: socket_bind()'); } try { socket_listen($this->master, 20); } catch (Exception $e) { $this->stdout($e . 'Failed: socket_listen()'); } $this->sockets['m'] = $this->master; $this->stdout("Server started\nListening on: {$addr}:{$port}\nMaster socket: " . $this->master); }