Create or retrieve a muxed connection

        Arguments:
        address -- a peer endpoint in IPv4/v6 address format; None refers
                   to the connection for unknown peers

        Return:
        a bound, connected datagram socket instance
6141
def get_connection(self, address):
        

        if self.connections.has_key(address):
            return self.connections[address]
        
        # We need a new datagram socket on a dynamically assigned ephemeral port
        conn = socket.socket(self._forwarding_socket.family,
                             self._forwarding_socket.type,
                             self._forwarding_socket.proto)
        conn.bind((self._forwarding_socket.getsockname()[0], 0))
        conn.connect(self._forwarding_socket.getsockname())
        if not address:
            conn.setblocking(0)
        self.connections[address] = conn
        _logger.debug("Created new connection for address: %s", address)
        return conn
838189
def _negotiate_SOCKS5(self, *dest_addr):
        
        CONNECT = b"\x01"
        self.proxy_peername, self.proxy_sockname = self._SOCKS5_request(self,
            CONNECT, dest_addr)
1352151
def ipaddr(value, options=None):
    '''
    
    '''
    ipv4_obj = ipv4(value, options=options)
    ipv6_obj = ipv6(value, options=options)
    if ipv4_obj is None or ipv6_obj is None:
        # an IP address can be either IPv4 either IPv6
        # therefofe if the value passed as arg is not a list, at least one of the calls above will return None
        # if one of them is none, means that we should return only one of them
        return ipv4_obj or ipv6_obj  # one of them
    else:
        return ipv4_obj + ipv6_obj
1226199
def connection_made(self, transport):
        ''''''
        self.transport = transport
        # If the Socks proxy was used then _proxy and _remote_address are already set
        if self._proxy is None:
            # This would throw if called on a closed SSL transport.  Fixed in asyncio in
            # Python 3.6.1 and 3.5.4
            peername = transport.get_extra_info('peername')
            self._remote_address = NetAddress(peername[0], peername[1])
        self._task = spawn_sync(self._process_messages(), loop=self.loop)
221287
function peerResolved (ip, addressType) {
    // Possible cancelation during DNS lookup.
    if (!socket._connecting) return;

    socket._peer = { address: ip || '127.0.0.1', port: options.port };

    // Generate random bytes used to set randomized socket properties.
    // `crypto.randomBytes` calls OpenSSL `RAND_bytes` to generate the bytes.
    //
    //  * [RAND_bytes](http://www.openssl.org/docs/crypto/RAND_bytes.html).
    //  * [node_crypto.cc](https://github.com/joyent/node/blob/v0.8/src/node_crypto.cc#L4517)
    crypto.randomBytes(4, valid(randomzied));
  }
1154290
def connect(self, address, **kws):
        
        return yield_(Connect(self, address, timeout=self._timeout, **kws))
683235
def peer_address(self):
        
        if not self._peer_address:
            self._peer_address = self.proto.reader._transport.get_extra_info('peername')
            if len(self._peer_address) == 4:
                self._peer_address = self._peer_address[:2]
        return self._peer_address
769521
def get_ipv4(hostname):
    
    addrinfo = socket.getaddrinfo(hostname, None, socket.AF_INET,
                                  socket.SOCK_STREAM)
    return [addrinfo[x][4][0] for x in range(len(addrinfo))]
743834
def connected_socket(address, timeout=3):
    
    sock = socket.create_connection(address, timeout)
    yield sock
    sock.close()
24442
def get_address(pk, main_net=True, prefix=None):
    
    if isinstance(pk, str):
        pk = unhexlify(pk.encode())
    assert len(pk) == 32, 'PK is 32bytes {}'.format(len(pk))
    k = keccak_256(pk).digest()
    ripe = RIPEMD160.new(k).digest()
    if prefix is None:
        body = (b"\x68" if main_net else b"\x98") + ripe
    else:
        assert isinstance(prefix, bytes), 'Set prefix 1 bytes'
        body = prefix + ripe
    checksum = keccak_256(body).digest()[0:4]
    return b32encode(body + checksum).decode()
641226
def bind_tcp_socket(address):
    
    host, port = address
    for res in set(socket.getaddrinfo(host, port, socket.AF_INET,
                                      socket.SOCK_STREAM, 0,
                                      socket.AI_PASSIVE)):

        family, socktype, proto, _, sock_addr = res
        sock = socket.socket(family, socktype, proto)
        if os.name != 'nt':
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        # Automatic port allocation with port=None.
        sock.bind(sock_addr)
        sock.listen(128)
        bound_port = sock.getsockname()[1]
        return sock, (host, bound_port)

    raise socket.error('could not bind socket')
