socket.py 26.4 KB
Newer Older
1 2 3 4 5 6
# Wrapper module for _socket, providing some additional facilities
# implemented in Python.

"""\
This module provides socket operations and some related functions.
On Unix, it supports IP (Internet Protocol) and Unix domain sockets.
Tim Peters's avatar
Tim Peters committed
7
On other systems, it only supports IP. Functions specific for a
8
socket are available as methods of the socket object.
9 10 11 12

Functions:

socket() -- create a new socket object
13
socketpair() -- create a pair of new socket objects [*]
14
fromfd() -- create a socket object from an open file descriptor [*]
15
fromshare() -- create a socket object from data received from socket.share() [*]
16 17 18 19
gethostname() -- return the current hostname
gethostbyname() -- map a hostname to its IP number
gethostbyaddr() -- map an IP number or hostname to DNS info
getservbyname() -- map a service name and a protocol name to a port number
20
getprotobyname() -- map a protocol name (e.g. 'tcp') to a number
21 22 23 24
ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order
htons(), htonl() -- convert 16, 32 bit int from host to network byte order
inet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format
inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89)
25 26
socket.getdefaulttimeout() -- get the default timeout value
socket.setdefaulttimeout() -- set the default timeout value
27 28
create_connection() -- connects to an address, with an optional timeout and
                       optional source address.
29 30 31 32 33 34 35

 [*] not available on all platforms!

Special objects:

SocketType -- type object for socket objects
error -- exception raised for I/O errors
36
has_ipv6 -- boolean value indicating if IPv6 is supported
37 38 39 40 41 42 43 44 45 46

Integer constants:

AF_INET, AF_UNIX -- socket domains (first argument to socket() call)
SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument)

Many other constants may be defined; these may be used in calls to
the setsockopt() and getsockopt() methods.
"""

47
import _socket
48
from _socket import *
49

50
import os, sys, io, selectors
51
from enum import IntEnum
52

53
try:
54
    import errno
55
except ImportError:
56 57
    errno = None
EBADF = getattr(errno, 'EBADF', 9)
58 59
EAGAIN = getattr(errno, 'EAGAIN', 11)
EWOULDBLOCK = getattr(errno, 'EWOULDBLOCK', 11)
60

Benjamin Peterson's avatar
Benjamin Peterson committed
61
__all__ = ["getfqdn", "create_connection"]
62
__all__.extend(os._get_exports_list(_socket))
63

64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
# Set up the socket.AF_* socket.SOCK_* constants as members of IntEnums for
# nicer string representations.
# Note that _socket only knows about the integer values. The public interface
# in this module understands the enums and translates them back from integers
# where needed (e.g. .family property of a socket object).
AddressFamily = IntEnum('AddressFamily',
                        {name: value for name, value in globals().items()
                         if name.isupper() and name.startswith('AF_')})
globals().update(AddressFamily.__members__)

SocketType = IntEnum('SocketType',
                     {name: value for name, value in globals().items()
                      if name.isupper() and name.startswith('SOCK_')})
globals().update(SocketType.__members__)

79 80 81 82 83

_LOCALHOST    = '127.0.0.1'
_LOCALHOST_V6 = '::1'


84 85 86 87 88 89 90 91 92
def _intenum_converter(value, enum_klass):
    """Convert a numeric family value to an IntEnum member.

    If it's not a known member, return the numeric value itself.
    """
    try:
        return enum_klass(value)
    except ValueError:
        return value
93 94

_realsocket = socket
95

96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
# WSA error codes
if sys.platform.lower().startswith("win"):
    errorTab = {}
    errorTab[10004] = "The operation was interrupted."
    errorTab[10009] = "A bad file handle was passed."
    errorTab[10013] = "Permission denied."
    errorTab[10014] = "A fault occurred on the network??" # WSAEFAULT
    errorTab[10022] = "An invalid operation was attempted."
    errorTab[10035] = "The socket operation would block"
    errorTab[10036] = "A blocking operation is already in progress."
    errorTab[10048] = "The network address is in use."
    errorTab[10054] = "The connection has been reset."
    errorTab[10058] = "The network has been shut down."
    errorTab[10060] = "The operation timed out."
    errorTab[10061] = "Connection refused."
    errorTab[10063] = "The name is too long."
    errorTab[10064] = "The host is down."
    errorTab[10065] = "The host is unreachable."
