當前位置: 首頁>>代碼示例>>Python>>正文


Python socket.AddressFamily方法代碼示例

本文整理匯總了Python中socket.AddressFamily方法的典型用法代碼示例。如果您正苦於以下問題:Python socket.AddressFamily方法的具體用法?Python socket.AddressFamily怎麽用?Python socket.AddressFamily使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在socket的用法示例。


在下文中一共展示了socket.AddressFamily方法的14個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: resolve

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AddressFamily [as 別名]
def resolve(
        self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC
    ) -> Awaitable[List[Tuple[int, Any]]]:
        """Resolves an address.

        The ``host`` argument is a string which may be a hostname or a
        literal IP address.

        Returns a `.Future` whose result is a list of (family,
        address) pairs, where address is a tuple suitable to pass to
        `socket.connect <socket.socket.connect>` (i.e. a ``(host,
        port)`` pair for IPv4; additional fields may be present for
        IPv6). If a ``callback`` is passed, it will be run with the
        result as an argument when it is complete.

        :raises IOError: if the address cannot be resolved.

        .. versionchanged:: 4.4
           Standardized all implementations to raise `IOError`.

        .. versionchanged:: 6.0 The ``callback`` argument was removed.
           Use the returned awaitable object instead.

        """
        raise NotImplementedError() 
開發者ID:opendevops-cn,項目名稱:opendevops,代碼行數:27,代碼來源:netutil.py

示例2: split

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AddressFamily [as 別名]
def split(
        addrinfo: List[Tuple]
    ) -> Tuple[
        List[Tuple[socket.AddressFamily, Tuple]],
        List[Tuple[socket.AddressFamily, Tuple]],
    ]:
        """Partition the ``addrinfo`` list by address family.

        Returns two lists.  The first list contains the first entry from
        ``addrinfo`` and all others with the same family, and the
        second list contains all other addresses (normally one list will
        be AF_INET and the other AF_INET6, although non-standard resolvers
        may return additional families).
        """
        primary = []
        secondary = []
        primary_af = addrinfo[0][0]
        for af, addr in addrinfo:
            if af == primary_af:
                primary.append((af, addr))
            else:
                secondary.append((af, addr))
        return primary, secondary 
開發者ID:opendevops-cn,項目名稱:opendevops,代碼行數:25,代碼來源:tcpclient.py

示例3: try_connect

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AddressFamily [as 別名]
def try_connect(self, addrs: Iterator[Tuple[socket.AddressFamily, Tuple]]) -> None:
        try:
            af, addr = next(addrs)
        except StopIteration:
            # We've reached the end of our queue, but the other queue
            # might still be working.  Send a final error on the future
            # only when both queues are finished.
            if self.remaining == 0 and not self.future.done():
                self.future.set_exception(
                    self.last_error or IOError("connection failed")
                )
            return
        stream, future = self.connect(af, addr)
        self.streams.add(stream)
        future_add_done_callback(
            future, functools.partial(self.on_connect_done, addrs, af, addr)
        ) 
開發者ID:opendevops-cn,項目名稱:opendevops,代碼行數:19,代碼來源:tcpclient.py

示例4: __init__

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AddressFamily [as 別名]
def __init__(
        self,
        addrinfo: List[Tuple],
        connect: Callable[
            [socket.AddressFamily, Tuple], Tuple[IOStream, "Future[IOStream]"]
        ],
    ) -> None:
        self.io_loop = IOLoop.current()
        self.connect = connect

        self.future = (
            Future()
        )  # type: Future[Tuple[socket.AddressFamily, Any, IOStream]]
        self.timeout = None  # type: Optional[object]
        self.connect_timeout = None  # type: Optional[object]
        self.last_error = None  # type: Optional[Exception]
        self.remaining = len(addrinfo)
        self.primary_addrs, self.secondary_addrs = self.split(addrinfo)
        self.streams = set()  # type: Set[IOStream] 
開發者ID:tp4a,項目名稱:teleport,代碼行數:21,代碼來源:tcpclient.py

