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


Python socket.AF_UNSPEC屬性代碼示例

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


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

示例1: _do_dns_lookup

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AF_UNSPEC [as 別名]
def _do_dns_lookup(hostname: str, port: int) -> str:
    try:
        addr_infos = socket.getaddrinfo(hostname, port, socket.AF_UNSPEC, socket.IPPROTO_IP)
    except (socket.gaierror, IndexError, ConnectionError):
        raise ServerHostnameCouldNotBeResolved(f"Could not resolve {hostname}")

    family, socktype, proto, canonname, sockaddr = addr_infos[0]

    # By default use the first DNS entry, IPv4 or IPv6
    tentative_ip_addr = sockaddr[0]

    # But try to use IPv4 if we have both IPv4 and IPv6 addresses, to work around buggy networks
    for family, socktype, proto, canonname, sockaddr in addr_infos:
        if family == socket.AF_INET:
            tentative_ip_addr = sockaddr[0]

    return tentative_ip_addr 
開發者ID:nabla-c0d3,項目名稱:sslyze,代碼行數:19,代碼來源:server_setting.py

示例2: is_valid_ip

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AF_UNSPEC [as 別名]
def is_valid_ip(ip):
    """Returns true if the given string is a well-formed IP address.

    Supports IPv4 and IPv6.
    """
    if not ip or '\x00' in ip:
        # getaddrinfo resolves empty strings to localhost, and truncates
        # on zero bytes.
        return False
    try:
        res = socket.getaddrinfo(ip, 0, socket.AF_UNSPEC,
                                 socket.SOCK_STREAM,
                                 0, socket.AI_NUMERICHOST)
        return bool(res)
    except socket.gaierror as e:
        if e.args[0] == socket.EAI_NONAME:
            return False
        raise
    return True 
開發者ID:tao12345666333,項目名稱:tornado-zh,代碼行數:21,代碼來源:netutil.py

示例3: connect

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AF_UNSPEC [as 別名]
def connect(self, host, port, af=socket.AF_UNSPEC, ssl_options=None,
                max_buffer_size=None):
        """Connect to the given host and port.

        Asynchronously returns an `.IOStream` (or `.SSLIOStream` if
        ``ssl_options`` is not None).
        """
        addrinfo = yield self.resolver.resolve(host, port, af)
        connector = _Connector(
            addrinfo, self.io_loop,
            functools.partial(self._create_stream, max_buffer_size))
        af, addr, stream = yield connector.start()
        # TODO: For better performance we could cache the (af, addr)
        # information here and re-use it on subsequent connections to
        # the same host. (http://tools.ietf.org/html/rfc6555#section-4.2)
        if ssl_options is not None:
            stream = yield stream.start_tls(False, ssl_options=ssl_options,
                                            server_hostname=host)
        raise gen.Return(stream) 
開發者ID:tao12345666333,項目名稱:tornado-zh,代碼行數:21,代碼來源:tcpclient.py

示例4: bind

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AF_UNSPEC [as 別名]
def bind(self, port, address=None, family=socket.AF_UNSPEC, backlog=128):
        u"""綁定該服務到指定的地址的指定端口上.

        要啟動該服務, 調用 `start`. 如果你想要在一個單進程上運行該服務,
        你可以調用 `listen` 作為順序調用 `bind` 和 `start` 的一個快捷方式.

        address 參數可以是 IP 地址或者主機名.  如果它是主機名,
        該服務將監聽在和該名稱有關的所有 IP 地址上.  地址也可以是空字符串或者
        None, 服務將監聽所有可用的接口. family 可以被設置為 `socket.AF_INET` 或
        `socket.AF_INET6` 用來限定是 IPv4 或 IPv6 地址, 否則如果可用的話, 兩者
        都將被使用.

        ``backlog`` 參數和 `socket.listen <socket.socket.listen>` 是相同含義.

        這個方法可能在 `start` 之前被調用多次來監聽在多個端口或接口上.
        """
        sockets = bind_sockets(port, address=address, family=family,
                               backlog=backlog)
        if self._started:
            self.add_sockets(sockets)
        else:
            self._pending_sockets.extend(sockets) 
開發者ID:tao12345666333,項目名稱:tornado-zh,代碼行數:24,代碼來源:tcpserver.py

示例5: select_address_family

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AF_UNSPEC [as 別名]
def select_address_family(host, port):
    """Return ``AF_INET4``, ``AF_INET6``, or ``AF_UNIX`` depending on
    the host and port."""
    # disabled due to problems with current ipv6 implementations
    # and various operating systems.  Probably this code also is
    # not supposed to work, but I can't come up with any other
    # ways to implement this.
    # try:
    #     info = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
    #                               socket.SOCK_STREAM, 0,
    #                               socket.AI_PASSIVE)
    #     if info:
    #         return info[0][0]
    # except socket.gaierror:
    #     pass
    if host.startswith("unix://"):
        return socket.AF_UNIX
    elif ":" in host and hasattr(socket, "AF_INET6"):
        return socket.AF_INET6
    return socket.AF_INET 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:22,代碼來源:serving.py