114
    __all__.append("errorTab")
115

116

117 118 119
class _GiveupOnSendfile(Exception): pass


120 121 122 123
class socket(_socket.socket):

    """A subclass of _socket.socket adding the makefile() method."""

124
    __slots__ = ["__weakref__", "_io_refs", "_closed"]
125

126
    def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None):
127 128 129 130
        # For user code address family and type values are IntEnum members, but
        # for the underlying _socket.socket they're just integers. The
        # constructor of _socket.socket converts the given argument to an
        # integer automatically.
131
        _socket.socket.__init__(self, family, type, proto, fileno)
132 133
        self._io_refs = 0
        self._closed = False
134

135 136 137 138 139 140 141
    def __enter__(self):
        return self

    def __exit__(self, *args):
        if not self._closed:
            self.close()

142
    def __repr__(self):
143 144 145 146
        """Wrap __repr__() to reveal the real class name and socket
        address(es).
        """
        closed = getattr(self, '_closed', False)
147
        s = "<%s.%s%s fd=%i, family=%s, type=%s, proto=%i" \
148
            % (self.__class__.__module__,
149
               self.__class__.__qualname__,
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
               " [closed]" if closed else "",
               self.fileno(),
               self.family,
               self.type,
               self.proto)
        if not closed:
            try:
                laddr = self.getsockname()
                if laddr:
                    s += ", laddr=%s" % str(laddr)
            except error:
                pass
            try:
                raddr = self.getpeername()
                if raddr:
                    s += ", raddr=%s" % str(raddr)
            except error:
                pass
        s += '>'
169 170
        return s

171 172 173
    def __getstate__(self):
        raise TypeError("Cannot serialize socket object")

174 175 176
    def dup(self):
        """dup() -> socket object

177 178
        Duplicate the socket. Return a new socket object connected to the same
        system resource. The new socket is non-inheritable.
179 180 181 182 183 184
        """
        fd = dup(self.fileno())
        sock = self.__class__(self.family, self.type, self.proto, fileno=fd)
        sock.settimeout(self.gettimeout())
        return sock

185
    def accept(self):
186 187 188 189 190 191 192
        """accept() -> (socket object, address info)

        Wait for an incoming connection.  Return a new socket
        representing the connection, and the address of the client.
        For IP sockets, the address info is a pair (hostaddr, port).
        """
        fd, addr = self._accept()
193 194 195 196 197 198 199
        sock = socket(self.family, self.type, self.proto, fileno=fd)
        # Issue #7995: if no default timeout is set and the listening
        # socket had a (non-zero) timeout, force the new socket in blocking
        # mode to override platform-specific socket flags inheritance.
        if getdefaulttimeout() is None and self.gettimeout():
            sock.setblocking(True)
        return sock, addr
200 201

    def makefile(self, mode="r", buffering=None, *,
202
                 encoding=None, errors=None, newline=None):
203
        """makefile(...) -> an I/O stream connected to the socket
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220

        The arguments are as for io.open() after the filename,
        except the only mode characters supported are 'r', 'w' and 'b'.
        The semantics are similar too.  (XXX refactor to share code?)
        """
        for c in mode:
            if c not in {"r", "w", "b"}:
                raise ValueError("invalid mode %r (only r, w, b allowed)")
        writing = "w" in mode
        reading = "r" in mode or not writing
        assert reading or writing
        binary = "b" in mode
        rawmode = ""
        if reading:
            rawmode += "r"
        if writing:
            rawmode += "w"
221 222
        raw = SocketIO(self, rawmode)
        self._io_refs += 1
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
        if buffering is None:
            buffering = -1
        if buffering < 0:
            buffering = io.DEFAULT_BUFFER_SIZE
        if buffering == 0:
            if not binary:
                raise ValueError("unbuffered streams must be binary")
            return raw
        if reading and writing:
            buffer = io.BufferedRWPair(raw, raw, buffering)
        elif reading:
            buffer = io.BufferedReader(raw, buffering)
        else:
            assert writing
            buffer = io.BufferedWriter(raw, buffering)
        if binary:
            return buffer