示例5: split

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AddressFamily [as 別名]
def split(
        addrinfo: List[Tuple],
    ) -> Tuple[
        List[Tuple[socket.AddressFamily, Tuple]],
        List[Tuple[socket.AddressFamily, Tuple]],
    ]:
        """Partition the ``addrinfo`` list by address family.

        Returns two lists.  The first list contains the first entry from
        ``addrinfo`` and all others with the same family, and the
        second list contains all other addresses (normally one list will
        be AF_INET and the other AF_INET6, although non-standard resolvers
        may return additional families).
        """
        primary = []
        secondary = []
        primary_af = addrinfo[0][0]
        for af, addr in addrinfo:
            if af == primary_af:
                primary.append((af, addr))
            else:
                secondary.append((af, addr))
        return primary, secondary 
開發者ID:tp4a,項目名稱:teleport,代碼行數:25,代碼來源:tcpclient.py

示例6: test_create_sockets_ip

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AddressFamily [as 別名]
def test_create_sockets_ip(
    bind: str,
    expected_family: socket.AddressFamily,
    expected_binding: Tuple[str, int],
    monkeypatch: MonkeyPatch,
) -> None:
    mock_socket = Mock()
    monkeypatch.setattr(socket, "socket", mock_socket)
    config = Config()
    config.bind = [bind]
    sockets = config.create_sockets()
    sock = sockets.insecure_sockets[0]
    mock_socket.assert_called_with(expected_family, socket.SOCK_STREAM)
    sock.setsockopt.assert_called_with(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)  # type: ignore
    sock.bind.assert_called_with(expected_binding)  # type: ignore
    sock.setblocking.assert_called_with(False)  # type: ignore
    sock.set_inheritable.assert_called_with(True)  # type: ignore 
開發者ID:pgjones,項目名稱:hypercorn,代碼行數:19,代碼來源:test_config.py

示例7: get_ip_address_type

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AddressFamily [as 別名]
def get_ip_address_type(addr: str) -> socket.AddressFamily:
    """Return socket.AF_INET6 or socket.AF_INET4 for the provided address."""
    import socket
    socket_type = None

    # First try it as an ipv4 address.
    try:
        socket.inet_pton(socket.AF_INET, addr)
        socket_type = socket.AF_INET
    except OSError:
        pass

    # Hmm apparently not ipv4; try ipv6.
    if socket_type is None:
        try:
            socket.inet_pton(socket.AF_INET6, addr)
            socket_type = socket.AF_INET6
        except OSError:
            pass
    if socket_type is None:
        raise ValueError('addr seems to be neither v4 or v6: ' + str(addr))
    return socket_type 
開發者ID:efroemling,項目名稱:ballistica,代碼行數:24,代碼來源:_netutils.py

示例8: _resolve_addr

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AddressFamily [as 別名]
def _resolve_addr(
    host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC
) -> List[Tuple[int, Any]]:
    # On Solaris, getaddrinfo fails if the given port is not found
    # in /etc/services and no socket type is given, so we must pass
    # one here.  The socket type used here doesn't seem to actually
    # matter (we discard the one we get back in the results),
    # so the addresses we return should still be usable with SOCK_DGRAM.
    addrinfo = socket.getaddrinfo(host, port, family, socket.SOCK_STREAM)
    results = []
    for fam, socktype, proto, canonname, address in addrinfo:
        results.append((fam, address))
    return results 
開發者ID:opendevops-cn,項目名稱:opendevops,代碼行數:15,代碼來源:netutil.py

示例9: start

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AddressFamily [as 別名]
def start(
        self,
        timeout: float = _INITIAL_CONNECT_TIMEOUT,
        connect_timeout: Union[float, datetime.timedelta] = None,
    ) -> "Future[Tuple[socket.AddressFamily, Any, IOStream]]":
        self.try_connect(iter(self.primary_addrs))
        self.set_timeout(timeout)
        if connect_timeout is not None:
            self.set_connect_timeout(connect_timeout)
        return self.future 
開發者ID:opendevops-cn,項目名稱:opendevops,代碼行數:12,代碼來源:tcpclient.py

