Tunnels a connection
@param string $host The host to tunnel to via the ssh2 client
@param integer $port The port to tunnel to via the ssh2 client
@return stream The tunnel stream
559052
public function tunnel($host, $port)
    {
        $stream = @ssh2_tunnel($this->connection, $command);
        if(!$stream){
            throw new \Exception('Cannot create tunnel to: '.$host.' on port'.$port);
        }

        return $stream;
    }
940174
public static function tcp(string $host, array $options = []) : Socket
    {
        return self::create($host, \array_merge($options, ['transport' => 'tcp']));
    }
15272
public function setProxy($host, $port, $type = CURLPROXY_HTTP)
  {
    static $types_str = [
      'HTTP', 'SOCKS4', 'SOCKS5', 'SOCKS4A', 'SOCKS5_HOSTNAME'
    ];
    $types = [];
    foreach ($types_str as $type_str) {
      if (defined('CURLPROXY_' . $type_str)) {
        $types[] = constant('CURLPROXY_' . $type_str);
      }
    }
    if (! in_array($type, $types)) {
      throw new \Exception('Invalid proxy type specified.');
    }

    $this->_proxy['host'] = $host;
    $this->_proxy['port'] = (int) $port;
    $this->_proxy['type'] = $type;
  }
1214465
protected function connect(string $host, int $port): void
    {
        $this->socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

        if (!$this->socket || !@socket_connect($this->socket, $host, $port)) {
            $error = $this->getLastError();
            throw new CommunicationException($error['message'], $error['code']);
        }
    }
797522
public function connect($host, $port, $secure = true)
    {
        $this->socket->setBlocking(false);

        if (!$this->socket->connect($host, $port, $secure)) {
            throw new Exception\ConnectionFailedException(
                sprintf(
                    '%s failed to %s:%d with error %s (%d).',
                    $secure ? 'Secure connection' : 'Connection',
                    $host,
                    $port,
                    $this->socket->connectionError(),
                    $this->socket->connectionErrorNo()
                )
            );
        }
    }
1008132
public function devServer(string $host, int $port)
    {
        // Mark server mode
        define('SERVER_MODE', 'buildin');

        $this->config['host'] = $host;
        $this->config['port'] = $port;

        $this->printServerFinger();

        // Start cli Development Server
        $bind_http = $host . ':' . $port;
        passthru("php -S {$bind_http} -t " . APP_PATH . "/public");
    }
1027451
public static function create($host, $port)
  {
    $transceiver = new SocketTransceiver();
    $transceiver->createSocket($host, $port);
    
    return $transceiver;
  }
317037
public static function connect(string $host, int $port = 119, array $options = []): Generator
    {
        // Connect to the remote host.
        $socket = yield from Dns\connect($host, $port, $options);

        // Encoder for encoding and decoding the protocol.
        $encoder = new Rfc3977Encoder();

        // Create the client object.
        $client = new static($socket, $encoder);

        // The server should respond with a welcome message.
        $response = yield from $encoder->readResponse($socket);

        // A 201 response code means posting is not allowed.
        if ($response->code() === 201) {
            $client->postingAllowed = false;
        }

        // Get the server capabilities.
        yield from $client->getServerCapabilities();

        // Set reader client mode if necessary.
        if ($client->hasCapability('MODE-READER') || !$client->hasCapability('READER')) {
            yield from $client->sendCommand(new Command('MODE READER'));
        }

        // Enable encryption if supported.
        if ($client->hasCapability('STARTTLS')) {
            yield from $client->sendCommand(new Command('STARTTLS'));
            yield from $socket->enableCrypto(STREAM_CRYPTO_METHOD_ANY_CLIENT);
        }

        return $client;
    }
1033734
public function create($host = '', $port = '')
    {
        $this->host = ($host != '') ? $host : 'localhost';
        $this->port = ($port != '') ? $port : 11211;

        if (is_null($this->memory)) {
            $this->memory = new \Memcache();
            $this->isEnabled = true;

            if (!$this->memory->connect($this->host, $this->port)) { // Instead 'localhost' here can be IP
                $this->memory = null;
                $this->isEnabled = true;
            }
        }

        return $this;
    }
584105
public function setProxy($host = null, $port = null)
    {
        $this->downloader->setProxy($host, $port);
    }
471355
public function connect($host, $port = 80, $secure = false)
    {
        // If no proxy is set, fall back to Socket adapter
        if (!$this->config['proxy_host']) {
            return parent::connect($host, $port, $secure);
        }

        /* Url might require stream context even if proxy connection doesn't */
        if ($secure) {
            $this->config['sslusecontext'] = true;
        }

        // Connect (a non-secure connection) to the proxy server
        return parent::connect(
            $this->config['proxy_host'],
            $this->config['proxy_port'],
            false
        );
    }