240
        text = io.TextIOWrapper(buffer, encoding, errors, newline)
241
        text.mode = mode
242 243
        return text

244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
    if hasattr(os, 'sendfile'):

        def _sendfile_use_sendfile(self, file, offset=0, count=None):
            self._check_sendfile_params(file, offset, count)
            sockno = self.fileno()
            try:
                fileno = file.fileno()
            except (AttributeError, io.UnsupportedOperation) as err:
                raise _GiveupOnSendfile(err)  # not a regular file
            try:
                fsize = os.fstat(fileno).st_size
            except OSError:
                raise _GiveupOnSendfile(err)  # not a regular file
            if not fsize:
                return 0  # empty file
            blocksize = fsize if not count else count

            timeout = self.gettimeout()
            if timeout == 0:
                raise ValueError("non-blocking sockets are not supported")
            # poll/select have the advantage of not requiring any
            # extra file descriptor, contrarily to epoll/kqueue
            # (also, they require a single syscall).
            if hasattr(selectors, 'PollSelector'):
                selector = selectors.PollSelector()
            else:
                selector = selectors.SelectSelector()
            selector.register(sockno, selectors.EVENT_WRITE)

            total_sent = 0
            # localize variable access to minimize overhead
            selector_select = selector.select
            os_sendfile = os.sendfile
            try:
                while True:
                    if timeout and not selector_select(timeout):
                        raise _socket.timeout('timed out')
                    if count:
                        blocksize = count - total_sent
                        if blocksize <= 0:
                            break
                    try:
                        sent = os_sendfile(sockno, fileno, offset, blocksize)
                    except BlockingIOError:
                        if not timeout:
                            # Block until the socket is ready to send some
                            # data; avoids hogging CPU resources.
                            selector_select()
                        continue
                    except OSError as err:
                        if total_sent == 0:
                            # We can get here for different reasons, the main
                            # one being 'file' is not a regular mmap(2)-like
                            # file, in which case we'll fall back on using
                            # plain send().
                            raise _GiveupOnSendfile(err)
                        raise err from None
                    else:
                        if sent == 0:
                            break  # EOF
                        offset += sent
                        total_sent += sent
                return total_sent
            finally:
                if total_sent > 0 and hasattr(file, 'seek'):
                    file.seek(offset)
    else:
        def _sendfile_use_sendfile(self, file, offset=0, count=None):
            raise _GiveupOnSendfile(
                "os.sendfile() not available on this platform")

    def _sendfile_use_send(self, file, offset=0, count=None):
        self._check_sendfile_params(file, offset, count)
        if self.gettimeout() == 0:
            raise ValueError("non-blocking sockets are not supported")
        if offset:
            file.seek(offset)
        blocksize = min(count, 8192) if count else 8192
        total_sent = 0
        # localize variable access to minimize overhead
        file_read = file.read
        sock_send = self.send
        try:
            while True:
                if count:
                    blocksize = min(count - total_sent, blocksize)
                    if blocksize <= 0:
                        break
                data = memoryview(file_read(blocksize))
                if not data:
                    break  # EOF
                while True:
                    try:
                        sent = sock_send(data)
                    except BlockingIOError:
                        continue
                    else:
                        total_sent += sent
                        if sent < len(data):
                            data = data[sent:]
                        else:
                            break
            return total_sent
        finally:
            if total_sent > 0 and hasattr(file, 'seek'):
                file.seek(offset + total_sent)

    def _check_sendfile_params(self, file, offset, count):
        if 'b' not in getattr(file, 'mode', 'b'):
            raise ValueError("file should be opened in binary mode")
        if not self.type & SOCK_STREAM:
            raise ValueError("only SOCK_STREAM type sockets are supported")
        if count is not None:
            if not isinstance(count, int):
                raise TypeError(
                    "count must be a positive integer (got {!r})".format(count))
            if count <= 0:
                raise ValueError(
                    "count must be a positive integer (got {!r})".format(count))

    def sendfile(self, file, offset=0, count=None):
        """sendfile(file[, offset[, count]]) -> sent

        Send a file until EOF is reached by using high-performance
        os.sendfile() and return the total number of bytes which
        were sent.
        *file* must be a regular file object opened in binary mode.
        If os.sendfile() is not available (e.g. Windows) or file is
        not a regular file socket.send() will be used instead.
        *offset* tells from where to start reading the file.
        If specified, *count* is the total number of bytes to transmit
        as opposed to sending the file until EOF is reached.
        File position is updated on return or also in case of error in
        which case file.tell() can be used to figure out the number of
        bytes which were sent.
        The socket must be of SOCK_STREAM type.
        Non-blocking sockets are not supported.
        """
        try:
            return self._sendfile_use_sendfile(file, offset, count)
        except _GiveupOnSendfile:
            return self._sendfile_use_send(file, offset, count)

