Python errno 模块,EAFNOSUPPORT 实例源码

我们从Python开源项目中,提取了以下6个代码示例,用于说明如何使用errno.EAFNOSUPPORT

项目:Deploy_XXNET_Server    作者:jzp820927    | 项目源码 | 文件源码
def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, _create=False):
    if family not in (AF_INET, AF_INET6):
      raise error(errno.EAFNOSUPPORT, os.strerror(errno.EAFNOSUPPORT))

    if type not in (SOCK_STREAM, SOCK_DGRAM):
      raise error(errno.EPROTONOSUPPORT, os.strerror(errno.EPROTONOSUPPORT))

    if proto:
      if ((proto not in (IPPROTO_TCP, IPPROTO_UDP)) or
          (proto == IPPROTO_TCP and type != SOCK_STREAM) or
          (proto == IPPROTO_UDP and type != SOCK_DGRAM)):
        raise error(errno.EPROTONOSUPPORT, os.strerror(errno.EPROTONOSUPPORT))

    self.family = family
    self.type = type
    self.proto = proto
    self._created = False
    self._fileno = None
    self._serialized = False
    self.settimeout(getdefaulttimeout())
    self._Clear()

    if _create:
      self._CreateSocket()
项目:masakari    作者:openstack    | 项目源码 | 文件源码
def is_ipv6_supported():
    has_ipv6_support = socket.has_ipv6
    try:
        s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
        s.close()
    except socket.error as e:
        if e.errno == errno.EAFNOSUPPORT:
            has_ipv6_support = False
        else:
            raise

    # check if there is at least one interface with ipv6
    if has_ipv6_support and sys.platform.startswith('linux'):
        try:
            with open('/proc/net/if_inet6') as f:
                if not f.read():
                    has_ipv6_support = False
        except IOError:
            has_ipv6_support = False

    return has_ipv6_support
项目:Trusted-Platform-Module-nova    作者:BU-NU-CLOUD-SP16    | 项目源码 | 文件源码
def test_ipv6_supported(self):
        self.assertIn(test_utils.is_ipv6_supported(), (False, True))

        def fake_open(path):
            raise IOError

        def fake_socket_fail(x, y):
            e = socket.error()
            e.errno = errno.EAFNOSUPPORT
            raise e

        def fake_socket_ok(x, y):
            return tempfile.TemporaryFile()

        with fixtures.MonkeyPatch('socket.socket', fake_socket_fail):
            self.assertFalse(test_utils.is_ipv6_supported())

        with fixtures.MonkeyPatch('socket.socket', fake_socket_ok):
            with fixtures.MonkeyPatch('sys.platform', 'windows'):
                self.assertTrue(test_utils.is_ipv6_supported())

            with fixtures.MonkeyPatch('sys.platform', 'linux2'):
                with fixtures.MonkeyPatch('six.moves.builtins.open',
                                          fake_open):
                    self.assertFalse(test_utils.is_ipv6_supported())
项目:Trusted-Platform-Module-nova    作者:BU-NU-CLOUD-SP16    | 项目源码 | 文件源码
def is_ipv6_supported():
    has_ipv6_support = socket.has_ipv6
    try:
        s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
        s.close()
    except socket.error as e:
        if e.errno == errno.EAFNOSUPPORT:
            has_ipv6_support = False
        else:
            raise

    # check if there is at least one interface with ipv6
    if has_ipv6_support and sys.platform.startswith('linux'):
        try:
            with open('/proc/net/if_inet6') as f:
                if not f.read():
                    has_ipv6_support = False
        except IOError:
            has_ipv6_support = False

    return has_ipv6_support