496231
public function connect($host = '127.0.0.1', $port = 21)
	{
		$errno = null;
		$err   = null;

		// If already connected, return
		if (\is_resource($this->conn))
		{
			return true;
		}

		// If native FTP support is enabled let's use it...
		if (FTP_NATIVE)
		{
			$this->conn = @ftp_connect($host, $port, $this->timeout);

			if ($this->conn === false)
			{
				throw new FilesystemException(sprintf('%1$s: Could not connect to host " %2$s " on port " %3$s "', __METHOD__, $host, $port));
			}

			// Set the timeout for this connection
			ftp_set_option($this->conn, FTP_TIMEOUT_SEC, $this->timeout);

			return true;
		}

		// Connect to the FTP server.
		$this->conn = @ fsockopen($host, $port, $errno, $err, $this->timeout);

		if (!$this->conn)
		{
			throw new FilesystemException(
				sprintf(
					'%1$s: Could not connect to host " %2$s " on port " %3$s ". Socket error number: %4$s and error message: %5$s',
					__METHOD__,
					$host,
					$port,
					$errno,
					$err
				)
			);
		}

		// Set the timeout for this connection
		socket_set_timeout($this->conn, $this->timeout, 0);

		// Check for welcome response code
		if (!$this->_verifyResponse(220))
		{
			throw new FilesystemException(sprintf('%1$s: Bad response. Server response: %2$s [Expected: 220]', __METHOD__, $this->response));
		}

		return true;
	}
176150
public static function getFreePort($from, $host = 'localhost')
    {
        $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
        $ret = $from;
        while (true) {
            if (@socket_bind($socket, $host, $ret)) {
                break;
            }
            $ret++;
            if ($ret > $from+100) {
                $this->fail('can\'t get free port number');
            }
        }
        socket_close($socket);
        return $ret;
    }
723714
protected function checkConnection($host, $port)
    {
        $host = ($port == 443) ? 'ssl://' . $host : 'tcp://' . $host;

        // If the connection could not be established, fsockopen sadly does not
        // only return false (as documented), but also always issues a warning.
        if (($this->connection === null) &&
            (($this->connection = @stream_socket_client($host . ':' . $port, $errno, $errstr)) === false)) {
            // This is a bit hackisch...
            $this->connection = null;
            throw new \RuntimeException('fail');
        }
    }
947434
public function tunnel($configuration)
    {
        $configurationData = explode(':', $configuration);

        if (count($configurationData) == 4) {
            list($localIp, $localPort, $remoteHost, $remotePort) = $configurationData;

            if (empty($localIp)) {
                throw new \InvalidArgumentException('Invalid local host');
            }
        } else {
            list($localPort, $remoteHost, $remotePort) = $configurationData;
        }

        if (!ctype_digit($localPort)) {
            throw new \InvalidArgumentException('Invalid local port');
        }
        if (empty($remoteHost)) {
            throw new \InvalidArgumentException('Invalid remote host');
        }
        if (!ctype_digit($remotePort)) {
            throw new \InvalidArgumentException('Invalid remote port');
        }

        $descriptorSpec = [0 => STDIN, 1 => STDOUT, 2 => STDERR];
        $pipes = [];
        $command = $this->__toString() . ' -L ' . $configuration . ' -N';
        $process = proc_open($command, $descriptorSpec, $pipes);
        if (is_resource($process)) {
            proc_close($process);
        }
    }
1373593
public function connectUdp($host, $port)
    {
        $this->type = 'udp';
        $pton = @inet_pton($host);
        if ($pton === false) { // dirty check
            \PHPDaemon\Clients\DNS\Pool::getInstance()->resolve($host, function ($result) use ($host, $port) {
                if (!$result) {
                    Daemon::log(get_class($this) . '->connectUdp : unable to resolve hostname: ' . $host);
                    $this->onStateEv($this->bev, \EventBufferEvent::ERROR);
                    return;
                }
                // @todo stack of addrs
                if (is_array($result)) {
                    srand(Daemon::$process->getPid());
                    $real = $result[rand(0, sizeof($result) - 1)];
                    srand();
                } else {
                    $real = $result;
                }
                $this->connectUdp($real, $port);
            });
            return true;
        }
        $this->hostReal = $host;
        if ($this->host === null) {
            $this->host = $this->hostReal;
        }
        $l = mb_orig_strlen($pton);
        if ($l === 4) {
            $this->addr = $host . ':' . $port;
            /* @TODO: use EventUtil::SOCK_DGRAM */
            $fd = socket_create(\EventUtil::AF_INET, SOCK_DGRAM, \EventUtil::SOL_UDP);
        } elseif ($l === 16) {
            $this->addr = '[' . $host . ']:' . $port;
            $fd = socket_create(\EventUtil::AF_INET6, SOCK_DGRAM, \EventUtil::SOL_UDP);
        } else {
            return false;
        }
        if (!$fd) {
            return false;
        }
        socket_set_nonblock($fd);
        @socket_connect($fd, $host, $port);
        socket_getsockname($fd, $this->locAddr, $this->locPort);
        $this->setFd($fd);
        if (!$this->bev) {
            return false;
        }
        return true;
    }
403643
public function useProxy($host, $port, $username = null, $password = null) {
    $this->proxy_host = $host;
    $this->proxy_port = $port;
    $this->proxy_username = $username;
    $this->proxy_password = $password;
  }