387 388 389 390 391 392
    def _decref_socketios(self):
        if self._io_refs > 0:
            self._io_refs -= 1
        if self._closed:
            self.close()

393
    def _real_close(self, _ss=_socket.socket):
Benjamin Peterson's avatar
Benjamin Peterson committed
394
        # This function should not reference any globals. See issue #808164.
395
        _ss.close(self)
396

397
    def close(self):
Benjamin Peterson's avatar
Benjamin Peterson committed
398
        # This function should not reference any globals. See issue #808164.
399
        self._closed = True
400
        if self._io_refs <= 0:
401
            self._real_close()
402

403 404 405 406 407 408 409 410 411 412
    def detach(self):
        """detach() -> file descriptor

        Close the socket object without closing the underlying file descriptor.
        The object cannot be used after this call, but the file descriptor
        can be reused for other purposes.  The file descriptor is returned.
        """
        self._closed = True
        return super().detach()

413 414 415 416 417 418 419 420 421 422 423 424
    @property
    def family(self):
        """Read-only access to the address family for this socket.
        """
        return _intenum_converter(super().family, AddressFamily)

    @property
    def type(self):
        """Read-only access to the socket type.
        """
        return _intenum_converter(super().type, SocketType)

425 426 427 428 429 430 431 432 433 434 435 436 437
    if os.name == 'nt':
        def get_inheritable(self):
            return os.get_handle_inheritable(self.fileno())
        def set_inheritable(self, inheritable):
            os.set_handle_inheritable(self.fileno(), inheritable)
    else:
        def get_inheritable(self):
            return os.get_inheritable(self.fileno())
        def set_inheritable(self, inheritable):
            os.set_inheritable(self.fileno(), inheritable)
    get_inheritable.__doc__ = "Get the inheritable flag of the socket"
    set_inheritable.__doc__ = "Set the inheritable flag of the socket"

438 439 440 441 442 443 444 445
def fromfd(fd, family, type, proto=0):
    """ fromfd(fd, family, type[, proto]) -> socket object

    Create a socket object from a duplicate of the given file
    descriptor.  The remaining arguments are the same as for socket().
    """
    nfd = dup(fd)
    return socket(family, type, proto, nfd)
446

447 448 449 450 451 452 453 454
if hasattr(_socket.socket, "share"):
    def fromshare(info):
        """ fromshare(info) -> socket object

        Create a socket object from a the bytes object returned by
        socket.share(pid).
        """
        return socket(0, 0, 0, info)
455

456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
if hasattr(_socket, "socketpair"):

    def socketpair(family=None, type=SOCK_STREAM, proto=0):
        """socketpair([family[, type[, proto]]]) -> (socket object, socket object)

        Create a pair of socket objects from the sockets returned by the platform
        socketpair() function.
        The arguments are the same as for socket() except the default family is
        AF_UNIX if defined on the platform; otherwise, the default is AF_INET.
        """
        if family is None:
            try:
                family = AF_UNIX
            except NameError:
                family = AF_INET
        a, b = _socket.socketpair(family, type, proto)
        a = socket(family, type, proto, a.detach())
        b = socket(family, type, proto, b.detach())
        return a, b

