(root)/
Python-3.12.0/
Lib/
socket.py
       1  # Wrapper module for _socket, providing some additional facilities
       2  # implemented in Python.
       3  
       4  """\
       5  This module provides socket operations and some related functions.
       6  On Unix, it supports IP (Internet Protocol) and Unix domain sockets.
       7  On other systems, it only supports IP. Functions specific for a
       8  socket are available as methods of the socket object.
       9  
      10  Functions:
      11  
      12  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  send_fds() -- Send file descriptor to the socket.
      16  recv_fds() -- Receive file descriptors from the socket.
      17  fromshare() -- create a socket object from data received from socket.share() [*]
      18  gethostname() -- return the current hostname
      19  gethostbyname() -- map a hostname to its IP number
      20  gethostbyaddr() -- map an IP number or hostname to DNS info
      21  getservbyname() -- map a service name and a protocol name to a port number
      22  getprotobyname() -- map a protocol name (e.g. 'tcp') to a number
      23  ntohs(), ntohl() -- convert 16, 32 bit int from network to host byte order
      24  htons(), htonl() -- convert 16, 32 bit int from host to network byte order
      25  inet_aton() -- convert IP addr string (123.45.67.89) to 32-bit packed format
      26  inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89)
      27  socket.getdefaulttimeout() -- get the default timeout value
      28  socket.setdefaulttimeout() -- set the default timeout value
      29  create_connection() -- connects to an address, with an optional timeout and
      30                         optional source address.
      31  create_server() -- create a TCP socket and bind it to a specified address.
      32  
      33   [*] not available on all platforms!
      34  
      35  Special objects:
      36  
      37  SocketType -- type object for socket objects
      38  error -- exception raised for I/O errors
      39  has_ipv6 -- boolean value indicating if IPv6 is supported
      40  
      41  IntEnum constants:
      42  
      43  AF_INET, AF_UNIX -- socket domains (first argument to socket() call)
      44  SOCK_STREAM, SOCK_DGRAM, SOCK_RAW -- socket types (second argument)
      45  
      46  Integer constants:
      47  
      48  Many other constants may be defined; these may be used in calls to
      49  the setsockopt() and getsockopt() methods.
      50  """
      51  
      52  import _socket
      53  from _socket import *
      54  
      55  import os, sys, io, selectors
      56  from enum import IntEnum, IntFlag
      57  
      58  try:
      59      import errno
      60  except ImportError:
      61      errno = None
      62  EBADF = getattr(errno, 'EBADF', 9)
      63  EAGAIN = getattr(errno, 'EAGAIN', 11)
      64  EWOULDBLOCK = getattr(errno, 'EWOULDBLOCK', 11)
      65  
      66  __all__ = ["fromfd", "getfqdn", "create_connection", "create_server",
      67             "has_dualstack_ipv6", "AddressFamily", "SocketKind"]
      68  __all__.extend(os._get_exports_list(_socket))
      69  
      70  # Set up the socket.AF_* socket.SOCK_* constants as members of IntEnums for
      71  # nicer string representations.
      72  # Note that _socket only knows about the integer values. The public interface
      73  # in this module understands the enums and translates them back from integers
      74  # where needed (e.g. .family property of a socket object).
      75  
      76  IntEnum._convert_(
      77          'AddressFamily',
      78          __name__,
      79          lambda C: C.isupper() and C.startswith('AF_'))
      80  
      81  IntEnum._convert_(
      82          'SocketKind',
      83          __name__,
      84          lambda C: C.isupper() and C.startswith('SOCK_'))
      85  
      86  IntFlag._convert_(
      87          'MsgFlag',
      88          __name__,
      89          lambda C: C.isupper() and C.startswith('MSG_'))
      90  
      91  IntFlag._convert_(
      92          'AddressInfo',
      93          __name__,
      94          lambda C: C.isupper() and C.startswith('AI_'))
      95  
      96  _LOCALHOST    = '127.0.0.1'
      97  _LOCALHOST_V6 = '::1'
      98  
      99  
     100  def _intenum_converter(value, enum_klass):
     101      """Convert a numeric family value to an IntEnum member.
     102  
     103      If it's not a known member, return the numeric value itself.
     104      """
     105      try:
     106          return enum_klass(value)
     107      except ValueError:
     108          return value
     109  
     110  
     111  # WSA error codes
     112  if sys.platform.lower().startswith("win"):
     113      errorTab = {}
     114      errorTab[6] = "Specified event object handle is invalid."
     115      errorTab[8] = "Insufficient memory available."
     116      errorTab[87] = "One or more parameters are invalid."
     117      errorTab[995] = "Overlapped operation aborted."
     118      errorTab[996] = "Overlapped I/O event object not in signaled state."
     119      errorTab[997] = "Overlapped operation will complete later."
     120      errorTab[10004] = "The operation was interrupted."
     121      errorTab[10009] = "A bad file handle was passed."
     122      errorTab[10013] = "Permission denied."
     123      errorTab[10014] = "A fault occurred on the network??"  # WSAEFAULT
     124      errorTab[10022] = "An invalid operation was attempted."
     125      errorTab[10024] = "Too many open files."
     126      errorTab[10035] = "The socket operation would block."
     127      errorTab[10036] = "A blocking operation is already in progress."
     128      errorTab[10037] = "Operation already in progress."
     129      errorTab[10038] = "Socket operation on nonsocket."
     130      errorTab[10039] = "Destination address required."
     131      errorTab[10040] = "Message too long."
     132      errorTab[10041] = "Protocol wrong type for socket."
     133      errorTab[10042] = "Bad protocol option."
     134      errorTab[10043] = "Protocol not supported."
     135      errorTab[10044] = "Socket type not supported."
     136      errorTab[10045] = "Operation not supported."
     137      errorTab[10046] = "Protocol family not supported."
     138      errorTab[10047] = "Address family not supported by protocol family."
     139      errorTab[10048] = "The network address is in use."
     140      errorTab[10049] = "Cannot assign requested address."
     141      errorTab[10050] = "Network is down."
     142      errorTab[10051] = "Network is unreachable."
     143      errorTab[10052] = "Network dropped connection on reset."
     144      errorTab[10053] = "Software caused connection abort."
     145      errorTab[10054] = "The connection has been reset."
     146      errorTab[10055] = "No buffer space available."
     147      errorTab[10056] = "Socket is already connected."
     148      errorTab[10057] = "Socket is not connected."
     149      errorTab[10058] = "The network has been shut down."
     150      errorTab[10059] = "Too many references."
     151      errorTab[10060] = "The operation timed out."
     152      errorTab[10061] = "Connection refused."
     153      errorTab[10062] = "Cannot translate name."
     154      errorTab[10063] = "The name is too long."
     155      errorTab[10064] = "The host is down."
     156      errorTab[10065] = "The host is unreachable."
     157      errorTab[10066] = "Directory not empty."
     158      errorTab[10067] = "Too many processes."
     159      errorTab[10068] = "User quota exceeded."
     160      errorTab[10069] = "Disk quota exceeded."
     161      errorTab[10070] = "Stale file handle reference."
     162      errorTab[10071] = "Item is remote."
     163      errorTab[10091] = "Network subsystem is unavailable."
     164      errorTab[10092] = "Winsock.dll version out of range."
     165      errorTab[10093] = "Successful WSAStartup not yet performed."
     166      errorTab[10101] = "Graceful shutdown in progress."
     167      errorTab[10102] = "No more results from WSALookupServiceNext."
     168      errorTab[10103] = "Call has been canceled."
     169      errorTab[10104] = "Procedure call table is invalid."
     170      errorTab[10105] = "Service provider is invalid."
     171      errorTab[10106] = "Service provider failed to initialize."
     172      errorTab[10107] = "System call failure."
     173      errorTab[10108] = "Service not found."
     174      errorTab[10109] = "Class type not found."
     175      errorTab[10110] = "No more results from WSALookupServiceNext."
     176      errorTab[10111] = "Call was canceled."
     177      errorTab[10112] = "Database query was refused."
     178      errorTab[11001] = "Host not found."
     179      errorTab[11002] = "Nonauthoritative host not found."
     180      errorTab[11003] = "This is a nonrecoverable error."
     181      errorTab[11004] = "Valid name, no data record requested type."
     182      errorTab[11005] = "QoS receivers."
     183      errorTab[11006] = "QoS senders."
     184      errorTab[11007] = "No QoS senders."
     185      errorTab[11008] = "QoS no receivers."
     186      errorTab[11009] = "QoS request confirmed."
     187      errorTab[11010] = "QoS admission error."
     188      errorTab[11011] = "QoS policy failure."
     189      errorTab[11012] = "QoS bad style."
     190      errorTab[11013] = "QoS bad object."
     191      errorTab[11014] = "QoS traffic control error."
     192      errorTab[11015] = "QoS generic error."
     193      errorTab[11016] = "QoS service type error."
     194      errorTab[11017] = "QoS flowspec error."
     195      errorTab[11018] = "Invalid QoS provider buffer."
     196      errorTab[11019] = "Invalid QoS filter style."
     197      errorTab[11020] = "Invalid QoS filter style."
     198      errorTab[11021] = "Incorrect QoS filter count."
     199      errorTab[11022] = "Invalid QoS object length."
     200      errorTab[11023] = "Incorrect QoS flow count."
     201      errorTab[11024] = "Unrecognized QoS object."
     202      errorTab[11025] = "Invalid QoS policy object."
     203      errorTab[11026] = "Invalid QoS flow descriptor."
     204      errorTab[11027] = "Invalid QoS provider-specific flowspec."
     205      errorTab[11028] = "Invalid QoS provider-specific filterspec."
     206      errorTab[11029] = "Invalid QoS shape discard mode object."
     207      errorTab[11030] = "Invalid QoS shaping rate object."
     208      errorTab[11031] = "Reserved policy QoS element type."
     209      __all__.append("errorTab")
     210  
     211  
     212  class ESC[4;38;5;81m_GiveupOnSendfile(ESC[4;38;5;149mException): pass
     213  
     214  
     215  class ESC[4;38;5;81msocket(ESC[4;38;5;149m_socketESC[4;38;5;149m.ESC[4;38;5;149msocket):
     216  
     217      """A subclass of _socket.socket adding the makefile() method."""
     218  
     219      __slots__ = ["__weakref__", "_io_refs", "_closed"]
     220  
     221      def __init__(self, family=-1, type=-1, proto=-1, fileno=None):
     222          # For user code address family and type values are IntEnum members, but
     223          # for the underlying _socket.socket they're just integers. The
     224          # constructor of _socket.socket converts the given argument to an
     225          # integer automatically.
     226          if fileno is None:
     227              if family == -1:
     228                  family = AF_INET
     229              if type == -1:
     230                  type = SOCK_STREAM
     231              if proto == -1:
     232                  proto = 0
     233          _socket.socket.__init__(self, family, type, proto, fileno)
     234          self._io_refs = 0
     235          self._closed = False
     236  
     237      def __enter__(self):
     238          return self
     239  
     240      def __exit__(self, *args):
     241          if not self._closed:
     242              self.close()
     243  
     244      def __repr__(self):
     245          """Wrap __repr__() to reveal the real class name and socket
     246          address(es).
     247          """
     248          closed = getattr(self, '_closed', False)
     249          s = "<%s.%s%s fd=%i, family=%s, type=%s, proto=%i" \
     250              % (self.__class__.__module__,
     251                 self.__class__.__qualname__,
     252                 " [closed]" if closed else "",
     253                 self.fileno(),
     254                 self.family,
     255                 self.type,
     256                 self.proto)
     257          if not closed:
     258              # getsockname and getpeername may not be available on WASI.
     259              try:
     260                  laddr = self.getsockname()
     261                  if laddr:
     262                      s += ", laddr=%s" % str(laddr)
     263              except (error, AttributeError):
     264                  pass
     265              try:
     266                  raddr = self.getpeername()
     267                  if raddr:
     268                      s += ", raddr=%s" % str(raddr)
     269              except (error, AttributeError):
     270                  pass
     271          s += '>'
     272          return s
     273  
     274      def __getstate__(self):
     275          raise TypeError(f"cannot pickle {self.__class__.__name__!r} object")
     276  
     277      def dup(self):
     278          """dup() -> socket object
     279  
     280          Duplicate the socket. Return a new socket object connected to the same
     281          system resource. The new socket is non-inheritable.
     282          """
     283          fd = dup(self.fileno())
     284          sock = self.__class__(self.family, self.type, self.proto, fileno=fd)
     285          sock.settimeout(self.gettimeout())
     286          return sock
     287  
     288      def accept(self):
     289          """accept() -> (socket object, address info)
     290  
     291          Wait for an incoming connection.  Return a new socket
     292          representing the connection, and the address of the client.
     293          For IP sockets, the address info is a pair (hostaddr, port).
     294          """
     295          fd, addr = self._accept()
     296          sock = socket(self.family, self.type, self.proto, fileno=fd)
     297          # Issue #7995: if no default timeout is set and the listening
     298          # socket had a (non-zero) timeout, force the new socket in blocking
     299          # mode to override platform-specific socket flags inheritance.
     300          if getdefaulttimeout() is None and self.gettimeout():
     301              sock.setblocking(True)
     302          return sock, addr
     303  
     304      def makefile(self, mode="r", buffering=None, *,
     305                   encoding=None, errors=None, newline=None):
     306          """makefile(...) -> an I/O stream connected to the socket
     307  
     308          The arguments are as for io.open() after the filename, except the only
     309          supported mode values are 'r' (default), 'w' and 'b'.
     310          """
     311          # XXX refactor to share code?
     312          if not set(mode) <= {"r", "w", "b"}:
     313              raise ValueError("invalid mode %r (only r, w, b allowed)" % (mode,))
     314          writing = "w" in mode
     315          reading = "r" in mode or not writing
     316          assert reading or writing
     317          binary = "b" in mode
     318          rawmode = ""
     319          if reading:
     320              rawmode += "r"
     321          if writing:
     322              rawmode += "w"
     323          raw = SocketIO(self, rawmode)
     324          self._io_refs += 1
     325          if buffering is None:
     326              buffering = -1
     327          if buffering < 0:
     328              buffering = io.DEFAULT_BUFFER_SIZE
     329          if buffering == 0:
     330              if not binary:
     331                  raise ValueError("unbuffered streams must be binary")
     332              return raw
     333          if reading and writing:
     334              buffer = io.BufferedRWPair(raw, raw, buffering)
     335          elif reading:
     336              buffer = io.BufferedReader(raw, buffering)
     337          else:
     338              assert writing
     339              buffer = io.BufferedWriter(raw, buffering)
     340          if binary:
     341              return buffer
     342          encoding = io.text_encoding(encoding)
     343          text = io.TextIOWrapper(buffer, encoding, errors, newline)
     344          text.mode = mode
     345          return text
     346  
     347      if hasattr(os, 'sendfile'):
     348  
     349          def _sendfile_use_sendfile(self, file, offset=0, count=None):
     350              self._check_sendfile_params(file, offset, count)
     351              sockno = self.fileno()
     352              try:
     353                  fileno = file.fileno()
     354              except (AttributeError, io.UnsupportedOperation) as err:
     355                  raise _GiveupOnSendfile(err)  # not a regular file
     356              try:
     357                  fsize = os.fstat(fileno).st_size
     358              except OSError as err:
     359                  raise _GiveupOnSendfile(err)  # not a regular file
     360              if not fsize:
     361                  return 0  # empty file
     362              # Truncate to 1GiB to avoid OverflowError, see bpo-38319.
     363              blocksize = min(count or fsize, 2 ** 30)
     364              timeout = self.gettimeout()
     365              if timeout == 0:
     366                  raise ValueError("non-blocking sockets are not supported")
     367              # poll/select have the advantage of not requiring any
     368              # extra file descriptor, contrarily to epoll/kqueue
     369              # (also, they require a single syscall).
     370              if hasattr(selectors, 'PollSelector'):
     371                  selector = selectors.PollSelector()
     372              else:
     373                  selector = selectors.SelectSelector()
     374              selector.register(sockno, selectors.EVENT_WRITE)
     375  
     376              total_sent = 0
     377              # localize variable access to minimize overhead
     378              selector_select = selector.select
     379              os_sendfile = os.sendfile
     380              try:
     381                  while True:
     382                      if timeout and not selector_select(timeout):
     383                          raise TimeoutError('timed out')
     384                      if count:
     385                          blocksize = count - total_sent
     386                          if blocksize <= 0:
     387                              break
     388                      try:
     389                          sent = os_sendfile(sockno, fileno, offset, blocksize)
     390                      except BlockingIOError:
     391                          if not timeout:
     392                              # Block until the socket is ready to send some
     393                              # data; avoids hogging CPU resources.
     394                              selector_select()
     395                          continue
     396                      except OSError as err:
     397                          if total_sent == 0:
     398                              # We can get here for different reasons, the main
     399                              # one being 'file' is not a regular mmap(2)-like
     400                              # file, in which case we'll fall back on using
     401                              # plain send().
     402                              raise _GiveupOnSendfile(err)
     403                          raise err from None
     404                      else:
     405                          if sent == 0:
     406                              break  # EOF
     407                          offset += sent
     408                          total_sent += sent
     409                  return total_sent
     410              finally:
     411                  if total_sent > 0 and hasattr(file, 'seek'):
     412                      file.seek(offset)
     413      else:
     414          def _sendfile_use_sendfile(self, file, offset=0, count=None):
     415              raise _GiveupOnSendfile(
     416                  "os.sendfile() not available on this platform")
     417  
     418      def _sendfile_use_send(self, file, offset=0, count=None):
     419          self._check_sendfile_params(file, offset, count)
     420          if self.gettimeout() == 0:
     421              raise ValueError("non-blocking sockets are not supported")
     422          if offset:
     423              file.seek(offset)
     424          blocksize = min(count, 8192) if count else 8192
     425          total_sent = 0
     426          # localize variable access to minimize overhead
     427          file_read = file.read
     428          sock_send = self.send
     429          try:
     430              while True:
     431                  if count:
     432                      blocksize = min(count - total_sent, blocksize)
     433                      if blocksize <= 0:
     434                          break
     435                  data = memoryview(file_read(blocksize))
     436                  if not data:
     437                      break  # EOF
     438                  while True:
     439                      try:
     440                          sent = sock_send(data)
     441                      except BlockingIOError:
     442                          continue
     443                      else:
     444                          total_sent += sent
     445                          if sent < len(data):
     446                              data = data[sent:]
     447                          else:
     448                              break
     449              return total_sent
     450          finally:
     451              if total_sent > 0 and hasattr(file, 'seek'):
     452                  file.seek(offset + total_sent)
     453  
     454      def _check_sendfile_params(self, file, offset, count):
     455          if 'b' not in getattr(file, 'mode', 'b'):
     456              raise ValueError("file should be opened in binary mode")
     457          if not self.type & SOCK_STREAM:
     458              raise ValueError("only SOCK_STREAM type sockets are supported")
     459          if count is not None:
     460              if not isinstance(count, int):
     461                  raise TypeError(
     462                      "count must be a positive integer (got {!r})".format(count))
     463              if count <= 0:
     464                  raise ValueError(
     465                      "count must be a positive integer (got {!r})".format(count))
     466  
     467      def sendfile(self, file, offset=0, count=None):
     468          """sendfile(file[, offset[, count]]) -> sent
     469  
     470          Send a file until EOF is reached by using high-performance
     471          os.sendfile() and return the total number of bytes which
     472          were sent.
     473          *file* must be a regular file object opened in binary mode.
     474          If os.sendfile() is not available (e.g. Windows) or file is
     475          not a regular file socket.send() will be used instead.
     476          *offset* tells from where to start reading the file.
     477          If specified, *count* is the total number of bytes to transmit
     478          as opposed to sending the file until EOF is reached.
     479          File position is updated on return or also in case of error in
     480          which case file.tell() can be used to figure out the number of
     481          bytes which were sent.
     482          The socket must be of SOCK_STREAM type.
     483          Non-blocking sockets are not supported.
     484          """
     485          try:
     486              return self._sendfile_use_sendfile(file, offset, count)
     487          except _GiveupOnSendfile:
     488              return self._sendfile_use_send(file, offset, count)
     489  
     490      def _decref_socketios(self):
     491          if self._io_refs > 0:
     492              self._io_refs -= 1
     493          if self._closed:
     494              self.close()
     495  
     496      def _real_close(self, _ss=_socket.socket):
     497          # This function should not reference any globals. See issue #808164.
     498          _ss.close(self)
     499  
     500      def close(self):
     501          # This function should not reference any globals. See issue #808164.
     502          self._closed = True
     503          if self._io_refs <= 0:
     504              self._real_close()
     505  
     506      def detach(self):
     507          """detach() -> file descriptor
     508  
     509          Close the socket object without closing the underlying file descriptor.
     510          The object cannot be used after this call, but the file descriptor
     511          can be reused for other purposes.  The file descriptor is returned.
     512          """
     513          self._closed = True
     514          return super().detach()
     515  
     516      @property
     517      def family(self):
     518          """Read-only access to the address family for this socket.
     519          """
     520          return _intenum_converter(super().family, AddressFamily)
     521  
     522      @property
     523      def type(self):
     524          """Read-only access to the socket type.
     525          """
     526          return _intenum_converter(super().type, SocketKind)
     527  
     528      if os.name == 'nt':
     529          def get_inheritable(self):
     530              return os.get_handle_inheritable(self.fileno())
     531          def set_inheritable(self, inheritable):
     532              os.set_handle_inheritable(self.fileno(), inheritable)
     533      else:
     534          def get_inheritable(self):
     535              return os.get_inheritable(self.fileno())
     536          def set_inheritable(self, inheritable):
     537              os.set_inheritable(self.fileno(), inheritable)
     538      get_inheritable.__doc__ = "Get the inheritable flag of the socket"
     539      set_inheritable.__doc__ = "Set the inheritable flag of the socket"
     540  
     541  def fromfd(fd, family, type, proto=0):
     542      """ fromfd(fd, family, type[, proto]) -> socket object
     543  
     544      Create a socket object from a duplicate of the given file
     545      descriptor.  The remaining arguments are the same as for socket().
     546      """
     547      nfd = dup(fd)
     548      return socket(family, type, proto, nfd)
     549  
     550  if hasattr(_socket.socket, "sendmsg"):
     551      import array
     552  
     553      def send_fds(sock, buffers, fds, flags=0, address=None):
     554          """ send_fds(sock, buffers, fds[, flags[, address]]) -> integer
     555  
     556          Send the list of file descriptors fds over an AF_UNIX socket.
     557          """
     558          return sock.sendmsg(buffers, [(_socket.SOL_SOCKET,
     559              _socket.SCM_RIGHTS, array.array("i", fds))])
     560      __all__.append("send_fds")
     561  
     562  if hasattr(_socket.socket, "recvmsg"):
     563      import array
     564  
     565      def recv_fds(sock, bufsize, maxfds, flags=0):
     566          """ recv_fds(sock, bufsize, maxfds[, flags]) -> (data, list of file
     567          descriptors, msg_flags, address)
     568  
     569          Receive up to maxfds file descriptors returning the message
     570          data and a list containing the descriptors.
     571          """
     572          # Array of ints
     573          fds = array.array("i")
     574          msg, ancdata, flags, addr = sock.recvmsg(bufsize,
     575              _socket.CMSG_LEN(maxfds * fds.itemsize))
     576          for cmsg_level, cmsg_type, cmsg_data in ancdata:
     577              if (cmsg_level == _socket.SOL_SOCKET and cmsg_type == _socket.SCM_RIGHTS):
     578                  fds.frombytes(cmsg_data[:
     579                          len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
     580  
     581          return msg, list(fds), flags, addr
     582      __all__.append("recv_fds")
     583  
     584  if hasattr(_socket.socket, "share"):
     585      def fromshare(info):
     586          """ fromshare(info) -> socket object
     587  
     588          Create a socket object from the bytes object returned by
     589          socket.share(pid).
     590          """
     591          return socket(0, 0, 0, info)
     592      __all__.append("fromshare")
     593  
     594  if hasattr(_socket, "socketpair"):
     595  
     596      def socketpair(family=None, type=SOCK_STREAM, proto=0):
     597          """socketpair([family[, type[, proto]]]) -> (socket object, socket object)
     598  
     599          Create a pair of socket objects from the sockets returned by the platform
     600          socketpair() function.
     601          The arguments are the same as for socket() except the default family is
     602          AF_UNIX if defined on the platform; otherwise, the default is AF_INET.
     603          """
     604          if family is None:
     605              try:
     606                  family = AF_UNIX
     607              except NameError:
     608                  family = AF_INET
     609          a, b = _socket.socketpair(family, type, proto)
     610          a = socket(family, type, proto, a.detach())
     611          b = socket(family, type, proto, b.detach())
     612          return a, b
     613  
     614  else:
     615  
     616      # Origin: https://gist.github.com/4325783, by Geert Jansen.  Public domain.
     617      def socketpair(family=AF_INET, type=SOCK_STREAM, proto=0):
     618          if family == AF_INET:
     619              host = _LOCALHOST
     620          elif family == AF_INET6:
     621              host = _LOCALHOST_V6
     622          else:
     623              raise ValueError("Only AF_INET and AF_INET6 socket address families "
     624                               "are supported")
     625          if type != SOCK_STREAM:
     626              raise ValueError("Only SOCK_STREAM socket type is supported")
     627          if proto != 0:
     628              raise ValueError("Only protocol zero is supported")
     629  
     630          # We create a connected TCP socket. Note the trick with
     631          # setblocking(False) that prevents us from having to create a thread.
     632          lsock = socket(family, type, proto)
     633          try:
     634              lsock.bind((host, 0))
     635              lsock.listen()
     636              # On IPv6, ignore flow_info and scope_id
     637              addr, port = lsock.getsockname()[:2]
     638              csock = socket(family, type, proto)
     639              try:
     640                  csock.setblocking(False)
     641                  try:
     642                      csock.connect((addr, port))
     643                  except (BlockingIOError, InterruptedError):
     644                      pass
     645                  csock.setblocking(True)
     646                  ssock, _ = lsock.accept()
     647              except:
     648                  csock.close()
     649                  raise
     650          finally:
     651              lsock.close()
     652          return (ssock, csock)
     653      __all__.append("socketpair")
     654  
     655  socketpair.__doc__ = """socketpair([family[, type[, proto]]]) -> (socket object, socket object)
     656  Create a pair of socket objects from the sockets returned by the platform
     657  socketpair() function.
     658  The arguments are the same as for socket() except the default family is AF_UNIX
     659  if defined on the platform; otherwise, the default is AF_INET.
     660  """
     661  
     662  _blocking_errnos = { EAGAIN, EWOULDBLOCK }
     663  
     664  class ESC[4;38;5;81mSocketIO(ESC[4;38;5;149mioESC[4;38;5;149m.ESC[4;38;5;149mRawIOBase):
     665  
     666      """Raw I/O implementation for stream sockets.
     667  
     668      This class supports the makefile() method on sockets.  It provides
     669      the raw I/O interface on top of a socket object.
     670      """
     671  
     672      # One might wonder why not let FileIO do the job instead.  There are two
     673      # main reasons why FileIO is not adapted:
     674      # - it wouldn't work under Windows (where you can't used read() and
     675      #   write() on a socket handle)
     676      # - it wouldn't work with socket timeouts (FileIO would ignore the
     677      #   timeout and consider the socket non-blocking)
     678  
     679      # XXX More docs
     680  
     681      def __init__(self, sock, mode):
     682          if mode not in ("r", "w", "rw", "rb", "wb", "rwb"):
     683              raise ValueError("invalid mode: %r" % mode)
     684          io.RawIOBase.__init__(self)
     685          self._sock = sock
     686          if "b" not in mode:
     687              mode += "b"
     688          self._mode = mode
     689          self._reading = "r" in mode
     690          self._writing = "w" in mode
     691          self._timeout_occurred = False
     692  
     693      def readinto(self, b):
     694          """Read up to len(b) bytes into the writable buffer *b* and return
     695          the number of bytes read.  If the socket is non-blocking and no bytes
     696          are available, None is returned.
     697  
     698          If *b* is non-empty, a 0 return value indicates that the connection
     699          was shutdown at the other end.
     700          """
     701          self._checkClosed()
     702          self._checkReadable()
     703          if self._timeout_occurred:
     704              raise OSError("cannot read from timed out object")
     705          while True:
     706              try:
     707                  return self._sock.recv_into(b)
     708              except timeout:
     709                  self._timeout_occurred = True
     710                  raise
     711              except error as e:
     712                  if e.errno in _blocking_errnos:
     713                      return None
     714                  raise
     715  
     716      def write(self, b):
     717          """Write the given bytes or bytearray object *b* to the socket
     718          and return the number of bytes written.  This can be less than
     719          len(b) if not all data could be written.  If the socket is
     720          non-blocking and no bytes could be written None is returned.
     721          """
     722          self._checkClosed()
     723          self._checkWritable()
     724          try:
     725              return self._sock.send(b)
     726          except error as e:
     727              # XXX what about EINTR?
     728              if e.errno in _blocking_errnos:
     729                  return None
     730              raise
     731  
     732      def readable(self):
     733          """True if the SocketIO is open for reading.
     734          """
     735          if self.closed:
     736              raise ValueError("I/O operation on closed socket.")
     737          return self._reading
     738  
     739      def writable(self):
     740          """True if the SocketIO is open for writing.
     741          """
     742          if self.closed:
     743              raise ValueError("I/O operation on closed socket.")
     744          return self._writing
     745  
     746      def seekable(self):
     747          """True if the SocketIO is open for seeking.
     748          """
     749          if self.closed:
     750              raise ValueError("I/O operation on closed socket.")
     751          return super().seekable()
     752  
     753      def fileno(self):
     754          """Return the file descriptor of the underlying socket.
     755          """
     756          self._checkClosed()
     757          return self._sock.fileno()
     758  
     759      @property
     760      def name(self):
     761          if not self.closed:
     762              return self.fileno()
     763          else:
     764              return -1
     765  
     766      @property
     767      def mode(self):
     768          return self._mode
     769  
     770      def close(self):
     771          """Close the SocketIO object.  This doesn't close the underlying
     772          socket, except if all references to it have disappeared.
     773          """
     774          if self.closed:
     775              return
     776          io.RawIOBase.close(self)
     777          self._sock._decref_socketios()
     778          self._sock = None
     779  
     780  
     781  def getfqdn(name=''):
     782      """Get fully qualified domain name from name.
     783  
     784      An empty argument is interpreted as meaning the local host.
     785  
     786      First the hostname returned by gethostbyaddr() is checked, then
     787      possibly existing aliases. In case no FQDN is available and `name`
     788      was given, it is returned unchanged. If `name` was empty, '0.0.0.0' or '::',
     789      hostname from gethostname() is returned.
     790      """
     791      name = name.strip()
     792      if not name or name in ('0.0.0.0', '::'):
     793          name = gethostname()
     794      try:
     795          hostname, aliases, ipaddrs = gethostbyaddr(name)
     796      except error:
     797          pass
     798      else:
     799          aliases.insert(0, hostname)
     800          for name in aliases:
     801              if '.' in name:
     802                  break
     803          else:
     804              name = hostname
     805      return name
     806  
     807  
     808  _GLOBAL_DEFAULT_TIMEOUT = object()
     809  
     810  def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT,
     811                        source_address=None, *, all_errors=False):
     812      """Connect to *address* and return the socket object.
     813  
     814      Convenience function.  Connect to *address* (a 2-tuple ``(host,
     815      port)``) and return the socket object.  Passing the optional
     816      *timeout* parameter will set the timeout on the socket instance
     817      before attempting to connect.  If no *timeout* is supplied, the
     818      global default timeout setting returned by :func:`getdefaulttimeout`
     819      is used.  If *source_address* is set it must be a tuple of (host, port)
     820      for the socket to bind as a source address before making the connection.
     821      A host of '' or port 0 tells the OS to use the default. When a connection
     822      cannot be created, raises the last error if *all_errors* is False,
     823      and an ExceptionGroup of all errors if *all_errors* is True.
     824      """
     825  
     826      host, port = address
     827      exceptions = []
     828      for res in getaddrinfo(host, port, 0, SOCK_STREAM):
     829          af, socktype, proto, canonname, sa = res
     830          sock = None
     831          try:
     832              sock = socket(af, socktype, proto)
     833              if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
     834                  sock.settimeout(timeout)
     835              if source_address:
     836                  sock.bind(source_address)
     837              sock.connect(sa)
     838              # Break explicitly a reference cycle
     839              exceptions.clear()
     840              return sock
     841  
     842          except error as exc:
     843              if not all_errors:
     844                  exceptions.clear()  # raise only the last error
     845              exceptions.append(exc)
     846              if sock is not None:
     847                  sock.close()
     848  
     849      if len(exceptions):
     850          try:
     851              if not all_errors:
     852                  raise exceptions[0]
     853              raise ExceptionGroup("create_connection failed", exceptions)
     854          finally:
     855              # Break explicitly a reference cycle
     856              exceptions.clear()
     857      else:
     858          raise error("getaddrinfo returns an empty list")
     859  
     860  
     861  def has_dualstack_ipv6():
     862      """Return True if the platform supports creating a SOCK_STREAM socket
     863      which can handle both AF_INET and AF_INET6 (IPv4 / IPv6) connections.
     864      """
     865      if not has_ipv6 \
     866              or not hasattr(_socket, 'IPPROTO_IPV6') \
     867              or not hasattr(_socket, 'IPV6_V6ONLY'):
     868          return False
     869      try:
     870          with socket(AF_INET6, SOCK_STREAM) as sock:
     871              sock.setsockopt(IPPROTO_IPV6, IPV6_V6ONLY, 0)
     872              return True
     873      except error:
     874          return False
     875  
     876  
     877  def create_server(address, *, family=AF_INET, backlog=None, reuse_port=False,
     878                    dualstack_ipv6=False):
     879      """Convenience function which creates a SOCK_STREAM type socket
     880      bound to *address* (a 2-tuple (host, port)) and return the socket
     881      object.
     882  
     883      *family* should be either AF_INET or AF_INET6.
     884      *backlog* is the queue size passed to socket.listen().
     885      *reuse_port* dictates whether to use the SO_REUSEPORT socket option.
     886      *dualstack_ipv6*: if true and the platform supports it, it will
     887      create an AF_INET6 socket able to accept both IPv4 or IPv6
     888      connections. When false it will explicitly disable this option on
     889      platforms that enable it by default (e.g. Linux).
     890  
     891      >>> with create_server(('', 8000)) as server:
     892      ...     while True:
     893      ...         conn, addr = server.accept()
     894      ...         # handle new connection
     895      """
     896      if reuse_port and not hasattr(_socket, "SO_REUSEPORT"):
     897          raise ValueError("SO_REUSEPORT not supported on this platform")
     898      if dualstack_ipv6:
     899          if not has_dualstack_ipv6():
     900              raise ValueError("dualstack_ipv6 not supported on this platform")
     901          if family != AF_INET6:
     902              raise ValueError("dualstack_ipv6 requires AF_INET6 family")
     903      sock = socket(family, SOCK_STREAM)
     904      try:
     905          # Note about Windows. We don't set SO_REUSEADDR because:
     906          # 1) It's unnecessary: bind() will succeed even in case of a
     907          # previous closed socket on the same address and still in
     908          # TIME_WAIT state.
     909          # 2) If set, another socket is free to bind() on the same
     910          # address, effectively preventing this one from accepting
     911          # connections. Also, it may set the process in a state where
     912          # it'll no longer respond to any signals or graceful kills.
     913          # See: https://learn.microsoft.com/windows/win32/winsock/using-so-reuseaddr-and-so-exclusiveaddruse
     914          if os.name not in ('nt', 'cygwin') and \
     915                  hasattr(_socket, 'SO_REUSEADDR'):
     916              try:
     917                  sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
     918              except error:
     919                  # Fail later on bind(), for platforms which may not
     920                  # support this option.
     921                  pass
     922          if reuse_port:
     923              sock.setsockopt(SOL_SOCKET, SO_REUSEPORT, 1)
     924          if has_ipv6 and family == AF_INET6:
     925              if dualstack_ipv6:
     926                  sock.setsockopt(IPPROTO_IPV6, IPV6_V6ONLY, 0)
     927              elif hasattr(_socket, "IPV6_V6ONLY") and \
     928                      hasattr(_socket, "IPPROTO_IPV6"):
     929                  sock.setsockopt(IPPROTO_IPV6, IPV6_V6ONLY, 1)
     930          try:
     931              sock.bind(address)
     932          except error as err:
     933              msg = '%s (while attempting to bind on address %r)' % \
     934                  (err.strerror, address)
     935              raise error(err.errno, msg) from None
     936          if backlog is None:
     937              sock.listen()
     938          else:
     939              sock.listen(backlog)
     940          return sock
     941      except error:
     942          sock.close()
     943          raise
     944  
     945  
     946  def getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):
     947      """Resolve host and port into list of address info entries.
     948  
     949      Translate the host/port argument into a sequence of 5-tuples that contain
     950      all the necessary arguments for creating a socket connected to that service.
     951      host is a domain name, a string representation of an IPv4/v6 address or
     952      None. port is a string service name such as 'http', a numeric port number or
     953      None. By passing None as the value of host and port, you can pass NULL to
     954      the underlying C API.
     955  
     956      The family, type and proto arguments can be optionally specified in order to
     957      narrow the list of addresses returned. Passing zero as a value for each of
     958      these arguments selects the full range of results.
     959      """
     960      # We override this function since we want to translate the numeric family
     961      # and socket type values to enum constants.
     962      addrlist = []
     963      for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
     964          af, socktype, proto, canonname, sa = res
     965          addrlist.append((_intenum_converter(af, AddressFamily),
     966                           _intenum_converter(socktype, SocketKind),
     967                           proto, canonname, sa))
     968      return addrlist