示例6: test_basic_behavior

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AF_UNSPEC [as 別名]
def test_basic_behavior(self):
    inet4_server = self.mox.CreateMock(wsgi_server._SingleAddressWsgiServer)
    inet6_server = self.mox.CreateMock(wsgi_server._SingleAddressWsgiServer)
    self.mox.StubOutWithMock(wsgi_server, '_SingleAddressWsgiServer')
    self.mox.StubOutWithMock(socket, 'getaddrinfo')
    socket.getaddrinfo('localhost', 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
                       socket.AI_PASSIVE).AndReturn(
                           [(None, None, None, None, ('127.0.0.1', 0, 'baz')),
                            (None, None, None, None, ('::1', 0, 'baz'))])
    wsgi_server._SingleAddressWsgiServer(('127.0.0.1', 0), None).AndReturn(
        inet4_server)
    inet4_server.start()
    inet4_server.port = 123
    wsgi_server._SingleAddressWsgiServer(('::1', 123), None).AndReturn(
        inet6_server)
    inet6_server.start()
    self.mox.ReplayAll()
    self.server.start()
    self.mox.VerifyAll()
    self.assertItemsEqual([inet4_server, inet6_server],
                          self.server._servers) 
開發者ID:elsigh,項目名稱:browserscope,代碼行數:23,代碼來源:wsgi_server_test.py

示例7: test_retry_limited

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AF_UNSPEC [as 別名]
def test_retry_limited(self):
    inet4_servers = [self.mox.CreateMock(wsgi_server._SingleAddressWsgiServer)
                     for _ in range(wsgi_server._PORT_0_RETRIES)]
    inet6_servers = [self.mox.CreateMock(wsgi_server._SingleAddressWsgiServer)
                     for _ in range(wsgi_server._PORT_0_RETRIES)]
    self.mox.StubOutWithMock(wsgi_server, '_SingleAddressWsgiServer')
    self.mox.StubOutWithMock(socket, 'getaddrinfo')
    socket.getaddrinfo('localhost', 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
                       socket.AI_PASSIVE).AndReturn(
                           [(None, None, None, None, ('127.0.0.1', 0, 'baz')),
                            (None, None, None, None, ('::1', 0, 'baz'))])
    for offset, (inet4_server, inet6_server) in enumerate(zip(
        inet4_servers, inet6_servers)):
      wsgi_server._SingleAddressWsgiServer(('127.0.0.1', 0), None).AndReturn(
          inet4_server)
      inet4_server.start()
      inet4_server.port = offset + 1
      wsgi_server._SingleAddressWsgiServer(('::1', offset + 1), None).AndReturn(
          inet6_server)
      inet6_server.start().AndRaise(
          wsgi_server.BindError('message', (errno.EADDRINUSE, 'in use')))
      inet4_server.quit()
    self.mox.ReplayAll()
    self.assertRaises(wsgi_server.BindError, self.server.start)
    self.mox.VerifyAll() 
開發者ID:elsigh,項目名稱:browserscope,代碼行數:27,代碼來源:wsgi_server_test.py

示例8: test_ignore_other_errors

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AF_UNSPEC [as 別名]
def test_ignore_other_errors(self):
    inet4_server = self.mox.CreateMock(wsgi_server._SingleAddressWsgiServer)
    inet6_server = self.mox.CreateMock(wsgi_server._SingleAddressWsgiServer)
    self.mox.StubOutWithMock(wsgi_server, '_SingleAddressWsgiServer')
    self.mox.StubOutWithMock(socket, 'getaddrinfo')
    socket.getaddrinfo('localhost', 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
                       socket.AI_PASSIVE).AndReturn(
                           [(None, None, None, None, ('127.0.0.1', 0, 'baz')),
                            (None, None, None, None, ('::1', 0, 'baz'))])
    wsgi_server._SingleAddressWsgiServer(('127.0.0.1', 0), None).AndReturn(
        inet4_server)
    inet4_server.start()
    inet4_server.port = 123
    wsgi_server._SingleAddressWsgiServer(('::1', 123), None).AndReturn(
        inet6_server)
    inet6_server.start().AndRaise(
        wsgi_server.BindError('message', (errno.ENOPROTOOPT, 'no protocol')))
    self.mox.ReplayAll()
    self.server.start()
    self.mox.VerifyAll()
    self.assertItemsEqual([inet4_server],
                          self.server._servers) 
開發者ID:elsigh,項目名稱:browserscope,代碼行數:24,代碼來源:wsgi_server_test.py

