Check if remote server is accessible
435736
def connect(self):
        

        if not self._connected and not self._closed:
            try:
                log.info("Connecting to compute '{}'".format(self._id))
                response = yield from self._run_http_query("GET", "/capabilities")
            except ComputeError as e:
                # Try to reconnect after 2 seconds if server unavailable only if not during tests (otherwise we create a ressources usage bomb)
                if not hasattr(sys, "_called_from_test") or not sys._called_from_test:
                    self._connection_failure += 1
                    # After 5 failure we close the project using the compute to avoid sync issues
                    if self._connection_failure == 5:
                        log.warning("Cannot connect to compute '{}': {}".format(self._id, e))
                        yield from self._controller.close_compute_projects(self)
                    asyncio.get_event_loop().call_later(2, lambda: asyncio.async(self._try_reconnect()))
                return
            except aiohttp.web.HTTPNotFound:
                raise aiohttp.web.HTTPConflict(text="The server {} is not a GNS3 server or it's a 1.X server".format(self._id))
            except aiohttp.web.HTTPUnauthorized:
                raise aiohttp.web.HTTPConflict(text="Invalid auth for server {}".format(self._id))
            except aiohttp.web.HTTPServiceUnavailable:
                raise aiohttp.web.HTTPConflict(text="The server {} is unavailable".format(self._id))
            except ValueError:
                raise aiohttp.web.HTTPConflict(text="Invalid server url for server {}".format(self._id))

            if "version" not in response.json:
                self._http_session.close()
                raise aiohttp.web.HTTPConflict(text="The server {} is not a GNS3 server".format(self._id))
            self._capabilities = response.json
            if parse_version(__version__)[:2] != parse_version(response.json["version"])[:2]:
                self._http_session.close()
                raise aiohttp.web.HTTPConflict(text="The server {} versions are not compatible {} != {}".format(self._id, __version__, response.json["version"]))

            self._notifications = asyncio.gather(self._connect_notification())
            self._connected = True
            self._connection_failure = 0
            self._controller.notification.emit("compute.updated", self.__json__())
112338
public function isAvailable()
    {
        // check if apache module is installed
        if (function_exists('apache_get_modules')) {
            foreach (apache_get_modules() as $name) {
                if (strpos($name, 'geoip') !== false) {
                    return true;
                }
            }
        }

        $available = !empty($_SERVER[self::TEST_SERVER_VAR])
            || !empty($_SERVER[self::TEST_SERVER_VAR_ALT])
            || !empty($_SERVER[self::TEST_SERVER_VAR_ALT_IPV6])
        ;

        if ($available) {
            return true;
        }

        // if not available return message w/ extra info
        if (!function_exists('apache_get_modules')) {
            return Piwik::translate('General_Note') . ':&nbsp;' . Piwik::translate('UserCountry_AssumingNonApache');
        }

        $message = "<strong>" . Piwik::translate('General_Note') . ':&nbsp;'
            . Piwik::translate('UserCountry_FoundApacheModules')
            . "</strong>:<br/><br/>\n<ul style=\"list-style:disc;margin-left:24px\">\n";
        foreach (apache_get_modules() as $name) {
            $message .= "<li>$name</li>\n";
        }
        $message .= "</ul>";
        return $message;
    }
516739
def check_network_connection(server, port):
    '''
    
    '''
    logger = logging.getLogger(__name__)
    logger.debug("Checking network connection to server '%s'...", server)
    try:
        # see if we can resolve the host name -- tells us if there is
        # a DNS listening
        host = socket.gethostbyname(server)
        # connect to the host -- tells us if the host is actually
        # reachable
        sock = socket.create_connection((host, port), 2)
        sock.close()
    except Exception:  # pragma: no cover
        logger.debug("Network connection not working")
        return False
    logger.debug("Network connection working")
    return True
498532
def server_enabled(s_name, **connection_args):
    '''
    
    '''
    server = _server_get(s_name, **connection_args)
    return server is not None and server.get_state() == 'ENABLED'
