Helper for forcing a connection to localhost. Useful when using regtest mode. Returns the peer object.
969062
@Nullable
    public Peer connectToLocalHost() {
        lock.lock();
        try {
            final PeerAddress localhost = PeerAddress.localhost(params);
            backoffMap.put(localhost, new ExponentialBackoff(peerBackoffParams));
            return connectTo(localhost, true, vConnectTimeoutMillis);
        } finally {
            lock.unlock();
        }
    }
993325
async def _open_connection_http(self, location):
        '''
        
        '''
        sock = await connect_tcp(location[0], location[1], bind_host=self.source_address)
        sock._active = True
        return sock
84301
def connection_made(self, transport):
        '''
        
        '''

        self.transport = transport
        self.remote_ip, self.port = transport.get_extra_info('peername')[:2]

        logging.debug(
            'Connection made (address: {} port: {})'
            .format(self.remote_ip, self.port))

        self.future = self.send_package(
                protomap.CPROTO_REQ_INFO,
                data=None,
                timeout=10)
719053
def _try_connect(self, host):
        
        log.debug("[control connection] Opening new connection to %s", host)

        while True:
            try:
                connection = self._cluster.connection_factory(host.endpoint, is_control_connection=True)
                if self._is_shutdown:
                    connection.close()
                    raise DriverException("Reconnecting during shutdown")
                break
            except ProtocolVersionUnsupported as e:
                self._cluster.protocol_downgrade(host.endpoint, e.startup_version)

        log.debug("[control connection] Established new connection %r, "
                  "registering watchers and refreshing schema and topology",
                  connection)

        # use weak references in both directions
        # _clear_watcher will be called when this ControlConnection is about to be finalized
        # _watch_callback will get the actual callback from the Connection and relay it to
        # this object (after a dereferencing a weakref)
        self_weakref = weakref.ref(self, partial(_clear_watcher, weakref.proxy(connection)))
        try:
            connection.register_watchers({
                "TOPOLOGY_CHANGE": partial(_watch_callback, self_weakref, '_handle_topology_change'),
                "STATUS_CHANGE": partial(_watch_callback, self_weakref, '_handle_status_change'),
                "SCHEMA_CHANGE": partial(_watch_callback, self_weakref, '_handle_schema_change')
            }, register_timeout=self._timeout)

            sel_peers = self._SELECT_PEERS if self._token_meta_enabled else self._SELECT_PEERS_NO_TOKENS
            sel_local = self._SELECT_LOCAL if self._token_meta_enabled else self._SELECT_LOCAL_NO_TOKENS
            peers_query = QueryMessage(query=sel_peers, consistency_level=ConsistencyLevel.ONE)
            local_query = QueryMessage(query=sel_local, consistency_level=ConsistencyLevel.ONE)
            shared_results = connection.wait_for_responses(
                peers_query, local_query, timeout=self._timeout)

            self._refresh_node_list_and_token_map(connection, preloaded_results=shared_results)
            self._refresh_schema(connection, preloaded_results=shared_results, schema_agreement_wait=-1)
        except Exception:
            connection.close()
            raise

        return connection
723656
def urlopen(self, method, url, **kw):
        ""
        kw['assert_same_host'] = False
        return self.proxy_pool.urlopen(method, url, **kw)
1301934
public static String getLocalhost() {
    if (localhost == null) {
      synchronized (HostAndPort.class) {
        if (localhost == null) {
          return localhost = getLocalHostQuietly();
        }
      }
    }
    return localhost;
  }
1328791
def atlas_peer_get_neighbors( my_hostport, peer_hostport, timeout=None, peer_table=None, con=None, path=None ):
    
   
    if timeout is None:
        timeout = atlas_neighbors_timeout()

    peer_list = None

    host, port = url_to_host_port( peer_hostport )
    RPC = get_rpc_client_class()
    rpc = RPC( host, port, timeout=timeout, src=my_hostport )

    # sane limits
    max_neighbors = atlas_max_neighbors()

    assert not atlas_peer_table_is_locked_by_me()
    
    try:
        peer_list = blockstack_atlas_peer_exchange( peer_hostport, my_hostport, timeout=timeout, proxy=rpc )
        if json_is_exception(peer_list):
            # fall back to legacy method 
            peer_list = blockstack_get_atlas_peers(peer_hostport, timeout=timeout, proxy=rpc)

    except (socket.timeout, socket.gaierror, socket.herror, socket.error), se:
        atlas_log_socket_error( "atlas_peer_exchange(%s)" % peer_hostport, peer_hostport, se)
        log.error("Socket error in response from '%s'" % peer_hostport)

    except Exception, e:
        if os.environ.get("BLOCKSTACK_DEBUG") == "1":
            log.exception(e)
        log.error("Failed to talk to '%s'" % peer_hostport)
   
    if peer_list is None:
        log.error("Failed to query remote peer %s" % peer_hostport)
        atlas_peer_update_health( peer_hostport, False, peer_table=peer_table )
        return None 

    if 'error' in peer_list:
        log.debug("Remote peer error: %s" % peer_list['error'])
        log.error("Remote peer error on %s" % peer_hostport)
        atlas_peer_update_health( peer_hostport, False, peer_table=peer_table )
        return None

    ret = peer_list['peers']
    atlas_peer_update_health( peer_hostport, True, peer_table=peer_table )
    return ret