476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
else:

    # Origin: https://gist.github.com/4325783, by Geert Jansen.  Public domain.
    def socketpair(family=AF_INET, type=SOCK_STREAM, proto=0):
        if family == AF_INET:
            host = _LOCALHOST
        elif family == AF_INET6:
            host = _LOCALHOST_V6
        else:
            raise ValueError("Only AF_INET and AF_INET6 socket address families "
                             "are supported")
        if type != SOCK_STREAM:
            raise ValueError("Only SOCK_STREAM socket type is supported")
        if proto != 0:
            raise ValueError("Only protocol zero is supported")

        # We create a connected TCP socket. Note the trick with
        # setblocking(False) that prevents us from having to create a thread.
        lsock = socket(family, type, proto)
        try:
            lsock.bind((host, 0))
            lsock.listen()
            # On IPv6, ignore flow_info and scope_id
            addr, port = lsock.getsockname()[:2]
            csock = socket(family, type, proto)
            try:
                csock.setblocking(False)
                try:
                    csock.connect((addr, port))
                except (BlockingIOError, InterruptedError):
                    pass
                csock.setblocking(True)
                ssock, _ = lsock.accept()
            except:
                csock.close()
                raise
        finally:
            lsock.close()
        return (ssock, csock)

socketpair.__doc__ = """socketpair([family[, type[, proto]]]) -> (socket object, socket object)
Create a pair of socket objects from the sockets returned by the platform
socketpair() function.
The arguments are the same as for socket() except the default family is AF_UNIX
if defined on the platform; otherwise, the default is AF_INET.
"""
522

523 524
_blocking_errnos = { EAGAIN, EWOULDBLOCK }

525 526 527 528 529 530 531 532
class SocketIO(io.RawIOBase):

    """Raw I/O implementation for stream sockets.

    This class supports the makefile() method on sockets.  It provides
    the raw I/O interface on top of a socket object.
    """

533 534 535 536 537 538 539
    # One might wonder why not let FileIO do the job instead.  There are two
    # main reasons why FileIO is not adapted:
    # - it wouldn't work under Windows (where you can't used read() and
    #   write() on a socket handle)
    # - it wouldn't work with socket timeouts (FileIO would ignore the
    #   timeout and consider the socket non-blocking)

540 541
    # XXX More docs

542
    def __init__(self, sock, mode):
543
        if mode not in ("r", "w", "rw", "rb", "wb", "rwb"):
544
            raise ValueError("invalid mode: %r" % mode)
545 546
        io.RawIOBase.__init__(self)
        self._sock = sock
547 548
        if "b" not in mode:
            mode += "b"
549
        self._mode = mode
550 551
        self._reading = "r" in mode
        self._writing = "w" in mode
552
        self._timeout_occurred = False
553 554

    def readinto(self, b):
555 556 557 558 559 560 561
        """Read up to len(b) bytes into the writable buffer *b* and return
        the number of bytes read.  If the socket is non-blocking and no bytes
        are available, None is returned.

        If *b* is non-empty, a 0 return value indicates that the connection
        was shutdown at the other end.
        """
562 563
        self._checkClosed()
        self._checkReadable()
564
        if self._timeout_occurred:
565
            raise OSError("cannot read from timed out object")
566 567 568
        while True:
            try:
                return self._sock.recv_into(b)
569 570 571
            except timeout:
                self._timeout_occurred = True
                raise
572 573
            except InterruptedError:
                continue
574
            except error as e:
575
                if e.args[0] in _blocking_errnos:
576
                    return None
577
                raise
578 579

    def write(self, b):
580 581 582 583 584
        """Write the given bytes or bytearray object *b* to the socket
        and return the number of bytes written.  This can be less than
        len(b) if not all data could be written.  If the socket is
        non-blocking and no bytes could be written None is returned.
        """
585 586
        self._checkClosed()
        self._checkWritable()
587 588 589 590 591 592 593
        try:
            return self._sock.send(b)
        except error as e:
            # XXX what about EINTR?
            if e.args[0] in _blocking_errnos:
                return None
            raise
594 595

    def readable(self):
596 597
        """True if the SocketIO is open for reading.
        """