项目:annotated-py-tornado    作者:hhstore    | 项目源码 | 文件源码
def bind_sockets(port, address=None, family=socket.AF_UNSPEC, backlog=128, flags=None):
    """Creates listening sockets bound to the given port and address.

    Returns a list of socket objects (multiple sockets are returned if
    the given address maps to multiple IP addresses, which is most common
    for mixed IPv4 and IPv6 use).

    Address may be either an IP address or hostname.  If it's a hostname,
    the server will listen on all IP addresses associated with the
    name.  Address may be an empty string or None to listen on all
    available interfaces.  Family may be set to either `socket.AF_INET`
    or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise
    both will be used if available.

    The ``backlog`` argument has the same meaning as for
    `socket.listen() <socket.socket.listen>`.

    ``flags`` is a bitmask of AI_* flags to `~socket.getaddrinfo`, like
    ``socket.AI_PASSIVE | socket.AI_NUMERICHOST``.
    """
    sockets = []
    if address == "":
        address = None
    if not socket.has_ipv6 and family == socket.AF_UNSPEC:
        # Python can be compiled with --disable-ipv6, which causes
        # operations on AF_INET6 sockets to fail, but does not
        # automatically exclude those results from getaddrinfo
        # results.
        # http://bugs.python.org/issue16208
        family = socket.AF_INET
    if flags is None:
        flags = socket.AI_PASSIVE
    for res in set(socket.getaddrinfo(address, port, family, socket.SOCK_STREAM,
                                      0, flags)):
        af, socktype, proto, canonname, sockaddr = res
        try:
            sock = socket.socket(af, socktype, proto)
        except socket.error as e:
            if e.args[0] == errno.EAFNOSUPPORT:
                continue
            raise
        set_close_exec(sock.fileno())
        if os.name != 'nt':
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        if af == socket.AF_INET6:
            # On linux, ipv6 sockets accept ipv4 too by default,
            # but this makes it impossible to bind to both
            # 0.0.0.0 in ipv4 and :: in ipv6.  On other systems,
            # separate sockets *must* be used to listen for both ipv4
            # and ipv6.  For consistency, always disable ipv4 on our
            # ipv6 sockets and use a separate ipv4 socket when needed.
            #
            # Python 2.x on windows doesn't have IPPROTO_IPV6.
            if hasattr(socket, "IPPROTO_IPV6"):
                sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
        sock.setblocking(0)
        sock.bind(sockaddr)
        sock.listen(backlog)
        sockets.append(sock)
    return sockets
项目:Deploy_XXNET_Server    作者:jzp820927    | 项目源码 | 文件源码
def inet_pton(af, ip):
  """inet_pton(af, ip) -> packed IP address string

  Convert an IP address from string format to a packed string suitable
  for use with low-level network functions.
  """

  if not isinstance(af, (int, long)):
    raise TypeError('an integer is required')
  if not isinstance(ip, basestring):
    raise TypeError('inet_pton() argument 2 must be string, not %s' %
                    _TypeName(ip))
  if af == AF_INET:
    parts = ip.split('.')
    if len(parts) != 4:
      raise error('illegal IP address string passed to inet_pton')
    ret = 0
    bits = 32
    for part in parts:
      if not re.match(r'^(0|[1-9]\d*)$', part) or int(part) > 0xff:
        raise error('illegal IP address string passed to inet_pton')
      bits -= 8
      ret |= ((int(part) & 0xff) << bits)
    return struct.pack('!L', ret)
  elif af == AF_INET6:
    parts = ip.split(':')

    if '.' in parts[-1]:
      ipv4_shorts = struct.unpack('!2H', inet_pton(AF_INET, parts[-1]))
      parts[-1:] = [hex(n)[2:] for n in ipv4_shorts]

    if '' in parts:
      if len(parts) == 1 or len(parts) >= 8:
        raise error('illegal IP address string passed to inet_pton')

      idx = parts.index('')
      count = parts.count('')
      pad = ['0']*(count+(8-len(parts)))

      if count == len(parts) == 3:
        parts = pad
      elif count == 2 and parts[0:2] == ['', '']:
        parts[0:2] = pad
      elif count == 2 and parts[-2:] == ['', '']:
        parts[-2:] = pad
      elif count == 1:
        parts[idx:idx+1] = pad
      else:
        raise error('illegal IP address string passed to inet_pton')
    if (len(parts) != 8 or
        [x for x in parts if not re.match(r'^[0-9A-Fa-f]{1,4}$', x)]):
      raise error('illegal IP address string passed to inet_pton')
    return struct.pack('!8H', *[int(x, 16) for x in parts])
  else:
    raise error(errno.EAFNOSUPPORT, os.strerror(errno.EAFNOSUPPORT))