The fsockopen method simply tries to reach the host on a port. This method
is often the fastest, but not necessarily the most reliable. Even if a host
doesn't respond, fsockopen may still make a connection.

@return int
Latency, in ms.
518947
private function pingFsockopen() {
        $start = microtime(true);

        if (strtolower($this->typeCon) != 'tcp') {
            $this->setPort(7);
            $this->setHost("udp://$this->host");
        }

        // fsockopen prints a bunch of errors if a host is unreachable. Hide those
        // irrelevant errors and deal with the results instead.
        $fp = @fsockopen($this->host, $this->port, $errno, $errstr, $this->timeout);
        if (!$fp) {
            $latency = false;
        } else {
            $latency = microtime(true) - $start;
            $latency = round($latency * 1000);
        }
        return $latency;
    }
1369050
public function postBatch()
    {
        $fp = fsockopen($this->hostname, $this->port, $errno, $errstr, 30);

        if (FALSE === $fp) {
            throw new \RuntimeException($errstr, $errno);
        }

        for ($i = 0, $c = count($this->buffer); $i < $c; $i++) {

            $message = $this->buffer[$i];

            $request = "POST /inputs/" . $this->input->getKey() . " HTTP/1.1\r\n";
            $request .= "Host: " . ClientInterface::LOGGLY_HOST . "\r\n";
            $request .= "User-Agent: " . ClientInterface::USER_AGENT . "\r\n";
            $request .= "Content-Type: " . $this->getContentType() . "\r\n";
            $request .= "Content-Length: " . strlen($message) . "\r\n";

            // Add Connection: Close header on the last request.
            $request .= $i === $c - 1 ? "Connection: Close\r\n\r\n" : "\r\n";

            $request .= $message;
            $request .= $i === $c - 1 ? "" : "\r\n";

            fwrite($fp, $request);
        }

        fclose($fp);

        return TRUE;
    }
916397
public function getServerPort()
    {
        return isset($this->swooleRequest->server['SERVER_PORT']) ? (int) $this->swooleRequest->server['SERVER_PORT'] : null;
    }
27473
public static function getHost() : string
  {
      // Check for proxy first
      $host = isset($_SERVER['HTTP_X_FORWARDED_HOST']) ?
          last(explode(',', $_SERVER['HTTP_X_FORWARDED_HOST'])) : 
          $_SERVER['HTTP_HOST'] ?? 
          $_SERVER['HTTP_SERVER_NAME'] ?? 
          $_SERVER['HTTP_SERVER_ADDR'];

      // trim and remove port number from host
      // host is lowercase as per RFC 952/2181
      return strtolower(preg_replace('/:\d+$/', '', trim($host)));
  }
771726
public function fsockopen($hostname, $port = -1, &$errno = 0, &$errstr = '', $timeout = null)
    {
        $this->handle = fsockopen($hostname, $port, $errno, $errstr, (is_null($timeout) ? ini_get("default_socket_timeout") : $timeout));

        if ($this->handle != false && $errno === 0 && $errstr === '') {
            return $this->handle;
        }
        return false;
    }
32035
public function getConnection()
    {
        if ($this->connection) {
            return $this->connection;
        }

        return $this->connection = new SFTP($this->host, $this->port, $this->timeout);
    }
1271514
public function checkFsockopen()
    {
        $result = 1;
        $iErrNo = 0;
        $sErrStr = '';
        if ($oRes = @fsockopen('www.example.com', 80, $iErrNo, $sErrStr, 10)) {
            $result = 2;
            fclose($oRes);
        }
        return $result;
    }