598 599 600
        if self.closed:
            raise ValueError("I/O operation on closed socket.")
        return self._reading
601 602

    def writable(self):
603 604
        """True if the SocketIO is open for writing.
        """
605 606 607 608 609 610 611 612 613 614
        if self.closed:
            raise ValueError("I/O operation on closed socket.")
        return self._writing

    def seekable(self):
        """True if the SocketIO is open for seeking.
        """
        if self.closed:
            raise ValueError("I/O operation on closed socket.")
        return super().seekable()
615 616

    def fileno(self):
617 618
        """Return the file descriptor of the underlying socket.
        """
619
        self._checkClosed()
620 621
        return self._sock.fileno()

622 623
    @property
    def name(self):
624 625 626 627
        if not self.closed:
            return self.fileno()
        else:
            return -1
628 629 630 631 632

    @property
    def mode(self):
        return self._mode

633
    def close(self):
634 635 636
        """Close the SocketIO object.  This doesn't close the underlying
        socket, except if all references to it have disappeared.
        """
637 638 639
        if self.closed:
            return
        io.RawIOBase.close(self)
640 641
        self._sock._decref_socketios()
        self._sock = None
642

643 644 645 646 647 648 649 650

def getfqdn(name=''):
    """Get fully qualified domain name from name.

    An empty argument is interpreted as meaning the local host.

    First the hostname returned by gethostbyaddr() is checked, then
    possibly existing aliases. In case no FQDN is available, hostname
651
    from gethostname() is returned.
652 653
    """
    name = name.strip()
654
    if not name or name == '0.0.0.0':
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
        name = gethostname()
    try:
        hostname, aliases, ipaddrs = gethostbyaddr(name)
    except error:
        pass
    else:
        aliases.insert(0, hostname)
        for name in aliases:
            if '.' in name:
                break
        else:
            name = hostname
    return name


Georg Brandl's avatar
Georg Brandl committed
670
_GLOBAL_DEFAULT_TIMEOUT = object()
671

672 673
def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT,
                      source_address=None):
Georg Brandl's avatar
Georg Brandl committed
674 675 676 677 678 679 680
    """Connect to *address* and return the socket object.

    Convenience function.  Connect to *address* (a 2-tuple ``(host,
    port)``) and return the socket object.  Passing the optional
    *timeout* parameter will set the timeout on the socket instance
    before attempting to connect.  If no *timeout* is supplied, the
    global default timeout setting returned by :func:`getdefaulttimeout`
681 682 683
    is used.  If *source_address* is set it must be a tuple of (host, port)
    for the socket to bind as a source address before making the connection.
    An host of '' or port 0 tells the OS to use the default.
684 685 686
    """

    host, port = address
687
    err = None
688 689 690 691 692
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
        af, socktype, proto, canonname, sa = res
        sock = None
        try:
            sock = socket(af, socktype, proto)
Georg Brandl's avatar
Georg Brandl committed
693
            if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
694
                sock.settimeout(timeout)
695 696
            if source_address:
                sock.bind(source_address)
697 698 699
            sock.connect(sa)
            return sock

700 701
        except error as _:
            err = _
702 703 704
            if sock is not None:
                sock.close()

705 706 707 708
    if err is not None:
        raise err
    else:
        raise error("getaddrinfo returns an empty list")
709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732

def getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):
    """Resolve host and port into list of address info entries.

    Translate the host/port argument into a sequence of 5-tuples that contain
    all the necessary arguments for creating a socket connected to that service.
    host is a domain name, a string representation of an IPv4/v6 address or
    None. port is a string service name such as 'http', a numeric port number or
    None. By passing None as the value of host and port, you can pass NULL to
    the underlying C API.

    The family, type and proto arguments can be optionally specified in order to
    narrow the list of addresses returned. Passing zero as a value for each of
    these arguments selects the full range of results.
    """
    # We override this function since we want to translate the numeric family
    # and socket type values to enum constants.
    addrlist = []
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
        af, socktype, proto, canonname, sa = res
        addrlist.append((_intenum_converter(af, AddressFamily),
                         _intenum_converter(socktype, SocketType),
                         proto, canonname, sa))
    return addrlist