PageRenderTime 57ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/Lib/socket.py

https://bitbucket.org/ncoghlan/cpython_sandbox
Python | 737 lines | 709 code | 1 blank | 27 comment | 1 complexity | dbfb74ca9970ab06710683cfa9813cc9 MD5 | raw file
Possible License(s): BSD-3-Clause, Unlicense, CC-BY-SA-3.0, 0BSD
  1. # Wrapper module for _socket, providing some additional facilities
  2. # implemented in Python.
  3. """\
  4. This module provides socket operations and some related functions.
  5. On Unix, it supports IP (Internet Protocol) and Unix domain sockets.
  6. On other systems, it only supports IP. Functions specific for a
  7. socket are available as methods of the socket object.
  8. Functions:
  9. socket() -- create a new socket object
  10. socketpair() -- create a pair of new socket objects [*]
  11. fromfd() -- create a socket object from an open file descriptor [*]
  12. fromshare() -- create a socket object from data received from socket.share() [*]
  13. gethostname() -- return the current hostname
  14. gethostbyname() -- map a hostname to its IP number
  15. gethostbyaddr() -- map an IP number or hostname to DNS info
  16. getservbyname() -- map a service name and a protocol name to a port number
  17. getprotobyname() -- map a protocol name (e.g. 'tcp') to a number
  18. ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order
  19. htons(), htonl() -- convert 16, 32 bit int from host to network byte order
  20. inet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format
  21. inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89)
  22. socket.getdefaulttimeout() -- get the default timeout value
  23. socket.setdefaulttimeout() -- set the default timeout value
  24. create_connection() -- connects to an address, with an optional timeout and
  25. optional source address.
  26. [*] not available on all platforms!
  27. Special objects:
  28. SocketType -- type object for socket objects
  29. error -- exception raised for I/O errors
  30. has_ipv6 -- boolean value indicating if IPv6 is supported
  31. IntEnum constants:
  32. AF_INET, AF_UNIX -- socket domains (first argument to socket() call)
  33. SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument)
  34. Integer constants:
  35. Many other constants may be defined; these may be used in calls to
  36. the setsockopt() and getsockopt() methods.
  37. """
  38. import _socket
  39. from _socket import *
  40. import os, sys, io, selectors
  41. from enum import IntEnum
  42. try:
  43. import errno
  44. except ImportError:
  45. errno = None
  46. EBADF = getattr(errno, 'EBADF', 9)
  47. EAGAIN = getattr(errno, 'EAGAIN', 11)
  48. EWOULDBLOCK = getattr(errno, 'EWOULDBLOCK', 11)
  49. __all__ = ["fromfd", "getfqdn", "create_connection",
  50. "AddressFamily", "SocketKind"]
  51. __all__.extend(os._get_exports_list(_socket))
  52. # Set up the socket.AF_* socket.SOCK_* constants as members of IntEnums for
  53. # nicer string representations.
  54. # Note that _socket only knows about the integer values. The public interface
  55. # in this module understands the enums and translates them back from integers
  56. # where needed (e.g. .family property of a socket object).
  57. IntEnum._convert(
  58. 'AddressFamily',
  59. __name__,
  60. lambda C: C.isupper() and C.startswith('AF_'))
  61. IntEnum._convert(
  62. 'SocketKind',
  63. __name__,
  64. lambda C: C.isupper() and C.startswith('SOCK_'))
  65. _LOCALHOST = '127.0.0.1'
  66. _LOCALHOST_V6 = '::1'
  67. def _intenum_converter(value, enum_klass):
  68. """Convert a numeric family value to an IntEnum member.
  69. If it's not a known member, return the numeric value itself.
  70. """
  71. try:
  72. return enum_klass(value)
  73. except ValueError:
  74. return value
  75. _realsocket = socket
  76. # WSA error codes
  77. if sys.platform.lower().startswith("win"):
  78. errorTab = {}
  79. errorTab[10004] = "The operation was interrupted."
  80. errorTab[10009] = "A bad file handle was passed."
  81. errorTab[10013] = "Permission denied."
  82. errorTab[10014] = "A fault occurred on the network??" # WSAEFAULT
  83. errorTab[10022] = "An invalid operation was attempted."
  84. errorTab[10035] = "The socket operation would block"
  85. errorTab[10036] = "A blocking operation is already in progress."
  86. errorTab[10048] = "The network address is in use."
  87. errorTab[10054] = "The connection has been reset."
  88. errorTab[10058] = "The network has been shut down."
  89. errorTab[10060] = "The operation timed out."
  90. errorTab[10061] = "Connection refused."
  91. errorTab[10063] = "The name is too long."
  92. errorTab[10064] = "The host is down."
  93. errorTab[10065] = "The host is unreachable."
  94. __all__.append("errorTab")
  95. class _GiveupOnSendfile(Exception): pass
  96. class socket(_socket.socket):
  97. """A subclass of _socket.socket adding the makefile() method."""
  98. __slots__ = ["__weakref__", "_io_refs", "_closed"]
  99. def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None):
  100. # For user code address family and type values are IntEnum members, but
  101. # for the underlying _socket.socket they're just integers. The
  102. # constructor of _socket.socket converts the given argument to an
  103. # integer automatically.
  104. _socket.socket.__init__(self, family, type, proto, fileno)
  105. self._io_refs = 0
  106. self._closed = False
  107. def __enter__(self):
  108. return self
  109. def __exit__(self, *args):
  110. if not self._closed:
  111. self.close()
  112. def __repr__(self):
  113. """Wrap __repr__() to reveal the real class name and socket
  114. address(es).
  115. """
  116. closed = getattr(self, '_closed', False)
  117. s = "<%s.%s%s fd=%i, family=%s, type=%s, proto=%i" \
  118. % (self.__class__.__module__,
  119. self.__class__.__qualname__,
  120. " [closed]" if closed else "",
  121. self.fileno(),
  122. self.family,
  123. self.type,
  124. self.proto)
  125. if not closed:
  126. try:
  127. laddr = self.getsockname()
  128. if laddr:
  129. s += ", laddr=%s" % str(laddr)
  130. except error:
  131. pass
  132. try:
  133. raddr = self.getpeername()
  134. if raddr:
  135. s += ", raddr=%s" % str(raddr)
  136. except error:
  137. pass
  138. s += '>'
  139. return s
  140. def __getstate__(self):
  141. raise TypeError("Cannot serialize socket object")
  142. def dup(self):
  143. """dup() -> socket object
  144. Duplicate the socket. Return a new socket object connected to the same
  145. system resource. The new socket is non-inheritable.
  146. """
  147. fd = dup(self.fileno())
  148. sock = self.__class__(self.family, self.type, self.proto, fileno=fd)
  149. sock.settimeout(self.gettimeout())
  150. return sock
  151. def accept(self):
  152. """accept() -> (socket object, address info)
  153. Wait for an incoming connection. Return a new socket
  154. representing the connection, and the address of the client.
  155. For IP sockets, the address info is a pair (hostaddr, port).
  156. """
  157. fd, addr = self._accept()
  158. # If our type has the SOCK_NONBLOCK flag, we shouldn't pass it onto the
  159. # new socket. We do not currently allow passing SOCK_NONBLOCK to
  160. # accept4, so the returned socket is always blocking.
  161. type = self.type & ~globals().get("SOCK_NONBLOCK", 0)
  162. sock = socket(self.family, type, self.proto, fileno=fd)
  163. # Issue #7995: if no default timeout is set and the listening
  164. # socket had a (non-zero) timeout, force the new socket in blocking
  165. # mode to override platform-specific socket flags inheritance.
  166. if getdefaulttimeout() is None and self.gettimeout():
  167. sock.setblocking(True)
  168. return sock, addr
  169. def makefile(self, mode="r", buffering=None, *,
  170. encoding=None, errors=None, newline=None):
  171. """makefile(...) -> an I/O stream connected to the socket
  172. The arguments are as for io.open() after the filename, except the only
  173. supported mode values are 'r' (default), 'w' and 'b'.
  174. """
  175. # XXX refactor to share code?
  176. if not set(mode) <= {"r", "w", "b"}:
  177. raise ValueError("invalid mode %r (only r, w, b allowed)" % (mode,))
  178. writing = "w" in mode
  179. reading = "r" in mode or not writing
  180. assert reading or writing
  181. binary = "b" in mode
  182. rawmode = ""
  183. if reading:
  184. rawmode += "r"
  185. if writing:
  186. rawmode += "w"
  187. raw = SocketIO(self, rawmode)
  188. self._io_refs += 1
  189. if buffering is None:
  190. buffering = -1
  191. if buffering < 0:
  192. buffering = io.DEFAULT_BUFFER_SIZE
  193. if buffering == 0:
  194. if not binary:
  195. raise ValueError("unbuffered streams must be binary")
  196. return raw
  197. if reading and writing:
  198. buffer = io.BufferedRWPair(raw, raw, buffering)
  199. elif reading:
  200. buffer = io.BufferedReader(raw, buffering)
  201. else:
  202. assert writing
  203. buffer = io.BufferedWriter(raw, buffering)
  204. if binary:
  205. return buffer
  206. text = io.TextIOWrapper(buffer, encoding, errors, newline)
  207. text.mode = mode
  208. return text
  209. if hasattr(os, 'sendfile'):
  210. def _sendfile_use_sendfile(self, file, offset=0, count=None):
  211. self._check_sendfile_params(file, offset, count)
  212. sockno = self.fileno()
  213. try:
  214. fileno = file.fileno()
  215. except (AttributeError, io.UnsupportedOperation) as err:
  216. raise _GiveupOnSendfile(err) # not a regular file
  217. try:
  218. fsize = os.fstat(fileno).st_size
  219. except OSError:
  220. raise _GiveupOnSendfile(err) # not a regular file
  221. if not fsize:
  222. return 0 # empty file
  223. blocksize = fsize if not count else count
  224. timeout = self.gettimeout()
  225. if timeout == 0:
  226. raise ValueError("non-blocking sockets are not supported")
  227. # poll/select have the advantage of not requiring any
  228. # extra file descriptor, contrarily to epoll/kqueue
  229. # (also, they require a single syscall).
  230. if hasattr(selectors, 'PollSelector'):
  231. selector = selectors.PollSelector()
  232. else:
  233. selector = selectors.SelectSelector()
  234. selector.register(sockno, selectors.EVENT_WRITE)
  235. total_sent = 0
  236. # localize variable access to minimize overhead
  237. selector_select = selector.select
  238. os_sendfile = os.sendfile
  239. try:
  240. while True:
  241. if timeout and not selector_select(timeout):
  242. raise _socket.timeout('timed out')
  243. if count:
  244. blocksize = count - total_sent
  245. if blocksize <= 0:
  246. break
  247. try:
  248. sent = os_sendfile(sockno, fileno, offset, blocksize)
  249. except BlockingIOError:
  250. if not timeout:
  251. # Block until the socket is ready to send some
  252. # data; avoids hogging CPU resources.
  253. selector_select()
  254. continue
  255. except OSError as err:
  256. if total_sent == 0:
  257. # We can get here for different reasons, the main
  258. # one being 'file' is not a regular mmap(2)-like
  259. # file, in which case we'll fall back on using
  260. # plain send().
  261. raise _GiveupOnSendfile(err)
  262. raise err from None
  263. else:
  264. if sent == 0:
  265. break # EOF
  266. offset += sent
  267. total_sent += sent
  268. return total_sent
  269. finally:
  270. if total_sent > 0 and hasattr(file, 'seek'):
  271. file.seek(offset)
  272. else:
  273. def _sendfile_use_sendfile(self, file, offset=0, count=None):
  274. raise _GiveupOnSendfile(
  275. "os.sendfile() not available on this platform")
  276. def _sendfile_use_send(self, file, offset=0, count=None):
  277. self._check_sendfile_params(file, offset, count)
  278. if self.gettimeout() == 0:
  279. raise ValueError("non-blocking sockets are not supported")
  280. if offset:
  281. file.seek(offset)
  282. blocksize = min(count, 8192) if count else 8192
  283. total_sent = 0
  284. # localize variable access to minimize overhead
  285. file_read = file.read
  286. sock_send = self.send
  287. try:
  288. while True:
  289. if count:
  290. blocksize = min(count - total_sent, blocksize)
  291. if blocksize <= 0:
  292. break
  293. data = memoryview(file_read(blocksize))
  294. if not data:
  295. break # EOF
  296. while True:
  297. try:
  298. sent = sock_send(data)
  299. except BlockingIOError:
  300. continue
  301. else:
  302. total_sent += sent
  303. if sent < len(data):
  304. data = data[sent:]
  305. else:
  306. break
  307. return total_sent
  308. finally:
  309. if total_sent > 0 and hasattr(file, 'seek'):
  310. file.seek(offset + total_sent)
  311. def _check_sendfile_params(self, file, offset, count):
  312. if 'b' not in getattr(file, 'mode', 'b'):
  313. raise ValueError("file should be opened in binary mode")
  314. if not self.type & SOCK_STREAM:
  315. raise ValueError("only SOCK_STREAM type sockets are supported")
  316. if count is not None:
  317. if not isinstance(count, int):
  318. raise TypeError(
  319. "count must be a positive integer (got {!r})".format(count))
  320. if count <= 0:
  321. raise ValueError(
  322. "count must be a positive integer (got {!r})".format(count))
  323. def sendfile(self, file, offset=0, count=None):
  324. """sendfile(file[, offset[, count]]) -> sent
  325. Send a file until EOF is reached by using high-performance
  326. os.sendfile() and return the total number of bytes which
  327. were sent.
  328. *file* must be a regular file object opened in binary mode.
  329. If os.sendfile() is not available (e.g. Windows) or file is
  330. not a regular file socket.send() will be used instead.
  331. *offset* tells from where to start reading the file.
  332. If specified, *count* is the total number of bytes to transmit
  333. as opposed to sending the file until EOF is reached.
  334. File position is updated on return or also in case of error in
  335. which case file.tell() can be used to figure out the number of
  336. bytes which were sent.
  337. The socket must be of SOCK_STREAM type.
  338. Non-blocking sockets are not supported.
  339. """
  340. try:
  341. return self._sendfile_use_sendfile(file, offset, count)
  342. except _GiveupOnSendfile:
  343. return self._sendfile_use_send(file, offset, count)
  344. def _decref_socketios(self):
  345. if self._io_refs > 0:
  346. self._io_refs -= 1
  347. if self._closed:
  348. self.close()
  349. def _real_close(self, _ss=_socket.socket):
  350. # This function should not reference any globals. See issue #808164.
  351. _ss.close(self)
  352. def close(self):
  353. # This function should not reference any globals. See issue #808164.
  354. self._closed = True
  355. if self._io_refs <= 0:
  356. self._real_close()
  357. def detach(self):
  358. """detach() -> file descriptor
  359. Close the socket object without closing the underlying file descriptor.
  360. The object cannot be used after this call, but the file descriptor
  361. can be reused for other purposes. The file descriptor is returned.
  362. """
  363. self._closed = True
  364. return super().detach()
  365. @property
  366. def family(self):
  367. """Read-only access to the address family for this socket.
  368. """
  369. return _intenum_converter(super().family, AddressFamily)
  370. @property
  371. def type(self):
  372. """Read-only access to the socket type.
  373. """
  374. return _intenum_converter(super().type, SocketKind)
  375. if os.name == 'nt':
  376. def get_inheritable(self):
  377. return os.get_handle_inheritable(self.fileno())
  378. def set_inheritable(self, inheritable):
  379. os.set_handle_inheritable(self.fileno(), inheritable)
  380. else:
  381. def get_inheritable(self):
  382. return os.get_inheritable(self.fileno())
  383. def set_inheritable(self, inheritable):
  384. os.set_inheritable(self.fileno(), inheritable)
  385. get_inheritable.__doc__ = "Get the inheritable flag of the socket"
  386. set_inheritable.__doc__ = "Set the inheritable flag of the socket"
  387. def fromfd(fd, family, type, proto=0):
  388. """ fromfd(fd, family, type[, proto]) -> socket object
  389. Create a socket object from a duplicate of the given file
  390. descriptor. The remaining arguments are the same as for socket().
  391. """
  392. nfd = dup(fd)
  393. return socket(family, type, proto, nfd)
  394. if hasattr(_socket.socket, "share"):
  395. def fromshare(info):
  396. """ fromshare(info) -> socket object
  397. Create a socket object from the bytes object returned by
  398. socket.share(pid).
  399. """
  400. return socket(0, 0, 0, info)
  401. __all__.append("fromshare")
  402. if hasattr(_socket, "socketpair"):
  403. def socketpair(family=None, type=SOCK_STREAM, proto=0):
  404. """socketpair([family[, type[, proto]]]) -> (socket object, socket object)
  405. Create a pair of socket objects from the sockets returned by the platform
  406. socketpair() function.
  407. The arguments are the same as for socket() except the default family is
  408. AF_UNIX if defined on the platform; otherwise, the default is AF_INET.
  409. """
  410. if family is None:
  411. try:
  412. family = AF_UNIX
  413. except NameError:
  414. family = AF_INET
  415. a, b = _socket.socketpair(family, type, proto)
  416. a = socket(family, type, proto, a.detach())
  417. b = socket(family, type, proto, b.detach())
  418. return a, b
  419. else:
  420. # Origin: https://gist.github.com/4325783, by Geert Jansen. Public domain.
  421. def socketpair(family=AF_INET, type=SOCK_STREAM, proto=0):
  422. if family == AF_INET:
  423. host = _LOCALHOST
  424. elif family == AF_INET6:
  425. host = _LOCALHOST_V6
  426. else:
  427. raise ValueError("Only AF_INET and AF_INET6 socket address families "
  428. "are supported")
  429. if type != SOCK_STREAM:
  430. raise ValueError("Only SOCK_STREAM socket type is supported")
  431. if proto != 0:
  432. raise ValueError("Only protocol zero is supported")
  433. # We create a connected TCP socket. Note the trick with
  434. # setblocking(False) that prevents us from having to create a thread.
  435. lsock = socket(family, type, proto)
  436. try:
  437. lsock.bind((host, 0))
  438. lsock.listen()
  439. # On IPv6, ignore flow_info and scope_id
  440. addr, port = lsock.getsockname()[:2]
  441. csock = socket(family, type, proto)
  442. try:
  443. csock.setblocking(False)
  444. try:
  445. csock.connect((addr, port))
  446. except (BlockingIOError, InterruptedError):
  447. pass
  448. csock.setblocking(True)
  449. ssock, _ = lsock.accept()
  450. except:
  451. csock.close()
  452. raise
  453. finally:
  454. lsock.close()
  455. return (ssock, csock)
  456. socketpair.__doc__ = """socketpair([family[, type[, proto]]]) -> (socket object, socket object)
  457. Create a pair of socket objects from the sockets returned by the platform
  458. socketpair() function.
  459. The arguments are the same as for socket() except the default family is AF_UNIX
  460. if defined on the platform; otherwise, the default is AF_INET.
  461. """
  462. _blocking_errnos = { EAGAIN, EWOULDBLOCK }
  463. class SocketIO(io.RawIOBase):
  464. """Raw I/O implementation for stream sockets.
  465. This class supports the makefile() method on sockets. It provides
  466. the raw I/O interface on top of a socket object.
  467. """
  468. # One might wonder why not let FileIO do the job instead. There are two
  469. # main reasons why FileIO is not adapted:
  470. # - it wouldn't work under Windows (where you can't used read() and
  471. # write() on a socket handle)
  472. # - it wouldn't work with socket timeouts (FileIO would ignore the
  473. # timeout and consider the socket non-blocking)
  474. # XXX More docs
  475. def __init__(self, sock, mode):
  476. if mode not in ("r", "w", "rw", "rb", "wb", "rwb"):
  477. raise ValueError("invalid mode: %r" % mode)
  478. io.RawIOBase.__init__(self)
  479. self._sock = sock
  480. if "b" not in mode:
  481. mode += "b"
  482. self._mode = mode
  483. self._reading = "r" in mode
  484. self._writing = "w" in mode
  485. self._timeout_occurred = False
  486. def readinto(self, b):
  487. """Read up to len(b) bytes into the writable buffer *b* and return
  488. the number of bytes read. If the socket is non-blocking and no bytes
  489. are available, None is returned.
  490. If *b* is non-empty, a 0 return value indicates that the connection
  491. was shutdown at the other end.
  492. """
  493. self._checkClosed()
  494. self._checkReadable()
  495. if self._timeout_occurred:
  496. raise OSError("cannot read from timed out object")
  497. while True:
  498. try:
  499. return self._sock.recv_into(b)
  500. except timeout:
  501. self._timeout_occurred = True
  502. raise
  503. except error as e:
  504. if e.args[0] in _blocking_errnos:
  505. return None
  506. raise
  507. def write(self, b):
  508. """Write the given bytes or bytearray object *b* to the socket
  509. and return the number of bytes written. This can be less than
  510. len(b) if not all data could be written. If the socket is
  511. non-blocking and no bytes could be written None is returned.
  512. """
  513. self._checkClosed()
  514. self._checkWritable()
  515. try:
  516. return self._sock.send(b)
  517. except error as e:
  518. # XXX what about EINTR?
  519. if e.args[0] in _blocking_errnos:
  520. return None
  521. raise
  522. def readable(self):
  523. """True if the SocketIO is open for reading.
  524. """
  525. if self.closed:
  526. raise ValueError("I/O operation on closed socket.")
  527. return self._reading
  528. def writable(self):
  529. """True if the SocketIO is open for writing.
  530. """
  531. if self.closed:
  532. raise ValueError("I/O operation on closed socket.")
  533. return self._writing
  534. def seekable(self):
  535. """True if the SocketIO is open for seeking.
  536. """
  537. if self.closed:
  538. raise ValueError("I/O operation on closed socket.")
  539. return super().seekable()
  540. def fileno(self):
  541. """Return the file descriptor of the underlying socket.
  542. """
  543. self._checkClosed()
  544. return self._sock.fileno()
  545. @property
  546. def name(self):
  547. if not self.closed:
  548. return self.fileno()
  549. else:
  550. return -1
  551. @property
  552. def mode(self):
  553. return self._mode
  554. def close(self):
  555. """Close the SocketIO object. This doesn't close the underlying
  556. socket, except if all references to it have disappeared.
  557. """
  558. if self.closed:
  559. return
  560. io.RawIOBase.close(self)
  561. self._sock._decref_socketios()
  562. self._sock = None
  563. def getfqdn(name=''):
  564. """Get fully qualified domain name from name.
  565. An empty argument is interpreted as meaning the local host.
  566. First the hostname returned by gethostbyaddr() is checked, then
  567. possibly existing aliases. In case no FQDN is available, hostname
  568. from gethostname() is returned.
  569. """
  570. name = name.strip()
  571. if not name or name == '0.0.0.0':
  572. name = gethostname()
  573. try:
  574. hostname, aliases, ipaddrs = gethostbyaddr(name)
  575. except error:
  576. pass
  577. else:
  578. aliases.insert(0, hostname)
  579. for name in aliases:
  580. if '.' in name:
  581. break
  582. else:
  583. name = hostname
  584. return name
  585. _GLOBAL_DEFAULT_TIMEOUT = object()
  586. def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT,
  587. source_address=None):
  588. """Connect to *address* and return the socket object.
  589. Convenience function. Connect to *address* (a 2-tuple ``(host,
  590. port)``) and return the socket object. Passing the optional
  591. *timeout* parameter will set the timeout on the socket instance
  592. before attempting to connect. If no *timeout* is supplied, the
  593. global default timeout setting returned by :func:`getdefaulttimeout`
  594. is used. If *source_address* is set it must be a tuple of (host, port)
  595. for the socket to bind as a source address before making the connection.
  596. A host of '' or port 0 tells the OS to use the default.
  597. """
  598. host, port = address
  599. err = None
  600. for res in getaddrinfo(host, port, 0, SOCK_STREAM):
  601. af, socktype, proto, canonname, sa = res
  602. sock = None
  603. try:
  604. sock = socket(af, socktype, proto)
  605. if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
  606. sock.settimeout(timeout)
  607. if source_address:
  608. sock.bind(source_address)
  609. sock.connect(sa)
  610. return sock
  611. except error as _:
  612. err = _
  613. if sock is not None:
  614. sock.close()
  615. if err is not None:
  616. raise err
  617. else:
  618. raise error("getaddrinfo returns an empty list")
  619. def getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):
  620. """Resolve host and port into list of address info entries.
  621. Translate the host/port argument into a sequence of 5-tuples that contain
  622. all the necessary arguments for creating a socket connected to that service.
  623. host is a domain name, a string representation of an IPv4/v6 address or
  624. None. port is a string service name such as 'http', a numeric port number or
  625. None. By passing None as the value of host and port, you can pass NULL to
  626. the underlying C API.
  627. The family, type and proto arguments can be optionally specified in order to
  628. narrow the list of addresses returned. Passing zero as a value for each of
  629. these arguments selects the full range of results.
  630. """
  631. # We override this function since we want to translate the numeric family
  632. # and socket type values to enum constants.
  633. addrlist = []
  634. for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
  635. af, socktype, proto, canonname, sa = res
  636. addrlist.append((_intenum_converter(af, AddressFamily),
  637. _intenum_converter(socktype, SocketKind),
  638. proto, canonname, sa))
  639. return addrlist