Return a socket.

    :param str host: the hostname to connect to
    :param int port: the port number to connect to
    :param timeout: if specified, set the socket timeout
511992
def get_socket(host, port, timeout=None):
    
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
        af, socktype, proto, canonname, sa = res
        sock = None
        try:
            sock = socket(af, socktype, proto)
            if timeout is not None:
                sock.settimeout(timeout)
            sock.connect(sa)
            return sock

        except error:
            if sock is not None:
                sock.close()

    raise error
275812
def get_host_finger(protocol, ip, port, timeout=5):
    
    client = None
    msg = b"Hello, Server\r\n"
    if protocol == 'tcp':
        # tcp 协议
        client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        client.settimeout(timeout)
        client.connect((ip, port))
        client.send(msg)
    elif protocol == 'udp':
        # udp 协议
        client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        client.settimeout(timeout)
        client.sendto(msg, (ip, port))
    else:
        raise Exception('协议不支持')

    serverFinger = client.recv(1024)
    client.close()
    return serverFinger
453202
def connect(self, host, port):
        '''
        
        '''
        # Clear the connect state immediately since we're no longer connected
        # at this point.
        self._connected = False

        # Only after the socket has connected do we clear this state; closed
        # must be False so that writes can be buffered in writePacket(). The
        # closed state might have been set to True due to a socket error or a
        # redirect.
        self._host = "%s:%d" % (host, port)
        self._closed = False
        self._close_info = {
            'reply_code': 0,
            'reply_text': 'failed to connect to %s' % (self._host),
            'class_id': 0,
            'method_id': 0
        }

        self._transport.connect((host, port))
        self._transport.write(PROTOCOL_HEADER)

        self._last_octet_time = time.time()

        if self._synchronous_connect:
            # Have to queue this callback just after connect, it can't go
            # into the constructor because the channel needs to be
            # "always there" for frame processing, but the synchronous
            # callback can't be added until after the protocol header has
            # been written. This SHOULD be registered before the protocol
            # header is written, in the case where the header bytes are
            # written, but this thread/greenlet/context does not return until
            # after another thread/greenlet/context has read and processed the
            # recv_start frame. Without more re-write to add_sync_cb though,
            # it will block on reading responses that will never arrive
            # because the protocol header isn't written yet. TBD if needs
            # refactoring. Could encapsulate entirely here, wherein
            # read_frames exits if protocol header not yet written. Like other
            # synchronous behaviors, adding this callback will result in a
            # blocking frame read and process loop until _recv_start and any
            # subsequent synchronous callbacks have been processed. In the
            # event that this is /not/ a synchronous transport, but the
            # caller wants the connect to be synchronous so as to ensure that
            # the connection is ready, then do a read frame loop here.
            self._channels[0].add_synchronous_cb(self._channels[0]._recv_start)
            while not self._connected:
                self.read_frames()
326604
def pick_free_port(hostname=REDIRECT_HOST, port=0):
    
    import socket
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        s.bind((hostname, port))  # port=0 finds an open port
    except OSError as e:
        log.warning("Could not bind to %s:%s %s", hostname, port, e)
        if port == 0:
            print('Unable to find an open port for authentication.')
            raise AuthenticationException(e)
        else:
            return pick_free_port(hostname, 0)
    addr, port = s.getsockname()
    s.close()
    return port
324506
def open(self):
        
        self.device = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.device.connect((self.host, self.port))

        if self.device is None:
            print "Could not open socket for %s" % self.host
957466
async def set_host_manager(self, addr, timeout=TIMEOUT):
        
        r_manager = await self.env.connect(addr, timeout=timeout)
        return await r_manager.set_host_manager(self.manager.addr)
679396
def get(host="localhost", port=3551, timeout=30):
    
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(timeout)
    sock.connect((host, port))
    sock.send(CMD_STATUS)
    buffr = ""
    while not buffr.endswith(EOF):
        buffr += sock.recv(BUFFER_SIZE).decode()
    sock.close()
    return buffr
781945
def _createSocket(self, port):
        '''
        
        '''
        self._logger.info(
            'Setting up UDP socket to listen to port {:}'.format(port))
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        sock.settimeout(self._timeout)
        self._logger.info(
            'Successfully set socket timeout to {_timeout}'
            .format(**self.__dict__))

        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self._logger.info('Successfully set socket option to SO_REUSEADDR')

        sock.bind(('', port))
        self._logger.info(
            'Successfully bound socket to ("", {port})'
            .format(port=port, **self.__dict__))

        return sock
474422
def _connect(self, sock, addr, timeout):
        """"""
        if self.connection:
            raise SocketClientConnectedError()

        if self.connector:
            raise SocketClientConnectingError()

        self.connect_deferred = Deferred(self.loop)
        self.sock = sock
        self.addr = addr
        self.connector = Connector(self.loop, sock, addr, timeout)
        self.connector.deferred.add_callback(self._connected)
        self.connector.deferred.add_errback(self._connect_failed)
        self.connector.start()

        return self.connect_deferred
457702
def port(self, port=None):
        
        if (port is None) or (port == self.__port):
            return self.__port
        # when port change ensure old socket is close
        self.close()
        # valid port ?
        if 0 < int(port) < 65536:
            self.__port = int(port)
            return self.__port
        else:
            return None
693243
def await_socket(self, timeout):
    """"""
    return self.await_metadata_by_name(self._name, 'socket', timeout, self._socket_type)
259409
def _get_channel(host, timeout):
    
    connection = create_blocking_connection(host)

    # register timeout
    if timeout >= 0:
        connection.add_timeout(
            timeout,
            lambda: sys.stderr.write("Timeouted!\n") or sys.exit(1)
        )

    return connection.channel()
541321
def connect(self, host, port):
        """"""
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((host, port))
        self._reader = sock.makefile(mode='rb')
        self._writer = sock.makefile(mode='wb')
1165075
public void connect (int timeout, InetAddress host, int tcpPort) throws IOException {
		connect(timeout, host, tcpPort, -1);
	}
173982
protected DRPCClient createClient(String host, int port, int timeout)
    {
        return new DRPCClient(host, port, timeout);
    }
1108036
def _create_socket(self):
        
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s = ssl.wrap_socket(s)
        s.connect((self.host, self.__port))
        s.settimeout(self.timeout)
        return s
852826
def open_socket(host, port) # :nodoc:
      return Timeout.timeout(@open_timeout, Net::OpenTimeout) {
        if defined? SOCKSSocket and ENV["SOCKS_SERVER"]
          @passive = true
          sock = SOCKSSocket.open(host, port)
        else
          sock = TCPSocket.open(host, port)
        end
        io = BufferedSocket.new(sock)
        io.read_timeout = @read_timeout
        io
      }
    end