示例10: on_connect_done

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AddressFamily [as 別名]
def on_connect_done(
        self,
        addrs: Iterator[Tuple[socket.AddressFamily, Tuple]],
        af: socket.AddressFamily,
        addr: Tuple,
        future: "Future[IOStream]",
    ) -> None:
        self.remaining -= 1
        try:
            stream = future.result()
        except Exception as e:
            if self.future.done():
                return
            # Error: try again (but remember what happened so we have an
            # error to raise in the end)
            self.last_error = e
            self.try_connect(addrs)
            if self.timeout is not None:
                # If the first attempt failed, don't wait for the
                # timeout to try an address from the secondary queue.
                self.io_loop.remove_timeout(self.timeout)
                self.on_timeout()
            return
        self.clear_timeouts()
        if self.future.done():
            # This is a late arrival; just drop it.
            stream.close()
        else:
            self.streams.discard(stream)
            self.future.set_result((af, addr, stream))
            self.close_streams() 
開發者ID:opendevops-cn,項目名稱:opendevops,代碼行數:33,代碼來源:tcpclient.py

示例11: _create_stream

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AddressFamily [as 別名]
def _create_stream(
        self,
        max_buffer_size: int,
        af: socket.AddressFamily,
        addr: Tuple,
        source_ip: str = None,
        source_port: int = None,
    ) -> Tuple[IOStream, "Future[IOStream]"]:
        # Always connect in plaintext; we'll convert to ssl if necessary
        # after one connection has completed.
        source_port_bind = source_port if isinstance(source_port, int) else 0
        source_ip_bind = source_ip
        if source_port_bind and not source_ip:
            # User required a specific port, but did not specify
            # a certain source IP, will bind to the default loopback.
            source_ip_bind = "::1" if af == socket.AF_INET6 else "127.0.0.1"
            # Trying to use the same address family as the requested af socket:
            # - 127.0.0.1 for IPv4
            # - ::1 for IPv6
        socket_obj = socket.socket(af)
        set_close_exec(socket_obj.fileno())
        if source_port_bind or source_ip_bind:
            # If the user requires binding also to a specific IP/port.
            try:
                socket_obj.bind((source_ip_bind, source_port_bind))
            except socket.error:
                socket_obj.close()
                # Fail loudly if unable to use the IP/port.
                raise
        try:
            stream = IOStream(socket_obj, max_buffer_size=max_buffer_size)
        except socket.error as e:
            fu = Future()  # type: Future[IOStream]
            fu.set_exception(e)
            return stream, fu
        else:
            return stream, stream.connect(addr) 
開發者ID:opendevops-cn,項目名稱:opendevops,代碼行數:39,代碼來源:tcpclient.py

示例12: _init

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AddressFamily [as 別名]
def _init(self, addr: addr_t, base: str, *,
	          auth: auth_t,
	          cookies: cookies_t,
	          headers: headers_t,
	          params: params_t,
	          timeout: timeout_t):
		base_url: str
		family: socket.AddressFamily
		host_numeric: bool
		base_url, family, host_numeric = multiaddr_to_url_data(addr, base)
		
		#FIXME once https://github.com/encode/httpcore/pull/100 is released
		if family != socket.AF_UNSPEC and not host_numeric:
			warnings.warn(
				"Restricting the address family on name lookups is not yet supported by HTTPx",
				UserWarning
			)
		
		self._session_kwargs = map_args_to_httpx(
			auth=auth,
			cookies=cookies,
			headers=headers,
			params=params,
			timeout=timeout,
		)
		self._session_kwargs["base_url"] = base_url 
開發者ID:ipfs-shipyard,項目名稱:py-ipfs-http-client,代碼行數:28,代碼來源:http_httpx.py

示例13: sockfam_to_enum

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AddressFamily [as 別名]
def sockfam_to_enum(num):
    """Convert a numeric socket family value to an IntEnum member.
    If it's not a known member, return the numeric value itself.
    """
    if enum is None:
        return num
    else:  # pragma: no cover
        try:
            return socket.AddressFamily(num)
        except (ValueError, AttributeError):
            return num 
開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:13,代碼來源:_common.py

示例14: sockfam_to_enum

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AddressFamily [as 別名]
def sockfam_to_enum(num):
    """Convert a numeric socket family value to an IntEnum member.
    If it's not a known member, return the numeric value itself.
    """
    if enum is None:
        return num
    else:  # pragma: no cover
        try:
            return socket.AddressFamily(num)
        except ValueError:
            return num 
開發者ID:giampaolo,項目名稱:psutil,代碼行數:13,代碼來源:_common.py


注:本文中的socket.AddressFamily方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。