1126051
private function canProxy() {
        // grab the comma-delimited set of trusted proxies if they exist
        $trustedProxies = config('proxypass.trusted_proxies');
        if(empty($trustedProxies)) {
            // no proxies have been whitelisted so allow all proxy servers
            return true;
        }

        // form an array and kill any whitespace in each element
        $proxyArr = explode(",", $trustedProxies);
        array_walk($proxyArr, 'trim');

        // first we need to check the REMOTE_ADDR value to see if the IP
        // address being reported matches one of the trusted proxies
        if(!empty($_SERVER['REMOTE_ADDR'])) {
            if(in_array($_SERVER['REMOTE_ADDR'], $proxyArr)) {
                // the machine that made the request is a trusted proxy so
                // everything is fine
                return true;
            }
        }

        // now we need to check the X-Forwarded-Server header if it exists
        // since that's one of the three standard request headers that a
        // proxy would pass along with a request
        if(!empty($_SERVER['HTTP_X_FORWARDED_SERVER'])) {
            if(in_array(trim($_SERVER['HTTP_X_FORWARDED_SERVER']), $proxyArr)) {
                // the hostname of the proxy matches a trusted proxy so
                // everything is fine
                return true;
            }
        }

        // we are either not behind a proxy or the proxy forwarding the request
        // is not in the set of trusted proxies
        return false;
    }
758374
def is_connected(self):
        
        if self._client is not None:
            try:
                self._client.server_info()
            except ConnectionFailure:
                return False
            return True
        else:
            return False
612102
def check_webserver_running(url="http://localhost:8800", max_retries=30):
    

    retry = 0
    response = ''
    success = False

    while response != requests.codes.ok and retry < max_retries:
        try:
            response = requests.head(url, allow_redirects=True).status_code
            success = True
        except:
            sleep(1)

        retry += 1

    if not success:
        logging.warning('Unable to connect to %s within %s retries'
                     % (url, max_retries))
    return success
1138462
def show_network_ip_availability(self, network, **_params):
        """"""
        return self.get(self.network_ip_availability_path % (network),
                        params=_params)
592937
def is_running(self, port):
        """"""
        try:
            con = self.client('localhost:%s' % port)
            con.admin.command('ping')
            return True
        except (AutoReconnect, ConnectionFailure, OperationFailure):
            # Catch OperationFailure to work around SERVER-31916.
            return False
1273347
function client_ip(){
        if (isset($_SERVER)) {
            if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
                $real_ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
            } else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
                $real_ip = $_SERVER["HTTP_CLIENT_IP"];
            } else {
                $real_ip = $_SERVER["REMOTE_ADDR"];
            }
        } else {
            if (getenv("HTTP_X_FORWARDED_FOR")) {
                $real_ip = getenv("HTTP_X_FORWARDED_FOR");
            } else if (getenv("HTTP_CLIENT_IP")) {
                $real_ip = getenv("HTTP_CLIENT_IP");
            } else {
                $real_ip = getenv("REMOTE_ADDR");
            }
        }
        return $real_ip;
    }
44038
def remote(self) -> Optional[str]:
        
        if isinstance(self._transport_peername, (list, tuple)):
            return self._transport_peername[0]
        else:
            return self._transport_peername
157361
def local_run():
  """"""
  server_software = os.environ.get('SERVER_SOFTWARE')
  if server_software is None:
    return True
  if 'remote_api' in server_software:
    return False
  if server_software.startswith(('Development', 'testutil')):
    return True
  return False
1192822
def get_available_port
      server = TCPServer.open(0)
      saddr = server.getsockname
      port = Socket.unpack_sockaddr_in(saddr)[0]
      server.close
      port
    end
764607
def is_server_running(host, port):
    
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        return s.connect_ex((host, port)) == 0
    finally:
        s.close()
991514
def get_current_status(self):
        """"""
        url = get_url("/remote/status.json")
        params = {"oauth": self._oauth_token, "csrf": self._csrf_token}
        r = self._request(url=url, params=params)
        return r.json()
1261374
def server_exists(s_name, ip=None, s_state=None, **connection_args):
    '''
    
    '''
    server = _server_get(s_name, **connection_args)
    if server is None:
        return False
    if ip is not None and ip != server.get_ipaddress():
        return False
    if s_state is not None and s_state.upper() != server.get_state():
        return False
    return True
704727
def local_check (self):
        """"""
        log.debug(LOG_CHECK, "Checking %s", unicode(self))
        # strict extern URLs should not be checked
        assert not self.extern[1], 'checking strict extern URL'
        # check connection
        log.debug(LOG_CHECK, "checking connection")
        try:
            self.check_connection()
            self.set_content_type()
            self.add_size_info()
            self.aggregate.plugin_manager.run_connection_plugins(self)
        except tuple(ExcList) as exc:
            value = self.handle_exception()
            # make nicer error msg for unknown hosts
            if isinstance(exc, socket.error) and exc.args[0] == -2:
                value = _('Hostname not found')
            elif isinstance(exc, UnicodeError):
                # idna.encode(host) failed
                value = _('Bad hostname %(host)r: %(msg)s') % {'host': self.host, 'msg': str(value)}
            self.set_result(unicode_safe(value), valid=False)