520509
def _get(self, scheme, host, port, path, assert_key=None):
        
        url = '%s://%s:%i/%s' % (scheme, host, port, path)
        try:
            request = urllib2.Request(url)
            if self.config['user'] and self.config['password']:
                base64string = base64.standard_b64encode(
                    '%s:%s' % (self.config['user'], self.config['password']))
                request.add_header("Authorization", "Basic %s" % base64string)
            response = urllib2.urlopen(request)
        except Exception as err:
            self.log.error("%s: %s" % (url, err))
            return False

        try:
            doc = json.load(response)
        except (TypeError, ValueError):
            self.log.error("Unable to parse response from elasticsearch as a" +
                           " json object")
            return False

        if assert_key and assert_key not in doc:
            self.log.error("Bad response from elasticsearch, expected key "
                           "'%s' was missing for %s" % (assert_key, url))
            return False
        return doc
160986
function (forceProtocol) {
        var rawUrl = E,
            protocol = this.protocol;

        forceProtocol && !protocol && (protocol = DEFAULT_PROTOCOL);

        if (protocol) {
            rawUrl += (_.endsWith(protocol, PROTOCOL_SEPARATOR) ? protocol : protocol + PROTOCOL_SEPARATOR);
        }

        if (this.auth && this.auth.user) { // If the user is not specified, ignore the password.
            rawUrl = rawUrl + ((this.auth.password) ?
                // ==> username:password@
                this.auth.user + AUTH_SEPARATOR + this.auth.password : this.auth.user) + AUTH_CREDENTIALS_SEPARATOR;
        }

        if (this.host) {
            rawUrl += this.getHost();
        }

        if (this.port) {
            rawUrl += PORT_SEPARATOR + this.port.toString();
        }

        if (this.path) {
            rawUrl += this.getPath();
        }

        if (this.query && this.query.count()) {
            rawUrl += QUERY_SEPARATOR + this.getQueryString({ ignoreDisabled: true });
        }

        if (this.hash) {
            rawUrl += SEARCH_SEPARATOR + this.hash;
        }

        return rawUrl;
    }
594029
def init(port=8813, numRetries=10, host="localhost", label="default"):
    
    _connections[label] = connect(port, numRetries, host)
    switch(label)
    return getVersion()
783396
def start_protocol(self, socket):
        
        assert socket
        peer_addr, peer_port = self.get_remotename(socket)
        peer = self._peer_manager.get_by_addr(peer_addr)
        bgp_proto = self.build_protocol(socket)

        # We reject this connection request from peer:
        # 1) If we have connection initiated by a peer that is not in our
        #     configuration.
        # 2) If this neighbor is not enabled according to configuration.
        if not peer or not peer.enabled:
            LOG.debug('Closed connection %s %s:%s as it is not a recognized'
                      ' peer.', 'from' if bgp_proto.is_reactive else 'to',
                      peer_addr, peer_port)
            # Send connection rejected notification as per RFC
            code = BGP_ERROR_CEASE
            subcode = BGP_ERROR_SUB_CONNECTION_RESET
            bgp_proto.send_notification(code, subcode)
        elif bgp_proto.is_reactive and \
                peer.connect_mode is CONNECT_MODE_ACTIVE:
            LOG.debug('Closed connection from %s:%s as connect_mode is'
                      ' configured ACTIVE.', peer_addr, peer_port)
            # Send connection rejected notification as per RFC
            code = BGP_ERROR_CEASE
            subcode = BGP_ERROR_SUB_CONNECTION_RESET
            bgp_proto.send_notification(code, subcode)
        elif not (peer.in_idle() or peer.in_active() or peer.in_connect()):
            LOG.debug('Closing connection to %s:%s as we have connection'
                      ' in state other than IDLE or ACTIVE,'
                      ' i.e. connection resolution',
                      peer_addr, peer_port)
            # Send Connection Collision Resolution notification as per RFC.
            code = BGP_ERROR_CEASE
            subcode = BGP_ERROR_SUB_CONNECTION_COLLISION_RESOLUTION
            bgp_proto.send_notification(code, subcode)
        else:
            bind_ip, bind_port = self.get_localname(socket)
            peer._host_bind_ip = bind_ip
            peer._host_bind_port = bind_port
            self._spawn_activity(bgp_proto, peer)
1081857
def configure_client(cls, host: str = 'localhost', port: int = 11211, **client_args):
        
        assert check_argument_types()
        client = Client(host, port, **client_args)
        return client
499202
@Override
	public final String getRemotePeerID()
	{
		SocketAddress peerAddress = getRemotePeer();
		return peerAddress != null ? peerAddress.toString() : "not connected";
	}
151821
def get_local_connection(logger, use_sudo=False):
    
    return get_connection(
        socket.gethostname(),  # cannot rely on 'localhost' here
        None,
        logger=logger,
        threads=1,
        use_sudo=use_sudo,
        detect_sudo=False
    )
1362047
def connectionJustEstablished(self):
        
        assert not self.disconnecting
        assert not self.disconnected
        try:
            p = self.factory.buildProtocol(PTCPAddress(
                    self.peerAddressTuple, self.pseudoPortPair))
            p.makeConnection(self)
        except:
            log.msg("Exception during PTCP connection setup.")
            log.err()
            self.loseConnection()
        else:
            self.protocol = p
137595
def getPeer(self, url):
        
        peers = list(models.Peer.select().where(models.Peer.url == url))
        if len(peers) == 0:
            raise exceptions.PeerNotFoundException(url)
        return peers[0]
216481
def get(self, hostport):
        
        assert hostport, "hostport is required"
        assert isinstance(hostport, basestring), "hostport must be a string"

        if hostport not in self._peers:
            self._add(hostport)

        return self._peers[hostport]