801240
def _negotiate_SOCKS4(self, dest_addr, dest_port):
        
        proxy_type, addr, port, rdns, username, password = self.proxy

        writer = self.makefile("wb")
        reader = self.makefile("rb", 0)  # buffering=0 renamed in Python 3
        try:
            # Check if the destination address provided is an IP address
            remote_resolve = False
            try:
                addr_bytes = socket.inet_aton(dest_addr)
            except socket.error:
                # It's a DNS name. Check where it should be resolved.
                if rdns:
                    addr_bytes = b"\x00\x00\x00\x01"
                    remote_resolve = True
                else:
                    addr_bytes = socket.inet_aton(socket.gethostbyname(dest_addr))

            # Construct the request packet
            writer.write(struct.pack(">BBH", 0x04, 0x01, dest_port))
            writer.write(addr_bytes)

            # The username parameter is considered userid for SOCKS4
            if username:
                writer.write(username)
            writer.write(b"\x00")

            # DNS name if remote resolving is required
            # NOTE: This is actually an extension to the SOCKS4 protocol
            # called SOCKS4A and may not be supported in all cases.
            if remote_resolve:
                writer.write(dest_addr.encode('idna') + b"\x00")
            writer.flush()

            # Get the response from the server
            resp = self._readall(reader, 8)
            if resp[0:1] != b"\x00":
                # Bad data
                raise GeneralProxyError("SOCKS4 proxy server sent invalid data")

            status = ord(resp[1:2])
            if status != 0x5A:
                # Connection failed: server returned an error
                error = SOCKS4_ERRORS.get(status, "Unknown error")
                raise SOCKS4Error("{0:#04x}: {1}".format(status, error))

            # Get the bound address/port
            self.proxy_sockname = (socket.inet_ntoa(resp[4:]), struct.unpack(">H", resp[2:4])[0])
            if remote_resolve:
                self.proxy_peername = socket.inet_ntoa(addr_bytes), dest_port
            else:
                self.proxy_peername = dest_addr, dest_port
        finally:
            reader.close()
            writer.close()
1012943
def get_socket(self, address, role):
        
        #
        # If this thread doesn't yet have a sockets cache
        # in its local storage, create one here.
        #
        try:
            self._tls.sockets
        except AttributeError:
            self._tls.sockets = {}
        
        # Convert the address to a single canonical string.
        #
        # If a list of addresses is passed, turn it into a tuple
        # of canonical addresses for use as a dictionary key. 
        # Otherwise convert it to a single canonical string.
        #
        if isinstance(address, list):
            caddress = tuple(core.address(a) for a in address)
        else:
            caddress = core.address(address)
            
        #
        # Each socket is identified for this thread by its address(es)
        # and the role the socket is playing (listener, publisher, etc.)
        # That is, within one thread, we are cacheing a read or a write
        # socket to the same address(es).
        #
        # The slight corner case from this is that if you attempt to
        # send to [addressA, addressB] and then to addressA and then
        # to [addressB, addressA], three separate sockets will be
        # created and used.
        #
        identifier = caddress
        
        if identifier not in self._tls.sockets:
            _logger.debug("%s does not exist in local sockets", identifier)
            #
            # If this is a listening / subscribing socket, it can only
            # be bound once, regardless of thread. Therefore keep a
            # threads-global list of addresses used and make sure this
            # one hasn't been used elsewhere.
            #
            if role in Socket.binding_roles:
                with self._lock:
                    if identifier in self._sockets:
                        raise core.SocketAlreadyExistsError("You cannot create a listening socket in more than one thread")
                    else:
                        self._sockets.add(identifier)
            
            type = self.roles[role]
            socket = context.socket(type)
            socket.role = role
            socket.address = caddress
            #
            # Do this last so that an exception earlier will result
            # in the socket not being cached
            #
            self._tls.sockets[identifier] = socket
        else:
            _logger.debug("%s already not exist in local sockets", identifier)
            #
            # Only return sockets created in this thread
            #
            socket = self._tls.sockets[identifier]

        return socket
448872
def ip_address(self):
        
        networks = self.get("networks", {})
        v4nets = networks.get("v4", [])
        v6nets = networks.get("v6", [])
        try:
            return (v4nets + v6nets)[0].ip_address
        except IndexError:
            return None
227063
def on_readable
      datagram = nil
      begin
        datagram = @socket.recvfrom_nonblock(DATAGRAM_SIZE).first
      rescue Errno::ECONNREFUSED
      end

      address = response_address datagram rescue nil
      address ? on_success(address) : on_failure
      detach
    end
770028
def connection_made(self):
        
        LOG.info(
            'Connection to peer: %s established',
            self._neigh_conf.ip_address,
            extra={
                'resource_name': self._neigh_conf.name,
                'resource_id': self._neigh_conf.id
            }
        )
541547
def addresses
      [get_peername, get_sockname].map do |addr|
        addr ? Socket.unpack_sockaddr_in(addr)[0, 2].reverse.join(':') : 'unknown'
      end
    end