1164152
function _connect()
    {
        if ($this->bitmap & NET_SSH2_MASK_CONSTRUCTOR) {
            return false;
        }

        $this->bitmap |= NET_SSH2_MASK_CONSTRUCTOR;

        $this->curTimeout = $this->timeout;

        $this->last_packet = strtok(microtime(), ' ') + strtok(''); // == microtime(true) in PHP5

        if (!is_resource($this->fsock)) {
            $start = strtok(microtime(), ' ') + strtok(''); // http://php.net/microtime#61838
            // with stream_select a timeout of 0 means that no timeout takes place;
            // with fsockopen a timeout of 0 means that you instantly timeout
            // to resolve this incompatibility a timeout of 100,000 will be used for fsockopen if timeout is 0
            $this->fsock = @fsockopen($this->host, $this->port, $errno, $errstr, $this->curTimeout == 0 ? 100000 : $this->curTimeout);
            if (!$this->fsock) {
                $host = $this->host . ':' . $this->port;
                user_error(rtrim("Cannot connect to $host. Error $errno. $errstr"));
                return false;
            }
            $elapsed = strtok(microtime(), ' ') + strtok('') - $start;

            $this->curTimeout-= $elapsed;

            if ($this->curTimeout <= 0) {
                $this->is_timeout = true;
                return false;
            }
        }

        $this->identifier = $this->_generate_identifier();

        fputs($this->fsock, $this->identifier . "\r\n");

        /* According to the SSH2 specs,

          "The server MAY send other lines of data before sending the version
           string.  Each line SHOULD be terminated by a Carriage Return and Line
           Feed.  Such lines MUST NOT begin with "SSH-", and SHOULD be encoded
           in ISO-10646 UTF-8 [RFC3629] (language is not specified).  Clients
           MUST be able to process such lines." */
        $temp = '';
        $extra = '';
        while (!feof($this->fsock) && !preg_match('#^SSH-(\d\.\d+)#', $temp, $matches)) {
            if (substr($temp, -2) == "\r\n") {
                $extra.= $temp;
                $temp = '';
            }

            if ($this->curTimeout) {
                if ($this->curTimeout < 0) {
                    $this->is_timeout = true;
                    return false;
                }
                $read = array($this->fsock);
                $write = $except = null;
                $start = strtok(microtime(), ' ') + strtok('');
                $sec = floor($this->curTimeout);
                $usec = 1000000 * ($this->curTimeout - $sec);
                // on windows this returns a "Warning: Invalid CRT parameters detected" error
                // the !count() is done as a workaround for <https://bugs.php.net/42682>
                if (!@stream_select($read, $write, $except, $sec, $usec) && !count($read)) {
                    $this->is_timeout = true;
                    return false;
                }
                $elapsed = strtok(microtime(), ' ') + strtok('') - $start;
                $this->curTimeout-= $elapsed;
            }

            $temp.= fgets($this->fsock, 255);
        }

        if (feof($this->fsock)) {
            user_error('Connection closed by server');
            return false;
        }

        if (defined('NET_SSH2_LOGGING')) {
            $this->_append_log('<-', $extra . $temp);
            $this->_append_log('->', $this->identifier . "\r\n");
        }

        $this->server_identifier = trim($temp, "\r\n");
        if (strlen($extra)) {
            $this->errors[] = utf8_decode($extra);
        }

        if ($matches[1] != '1.99' && $matches[1] != '2.0') {
            user_error("Cannot connect to SSH $matches[1] servers");
            return false;
        }

        $response = $this->_get_binary_packet();
        if ($response === false) {
            user_error('Connection closed by server');
            return false;
        }

        if (!strlen($response) || ord($response[0]) != NET_SSH2_MSG_KEXINIT) {
            user_error('Expected SSH_MSG_KEXINIT');
            return false;
        }

        if (!$this->_key_exchange($response)) {
            return false;
        }

        $this->bitmap|= NET_SSH2_MASK_CONNECTED;

        return true;
    }
99552
public int getPort() {
    if (port != null && port != 0) {
      return port;
    }
    return urlParser != null ? urlParser.getHostAddresses().get(0).port : 3306;
  }
912515
public function ping() {

		if ( $this->getOption( ONOI_HTTP_REQUEST_URL ) === null ) {
			return false;
		}

		$urlComponents = $this->getUrlComponents( $this->getOption( ONOI_HTTP_REQUEST_URL ) );

		$resource = $this->getResourceFromSocketClient(
			$urlComponents,
			STREAM_CLIENT_CONNECT
		);

		if ( !$resource ) {
			return false;
		}

		stream_set_timeout( $resource, $this->getOption( ONOI_HTTP_REQUEST_CONNECTION_TIMEOUT ) );

		$httpMessage = (
			"HEAD "  . $urlComponents['path'] . " HTTP/1.1\r\n" .
			"Host: " . $urlComponents['host'] . "\r\n" .
			"Connection: Close\r\n\r\n"
		);

		$res = @fwrite( $resource, $httpMessage );

		if ( $this->getOption( ONOI_HTTP_REQUEST_FOLLOWLOCATION ) && $res !== false ) {
			$this->setOption( ONOI_HTTP_REQUEST_URL, $this->tryToFindFollowLocation( $resource, $urlComponents ) );
		}

		@fclose( $resource );

		return $res !== false;
	}