示例9: select_ip_version

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AF_UNSPEC [as 別名]
def select_ip_version(host, port):
    """Returns AF_INET4 or AF_INET6 depending on where to connect to."""
    # disabled due to problems with current ipv6 implementations
    # and various operating systems.  Probably this code also is
    # not supposed to work, but I can't come up with any other
    # ways to implement this.
    # try:
    #     info = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
    #                               socket.SOCK_STREAM, 0,
    #                               socket.AI_PASSIVE)
    #     if info:
    #         return info[0][0]
    # except socket.gaierror:
    #     pass
    if ':' in host and hasattr(socket, 'AF_INET6'):
        return socket.AF_INET6
    return socket.AF_INET 
開發者ID:jpush,項目名稱:jbox,代碼行數:19,代碼來源:serving.py

示例10: is_valid_ip

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AF_UNSPEC [as 別名]
def is_valid_ip(ip):
    """Returns true if the given string is a well-formed IP address.

    Supports IPv4 and IPv6.
    //取自 tornado
    """
    if not ip or '\x00' in ip:
        # getaddrinfo resolves empty strings to localhost, and truncates
        # on zero bytes.
        return False
    try:
        res = socket.getaddrinfo(ip, 0, socket.AF_UNSPEC,
                                 socket.SOCK_STREAM,
                                 0, socket.AI_NUMERICHOST)
        return bool(res)
    except socket.gaierror as e:
        if e.args[0] == socket.EAI_NONAME:
            return False
        raise
    return True 
開發者ID:alexsunday,項目名稱:pyvpn,代碼行數:22,代碼來源:util.py

示例11: listen

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AF_UNSPEC [as 別名]
def listen(self):
    res0 = self._resolveAddr()
    socket_family = self._socket_family == socket.AF_UNSPEC and socket.AF_INET6 or self._socket_family
    for res in res0:
      if res[0] is socket_family or res is res0[-1]:
        break

    # We need remove the old unix socket if the file exists and
    # nobody is listening on it.
    if self._unix_socket:
      tmp = socket.socket(res[0], res[1])
      try:
        tmp.connect(res[4])
      except socket.error, err:
        eno, message = err.args
        if eno == errno.ECONNREFUSED:
          os.unlink(res[4]) 
開發者ID:XiaoMi,項目名稱:galaxy-sdk-python,代碼行數:19,代碼來源:TSocket.py

示例12: is_valid_ip

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AF_UNSPEC [as 別名]
def is_valid_ip(ip: str) -> bool:
    """Returns ``True`` if the given string is a well-formed IP address.

    Supports IPv4 and IPv6.
    """
    if not ip or "\x00" in ip:
        # getaddrinfo resolves empty strings to localhost, and truncates
        # on zero bytes.
        return False
    try:
        res = socket.getaddrinfo(
            ip, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_NUMERICHOST
        )
        return bool(res)
    except socket.gaierror as e:
        if e.args[0] == socket.EAI_NONAME:
            return False
        raise
    return True 
開發者ID:opendevops-cn,項目名稱:opendevops,代碼行數:21,代碼來源:netutil.py

示例13: resolve

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AF_UNSPEC [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

示例14: allowed_gai_family

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AF_UNSPEC [as 別名]
def allowed_gai_family():
    """This function is designed to work in the context of
    getaddrinfo, where family=socket.AF_UNSPEC is the default and
    will perform a DNS search for both IPv6 and IPv4 records."""

    family = socket.AF_INET
    if HAS_IPV6:
        family = socket.AF_UNSPEC
    return family 
開發者ID:danielecook,項目名稱:gist-alfred,代碼行數:11,代碼來源:connection.py

示例15: find_free_address

# 需要導入模塊: import socket [as 別名]
# 或者: from socket import AF_UNSPEC [as 別名]
def find_free_address():
    """Bind to None, 0 to find an unused port on localhost (IPv4 or IPv6)

    :return:
    """
    err = None
    for info in socket.getaddrinfo(None, 0, socket.AF_UNSPEC,
                                   socket.SOCK_STREAM):
        family, stype, proto, _, addr = info
        sock = None
        try:
            sock = socket.socket(family, stype, proto)
            sock.bind(addr)
            if family == socket.AF_INET:
                return "{}:{}".format(*sock.getsockname())
            elif family == socket.AF_INET6:
                return "[{}]:{}".format(*sock.getsockname()[:2])
        except socket.error as e:
            err = e
        finally:
            if sock is not None:
                sock.close()
    if err is not None:
        raise err  # pylint: disable=raising-bad-type
    else:
        raise socket.error("getaddrinfo returns an empty list") 
開發者ID:latchset,項目名稱:custodia,代碼行數:28,代碼來源:test_cli.py


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