534659
protected function _connect($host)
    {
        // initialize connection
        $this->error    = '';
        $this->errornum = self::ERROR_OK;

        if (!$this->prefs['port']) {
            $this->prefs['port'] = 143;
        }

        // check for SSL
        if ($this->prefs['ssl_mode'] && $this->prefs['ssl_mode'] != 'tls') {
            $host = $this->prefs['ssl_mode'] . '://' . $host;
        }

        if ($this->prefs['timeout'] <= 0) {
            $this->prefs['timeout'] = max(0, intval(ini_get('default_socket_timeout')));
        }

        if (!empty($this->prefs['socket_options'])) {
            $context  = stream_context_create($this->prefs['socket_options']);
            $this->fp = stream_socket_client($host . ':' . $this->prefs['port'], $errno, $errstr,
                $this->prefs['timeout'], STREAM_CLIENT_CONNECT, $context);
        }
        else {
            $this->fp = @fsockopen($host, $this->prefs['port'], $errno, $errstr, $this->prefs['timeout']);
        }

        if (!$this->fp) {
            $this->setError(self::ERROR_BAD, sprintf("Could not connect to %s:%d: %s",
                $host, $this->prefs['port'], $errstr ?: "Unknown reason"));

            return false;
        }

        if ($this->prefs['timeout'] > 0) {
            stream_set_timeout($this->fp, $this->prefs['timeout']);
        }

        $line = trim(fgets($this->fp, 8192));

        if ($this->debug) {
            // set connection identifier for debug output
            preg_match('/#([0-9]+)/', (string) $this->fp, $m);
            $this->resourceid = strtoupper(substr(md5($m[1].$this->user.microtime()), 0, 4));

            if ($line) {
                $this->debug('S: '. $line);
            }
        }

        // Connected to wrong port or connection error?
        if (!preg_match('/^\* (OK|PREAUTH)/i', $line)) {
            if ($line)
                $error = sprintf("Wrong startup greeting (%s:%d): %s", $host, $this->prefs['port'], $line);
            else
                $error = sprintf("Empty startup greeting (%s:%d)", $host, $this->prefs['port']);

            $this->setError(self::ERROR_BAD, $error);
            $this->closeConnection();
            return false;
        }

        $this->data['GREETING'] = trim(preg_replace('/\[[^\]]+\]\s*/', '', $line));

        // RFC3501 [7.1] optional CAPABILITY response
        if (preg_match('/\[CAPABILITY ([^]]+)\]/i', $line, $matches)) {
            $this->parseCapability($matches[1], true);
        }

        // TLS connection
        if ($this->prefs['ssl_mode'] == 'tls' && $this->getCapability('STARTTLS')) {
            $res = $this->execute('STARTTLS');

            if ($res[0] != self::ERROR_OK) {
                $this->closeConnection();
                return false;
            }

            if (isset($this->prefs['socket_options']['ssl']['crypto_method'])) {
                $crypto_method = $this->prefs['socket_options']['ssl']['crypto_method'];
            }
            else {
                // There is no flag to enable all TLS methods. Net_SMTP
                // handles enabling TLS similarly.
                $crypto_method = STREAM_CRYPTO_METHOD_TLS_CLIENT
                    | @STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT
                    | @STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT;
            }

            if (!stream_socket_enable_crypto($this->fp, true, $crypto_method)) {
                $this->setError(self::ERROR_BAD, "Unable to negotiate TLS");
                $this->closeConnection();
                return false;
            }

            // Now we're secure, capabilities need to be reread
            $this->clearCapability();
        }

        return true;
    }
260057
public function getClientIp()
    {
        $remoteAddress = $this->server()->remoteAddress();
        $fwdClientIp = $this->server()->get($this->getTrustedHeaders()['client_ip']);

        if ($fwdClientIp && $remoteAddress && in_array($remoteAddress, $this->getTrustedProxies())) {
            // Use the forwarded IP address, typically set when the
            // client is using a proxy server.
            // Format: "X-Forwarded-For: client1, proxy1, proxy2"
            $clientIps = explode(',', $fwdClientIp);
            $clientIp = array_shift($clientIps);
        } elseif ($fwdClientIp && in_array('*', $this->getTrustedProxies())) {
            $clientIps = explode(',', $fwdClientIp);
            $clientIp = array_shift($clientIps);
        } elseif ($this->server()->httpClientIp() && $remoteAddress && in_array($remoteAddress, $this->getTrustedProxies())) {
            // Use the forwarded IP address, typically set when the
            // client is using a proxy server.
            $clientIps = explode(',', $this->server()->httpClientIp());
            $clientIp = array_shift($clientIps);
        } elseif ($this->server()->remoteAddress()) {
            // The remote IP address
            $clientIp = $this->server()->remoteAddress();
        } else {
            return false;
        }

        return $clientIp;
    }
138055
public long getLatency() {
    if (latency >= 0L) {
      return latency;
    } else if (events.size() >= 2) {
      return events.get(events.size() - 1).timestamp() - events.get(0).timestamp();
    } else {
      return -1;
    }
  }
335719
public function getPort()
    {
        $port = parent::getPort();

        if (JUri::getInstance()->isSsl() || ($this->isSecure() && in_array($port, ['80', '8080']))) {
            $port = '443';
        }

        return $port;
    }
290939
public function getPort()
    {
        if (null !== $this->port) {
            return $this->port;
        }

        $tmp = parse_url($this->getUrl());
        if (isset($tmp['port'])) {
            $this->setPort($tmp['port']);
        } elseif (isset($tmp['scheme'])) {
            $this->setPort(self::$defaultPorts[$tmp['scheme']]);
        }

        return $this->port;
    }
391470
public static function isPortInUse($port, $hostname = null)
    {
        $fp = @fsockopen($hostname !== null ? $hostname : '127.0.0.1', $port, $errno, $errstr, 10);
        if ($fp !== false) {
            fclose($fp);

            return true;
        }

        return false;
    }
1328064
public static function getHostUri()
  {
    $sheme = (self::getHostParam("HTTPS") == "on") ? "https" : "http";

    $serverName = new Str(self::getHostParam("HTTP_HOST"));
    $serverPort = self::getHostParam("SERVER_PORT");
    $serverPort = ($serverPort != 80 && $serverPort != 443) ? ":" . $serverPort : "";

    if($serverName->endsWith($serverPort))
    {
      $serverName = $serverName->replace($serverPort, "");
    }

    return new Str($sheme . "://" . $serverName . $serverPort);
  }