PageRenderTime 48ms CodeModel.GetById 4ms app.highlight 32ms RepoModel.GetById 2ms app.codeStats 0ms

/Doc/library/socket.rst

https://bitbucket.org/bluehorn/sampling_prof
ReStructuredText | 1730 lines | 1213 code | 517 blank | 0 comment | 0 complexity | fb5f837d76bc1bd35ba87978817b0238 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1:mod:`socket` --- Low-level networking interface
   2================================================
   3
   4.. module:: socket
   5   :synopsis: Low-level networking interface.
   6
   7**Source code:** :source:`Lib/socket.py`
   8
   9--------------
  10
  11This module provides access to the BSD *socket* interface. It is available on
  12all modern Unix systems, Windows, MacOS, and probably additional platforms.
  13
  14.. note::
  15
  16   Some behavior may be platform dependent, since calls are made to the operating
  17   system socket APIs.
  18
  19.. index:: object: socket
  20
  21The Python interface is a straightforward transliteration of the Unix system
  22call and library interface for sockets to Python's object-oriented style: the
  23:func:`.socket` function returns a :dfn:`socket object` whose methods implement
  24the various socket system calls.  Parameter types are somewhat higher-level than
  25in the C interface: as with :meth:`read` and :meth:`write` operations on Python
  26files, buffer allocation on receive operations is automatic, and buffer length
  27is implicit on send operations.
  28
  29
  30.. seealso::
  31
  32   Module :mod:`socketserver`
  33      Classes that simplify writing network servers.
  34
  35   Module :mod:`ssl`
  36      A TLS/SSL wrapper for socket objects.
  37
  38
  39Socket families
  40---------------
  41
  42Depending on the system and the build options, various socket families
  43are supported by this module.
  44
  45The address format required by a particular socket object is automatically
  46selected based on the address family specified when the socket object was
  47created.  Socket addresses are represented as follows:
  48
  49- The address of an :const:`AF_UNIX` socket bound to a file system node
  50  is represented as a string, using the file system encoding and the
  51  ``'surrogateescape'`` error handler (see :pep:`383`).  An address in
  52  Linux's abstract namespace is returned as a :term:`bytes-like object` with
  53  an initial null byte; note that sockets in this namespace can
  54  communicate with normal file system sockets, so programs intended to
  55  run on Linux may need to deal with both types of address.  A string or
  56  bytes-like object can be used for either type of address when
  57  passing it as an argument.
  58
  59   .. versionchanged:: 3.3
  60      Previously, :const:`AF_UNIX` socket paths were assumed to use UTF-8
  61      encoding.
  62
  63   .. versionchanged:: 3.5
  64      Writable :term:`bytes-like object` is now accepted.
  65
  66- A pair ``(host, port)`` is used for the :const:`AF_INET` address family,
  67  where *host* is a string representing either a hostname in Internet domain
  68  notation like ``'daring.cwi.nl'`` or an IPv4 address like ``'100.50.200.5'``,
  69  and *port* is an integer.
  70
  71- For :const:`AF_INET6` address family, a four-tuple ``(host, port, flowinfo,
  72  scopeid)`` is used, where *flowinfo* and *scopeid* represent the ``sin6_flowinfo``
  73  and ``sin6_scope_id`` members in :const:`struct sockaddr_in6` in C.  For
  74  :mod:`socket` module methods, *flowinfo* and *scopeid* can be omitted just for
  75  backward compatibility.  Note, however, omission of *scopeid* can cause problems
  76  in manipulating scoped IPv6 addresses.
  77
  78- :const:`AF_NETLINK` sockets are represented as pairs ``(pid, groups)``.
  79
  80- Linux-only support for TIPC is available using the :const:`AF_TIPC`
  81  address family.  TIPC is an open, non-IP based networked protocol designed
  82  for use in clustered computer environments.  Addresses are represented by a
  83  tuple, and the fields depend on the address type. The general tuple form is
  84  ``(addr_type, v1, v2, v3 [, scope])``, where:
  85
  86  - *addr_type* is one of :const:`TIPC_ADDR_NAMESEQ`, :const:`TIPC_ADDR_NAME`,
  87    or :const:`TIPC_ADDR_ID`.
  88  - *scope* is one of :const:`TIPC_ZONE_SCOPE`, :const:`TIPC_CLUSTER_SCOPE`, and
  89    :const:`TIPC_NODE_SCOPE`.
  90  - If *addr_type* is :const:`TIPC_ADDR_NAME`, then *v1* is the server type, *v2* is
  91    the port identifier, and *v3* should be 0.
  92
  93    If *addr_type* is :const:`TIPC_ADDR_NAMESEQ`, then *v1* is the server type, *v2*
  94    is the lower port number, and *v3* is the upper port number.
  95
  96    If *addr_type* is :const:`TIPC_ADDR_ID`, then *v1* is the node, *v2* is the
  97    reference, and *v3* should be set to 0.
  98
  99- A tuple ``(interface, )`` is used for the :const:`AF_CAN` address family,
 100  where *interface* is a string representing a network interface name like
 101  ``'can0'``. The network interface name ``''`` can be used to receive packets
 102  from all network interfaces of this family.
 103
 104- A string or a tuple ``(id, unit)`` is used for the :const:`SYSPROTO_CONTROL`
 105  protocol of the :const:`PF_SYSTEM` family. The string is the name of a
 106  kernel control using a dynamically-assigned ID. The tuple can be used if ID
 107  and unit number of the kernel control are known or if a registered ID is
 108  used.
 109
 110  .. versionadded:: 3.3
 111
 112- :const:`AF_BLUETOOTH` supports the following protocols and address
 113  formats:
 114
 115  - :const:`BTPROTO_L2CAP` accepts ``(bdaddr, psm)`` where ``bdaddr`` is
 116    the Bluetooth address as a string and ``psm`` is an integer.
 117
 118  - :const:`BTPROTO_RFCOMM` accepts ``(bdaddr, channel)`` where ``bdaddr``
 119    is the Bluetooth address as a string and ``channel`` is an integer.
 120
 121  - :const:`BTPROTO_HCI` accepts ``(device_id,)`` where ``device_id`` is
 122    either an integer or a string with the Bluetooth address of the
 123    interface. (This depends on your OS; NetBSD and DragonFlyBSD expect
 124    a Bluetooth address while everything else expects an integer.)
 125
 126    .. versionchanged:: 3.2
 127       NetBSD and DragonFlyBSD support added.
 128
 129  - :const:`BTPROTO_SCO` accepts ``bdaddr`` where ``bdaddr`` is a
 130    :class:`bytes` object containing the Bluetooth address in a
 131    string format. (ex. ``b'12:23:34:45:56:67'``) This protocol is not
 132    supported under FreeBSD.
 133
 134- :const:`AF_ALG` is a Linux-only socket based interface to Kernel
 135  cryptography. An algorithm socket is configured with a tuple of two to four
 136  elements ``(type, name [, feat [, mask]])``, where:
 137
 138  - *type* is the algorithm type as string, e.g. ``aead``, ``hash``,
 139    ``skcipher`` or ``rng``.
 140
 141  - *name* is the algorithm name and operation mode as string, e.g.
 142    ``sha256``, ``hmac(sha256)``, ``cbc(aes)`` or ``drbg_nopr_ctr_aes256``.
 143
 144  - *feat* and *mask* are unsigned 32bit integers.
 145
 146  Availability Linux 2.6.38, some algorithm types require more recent Kernels.
 147
 148  .. versionadded:: 3.6
 149
 150- Certain other address families (:const:`AF_PACKET`, :const:`AF_CAN`)
 151  support specific representations.
 152
 153  .. XXX document them!
 154
 155For IPv4 addresses, two special forms are accepted instead of a host address:
 156the empty string represents :const:`INADDR_ANY`, and the string
 157``'<broadcast>'`` represents :const:`INADDR_BROADCAST`.  This behavior is not
 158compatible with IPv6, therefore, you may want to avoid these if you intend
 159to support IPv6 with your Python programs.
 160
 161If you use a hostname in the *host* portion of IPv4/v6 socket address, the
 162program may show a nondeterministic behavior, as Python uses the first address
 163returned from the DNS resolution.  The socket address will be resolved
 164differently into an actual IPv4/v6 address, depending on the results from DNS
 165resolution and/or the host configuration.  For deterministic behavior use a
 166numeric address in *host* portion.
 167
 168All errors raise exceptions.  The normal exceptions for invalid argument types
 169and out-of-memory conditions can be raised; starting from Python 3.3, errors
 170related to socket or address semantics raise :exc:`OSError` or one of its
 171subclasses (they used to raise :exc:`socket.error`).
 172
 173Non-blocking mode is supported through :meth:`~socket.setblocking`.  A
 174generalization of this based on timeouts is supported through
 175:meth:`~socket.settimeout`.
 176
 177
 178Module contents
 179---------------
 180
 181The module :mod:`socket` exports the following elements.
 182
 183
 184Exceptions
 185^^^^^^^^^^
 186
 187.. exception:: error
 188
 189   A deprecated alias of :exc:`OSError`.
 190
 191   .. versionchanged:: 3.3
 192      Following :pep:`3151`, this class was made an alias of :exc:`OSError`.
 193
 194
 195.. exception:: herror
 196
 197   A subclass of :exc:`OSError`, this exception is raised for
 198   address-related errors, i.e. for functions that use *h_errno* in the POSIX
 199   C API, including :func:`gethostbyname_ex` and :func:`gethostbyaddr`.
 200   The accompanying value is a pair ``(h_errno, string)`` representing an
 201   error returned by a library call.  *h_errno* is a numeric value, while
 202   *string* represents the description of *h_errno*, as returned by the
 203   :c:func:`hstrerror` C function.
 204
 205   .. versionchanged:: 3.3
 206      This class was made a subclass of :exc:`OSError`.
 207
 208.. exception:: gaierror
 209
 210   A subclass of :exc:`OSError`, this exception is raised for
 211   address-related errors by :func:`getaddrinfo` and :func:`getnameinfo`.
 212   The accompanying value is a pair ``(error, string)`` representing an error
 213   returned by a library call.  *string* represents the description of
 214   *error*, as returned by the :c:func:`gai_strerror` C function.  The
 215   numeric *error* value will match one of the :const:`EAI_\*` constants
 216   defined in this module.
 217
 218   .. versionchanged:: 3.3
 219      This class was made a subclass of :exc:`OSError`.
 220
 221.. exception:: timeout
 222
 223   A subclass of :exc:`OSError`, this exception is raised when a timeout
 224   occurs on a socket which has had timeouts enabled via a prior call to
 225   :meth:`~socket.settimeout` (or implicitly through
 226   :func:`~socket.setdefaulttimeout`).  The accompanying value is a string
 227   whose value is currently always "timed out".
 228
 229   .. versionchanged:: 3.3
 230      This class was made a subclass of :exc:`OSError`.
 231
 232
 233Constants
 234^^^^^^^^^
 235
 236   The AF_* and SOCK_* constants are now :class:`AddressFamily` and
 237   :class:`SocketKind` :class:`.IntEnum` collections.
 238
 239   .. versionadded:: 3.4
 240
 241.. data:: AF_UNIX
 242          AF_INET
 243          AF_INET6
 244
 245   These constants represent the address (and protocol) families, used for the
 246   first argument to :func:`.socket`.  If the :const:`AF_UNIX` constant is not
 247   defined then this protocol is unsupported.  More constants may be available
 248   depending on the system.
 249
 250
 251.. data:: SOCK_STREAM
 252          SOCK_DGRAM
 253          SOCK_RAW
 254          SOCK_RDM
 255          SOCK_SEQPACKET
 256
 257   These constants represent the socket types, used for the second argument to
 258   :func:`.socket`.  More constants may be available depending on the system.
 259   (Only :const:`SOCK_STREAM` and :const:`SOCK_DGRAM` appear to be generally
 260   useful.)
 261
 262.. data:: SOCK_CLOEXEC
 263          SOCK_NONBLOCK
 264
 265   These two constants, if defined, can be combined with the socket types and
 266   allow you to set some flags atomically (thus avoiding possible race
 267   conditions and the need for separate calls).
 268
 269   .. seealso::
 270
 271      `Secure File Descriptor Handling <http://udrepper.livejournal.com/20407.html>`_
 272      for a more thorough explanation.
 273
 274   Availability: Linux >= 2.6.27.
 275
 276   .. versionadded:: 3.2
 277
 278.. data:: SO_*
 279          SOMAXCONN
 280          MSG_*
 281          SOL_*
 282          SCM_*
 283          IPPROTO_*
 284          IPPORT_*
 285          INADDR_*
 286          IP_*
 287          IPV6_*
 288          EAI_*
 289          AI_*
 290          NI_*
 291          TCP_*
 292
 293   Many constants of these forms, documented in the Unix documentation on sockets
 294   and/or the IP protocol, are also defined in the socket module. They are
 295   generally used in arguments to the :meth:`setsockopt` and :meth:`getsockopt`
 296   methods of socket objects.  In most cases, only those symbols that are defined
 297   in the Unix header files are defined; for a few symbols, default values are
 298   provided.
 299
 300   .. versionchanged:: 3.6
 301      ``SO_DOMAIN``, ``SO_PROTOCOL``, ``SO_PEERSEC``, ``SO_PASSSEC``
 302      were added.
 303
 304.. data:: AF_CAN
 305          PF_CAN
 306          SOL_CAN_*
 307          CAN_*
 308
 309   Many constants of these forms, documented in the Linux documentation, are
 310   also defined in the socket module.
 311
 312   Availability: Linux >= 2.6.25.
 313
 314   .. versionadded:: 3.3
 315
 316.. data:: CAN_BCM
 317          CAN_BCM_*
 318
 319   CAN_BCM, in the CAN protocol family, is the broadcast manager (BCM) protocol.
 320   Broadcast manager constants, documented in the Linux documentation, are also
 321   defined in the socket module.
 322
 323   Availability: Linux >= 2.6.25.
 324
 325   .. versionadded:: 3.4
 326
 327.. data:: CAN_RAW_FD_FRAMES
 328
 329   Enables CAN FD support in a CAN_RAW socket. This is disabled by default.
 330   This allows your application to send both CAN and CAN FD frames; however,
 331   you one must accept both CAN and CAN FD frames when reading from the socket.
 332
 333   This constant is documented in the Linux documentation.
 334
 335   Availability: Linux >= 3.6.
 336
 337   .. versionadded:: 3.5
 338
 339.. data:: AF_RDS
 340          PF_RDS
 341          SOL_RDS
 342          RDS_*
 343
 344   Many constants of these forms, documented in the Linux documentation, are
 345   also defined in the socket module.
 346
 347   Availability: Linux >= 2.6.30.
 348
 349   .. versionadded:: 3.3
 350
 351
 352.. data:: SIO_RCVALL
 353          SIO_KEEPALIVE_VALS
 354          SIO_LOOPBACK_FAST_PATH
 355          RCVALL_*
 356
 357   Constants for Windows' WSAIoctl(). The constants are used as arguments to the
 358   :meth:`~socket.socket.ioctl` method of socket objects.
 359
 360   .. versionchanged:: 3.6
 361      ``SIO_LOOPBACK_FAST_PATH`` was added.
 362
 363
 364.. data:: TIPC_*
 365
 366   TIPC related constants, matching the ones exported by the C socket API. See
 367   the TIPC documentation for more information.
 368
 369.. data:: AF_ALG
 370          SOL_ALG
 371          ALG_*
 372
 373   Constants for Linux Kernel cryptography.
 374
 375   Availability: Linux >= 2.6.38.
 376
 377   .. versionadded:: 3.6
 378
 379.. data:: AF_LINK
 380
 381  Availability: BSD, OSX.
 382
 383  .. versionadded:: 3.4
 384
 385.. data:: has_ipv6
 386
 387   This constant contains a boolean value which indicates if IPv6 is supported on
 388   this platform.
 389
 390.. data:: BDADDR_ANY
 391          BDADDR_LOCAL
 392
 393   These are string constants containing Bluetooth addresses with special
 394   meanings. For example, :const:`BDADDR_ANY` can be used to indicate
 395   any address when specifying the binding socket with
 396   :const:`BTPROTO_RFCOMM`.
 397
 398.. data:: HCI_FILTER
 399          HCI_TIME_STAMP
 400          HCI_DATA_DIR
 401
 402   For use with :const:`BTPROTO_HCI`. :const:`HCI_FILTER` is not
 403   available for NetBSD or DragonFlyBSD. :const:`HCI_TIME_STAMP` and
 404   :const:`HCI_DATA_DIR` are not available for FreeBSD, NetBSD, or
 405   DragonFlyBSD.
 406
 407Functions
 408^^^^^^^^^
 409
 410Creating sockets
 411''''''''''''''''
 412
 413The following functions all create :ref:`socket objects <socket-objects>`.
 414
 415
 416.. function:: socket(family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None)
 417
 418   Create a new socket using the given address family, socket type and protocol
 419   number.  The address family should be :const:`AF_INET` (the default),
 420   :const:`AF_INET6`, :const:`AF_UNIX`, :const:`AF_CAN` or :const:`AF_RDS`. The
 421   socket type should be :const:`SOCK_STREAM` (the default),
 422   :const:`SOCK_DGRAM`, :const:`SOCK_RAW` or perhaps one of the other ``SOCK_``
 423   constants. The protocol number is usually zero and may be omitted or in the
 424   case where the address family is :const:`AF_CAN` the protocol should be one
 425   of :const:`CAN_RAW` or :const:`CAN_BCM`.  If *fileno* is specified, the other
 426   arguments are ignored, causing the socket with the specified file descriptor
 427   to return.  Unlike :func:`socket.fromfd`, *fileno* will return the same
 428   socket and not a duplicate. This may help close a detached socket using
 429   :meth:`socket.close()`.
 430
 431   The newly created socket is :ref:`non-inheritable <fd_inheritance>`.
 432
 433   .. versionchanged:: 3.3
 434      The AF_CAN family was added.
 435      The AF_RDS family was added.
 436
 437   .. versionchanged:: 3.4
 438       The CAN_BCM protocol was added.
 439
 440   .. versionchanged:: 3.4
 441      The returned socket is now non-inheritable.
 442
 443
 444.. function:: socketpair([family[, type[, proto]]])
 445
 446   Build a pair of connected socket objects using the given address family, socket
 447   type, and protocol number.  Address family, socket type, and protocol number are
 448   as for the :func:`.socket` function above. The default family is :const:`AF_UNIX`
 449   if defined on the platform; otherwise, the default is :const:`AF_INET`.
 450
 451   The newly created sockets are :ref:`non-inheritable <fd_inheritance>`.
 452
 453   .. versionchanged:: 3.2
 454      The returned socket objects now support the whole socket API, rather
 455      than a subset.
 456
 457   .. versionchanged:: 3.4
 458      The returned sockets are now non-inheritable.
 459
 460   .. versionchanged:: 3.5
 461      Windows support added.
 462
 463
 464.. function:: create_connection(address[, timeout[, source_address]])
 465
 466   Connect to a TCP service listening on the Internet *address* (a 2-tuple
 467   ``(host, port)``), and return the socket object.  This is a higher-level
 468   function than :meth:`socket.connect`: if *host* is a non-numeric hostname,
 469   it will try to resolve it for both :data:`AF_INET` and :data:`AF_INET6`,
 470   and then try to connect to all possible addresses in turn until a
 471   connection succeeds.  This makes it easy to write clients that are
 472   compatible to both IPv4 and IPv6.
 473
 474   Passing the optional *timeout* parameter will set the timeout on the
 475   socket instance before attempting to connect.  If no *timeout* is
 476   supplied, the global default timeout setting returned by
 477   :func:`getdefaulttimeout` is used.
 478
 479   If supplied, *source_address* must be a 2-tuple ``(host, port)`` for the
 480   socket to bind to as its source address before connecting.  If host or port
 481   are '' or 0 respectively the OS default behavior will be used.
 482
 483   .. versionchanged:: 3.2
 484      *source_address* was added.
 485
 486
 487.. function:: fromfd(fd, family, type, proto=0)
 488
 489   Duplicate the file descriptor *fd* (an integer as returned by a file object's
 490   :meth:`fileno` method) and build a socket object from the result.  Address
 491   family, socket type and protocol number are as for the :func:`.socket` function
 492   above. The file descriptor should refer to a socket, but this is not checked ---
 493   subsequent operations on the object may fail if the file descriptor is invalid.
 494   This function is rarely needed, but can be used to get or set socket options on
 495   a socket passed to a program as standard input or output (such as a server
 496   started by the Unix inet daemon).  The socket is assumed to be in blocking mode.
 497
 498   The newly created socket is :ref:`non-inheritable <fd_inheritance>`.
 499
 500   .. versionchanged:: 3.4
 501      The returned socket is now non-inheritable.
 502
 503
 504.. function:: fromshare(data)
 505
 506   Instantiate a socket from data obtained from the :meth:`socket.share`
 507   method.  The socket is assumed to be in blocking mode.
 508
 509   Availability: Windows.
 510
 511   .. versionadded:: 3.3
 512
 513
 514.. data:: SocketType
 515
 516   This is a Python type object that represents the socket object type. It is the
 517   same as ``type(socket(...))``.
 518
 519
 520Other functions
 521'''''''''''''''
 522
 523The :mod:`socket` module also offers various network-related services:
 524
 525
 526.. function:: getaddrinfo(host, port, family=0, type=0, proto=0, flags=0)
 527
 528   Translate the *host*/*port* argument into a sequence of 5-tuples that contain
 529   all the necessary arguments for creating a socket connected to that service.
 530   *host* is a domain name, a string representation of an IPv4/v6 address
 531   or ``None``. *port* is a string service name such as ``'http'``, a numeric
 532   port number or ``None``.  By passing ``None`` as the value of *host*
 533   and *port*, you can pass ``NULL`` to the underlying C API.
 534
 535   The *family*, *type* and *proto* arguments can be optionally specified
 536   in order to narrow the list of addresses returned.  Passing zero as a
 537   value for each of these arguments selects the full range of results.
 538   The *flags* argument can be one or several of the ``AI_*`` constants,
 539   and will influence how results are computed and returned.
 540   For example, :const:`AI_NUMERICHOST` will disable domain name resolution
 541   and will raise an error if *host* is a domain name.
 542
 543   The function returns a list of 5-tuples with the following structure:
 544
 545   ``(family, type, proto, canonname, sockaddr)``
 546
 547   In these tuples, *family*, *type*, *proto* are all integers and are
 548   meant to be passed to the :func:`.socket` function.  *canonname* will be
 549   a string representing the canonical name of the *host* if
 550   :const:`AI_CANONNAME` is part of the *flags* argument; else *canonname*
 551   will be empty.  *sockaddr* is a tuple describing a socket address, whose
 552   format depends on the returned *family* (a ``(address, port)`` 2-tuple for
 553   :const:`AF_INET`, a ``(address, port, flow info, scope id)`` 4-tuple for
 554   :const:`AF_INET6`), and is meant to be passed to the :meth:`socket.connect`
 555   method.
 556
 557   The following example fetches address information for a hypothetical TCP
 558   connection to ``example.org`` on port 80 (results may differ on your
 559   system if IPv6 isn't enabled)::
 560
 561      >>> socket.getaddrinfo("example.org", 80, proto=socket.IPPROTO_TCP)
 562      [(<AddressFamily.AF_INET6: 10>, <SocketType.SOCK_STREAM: 1>,
 563       6, '', ('2606:2800:220:1:248:1893:25c8:1946', 80, 0, 0)),
 564       (<AddressFamily.AF_INET: 2>, <SocketType.SOCK_STREAM: 1>,
 565       6, '', ('93.184.216.34', 80))]
 566
 567   .. versionchanged:: 3.2
 568      parameters can now be passed using keyword arguments.
 569
 570.. function:: getfqdn([name])
 571
 572   Return a fully qualified domain name for *name*. If *name* is omitted or empty,
 573   it is interpreted as the local host.  To find the fully qualified name, the
 574   hostname returned by :func:`gethostbyaddr` is checked, followed by aliases for the
 575   host, if available.  The first name which includes a period is selected.  In
 576   case no fully qualified domain name is available, the hostname as returned by
 577   :func:`gethostname` is returned.
 578
 579
 580.. function:: gethostbyname(hostname)
 581
 582   Translate a host name to IPv4 address format.  The IPv4 address is returned as a
 583   string, such as  ``'100.50.200.5'``.  If the host name is an IPv4 address itself
 584   it is returned unchanged.  See :func:`gethostbyname_ex` for a more complete
 585   interface. :func:`gethostbyname` does not support IPv6 name resolution, and
 586   :func:`getaddrinfo` should be used instead for IPv4/v6 dual stack support.
 587
 588
 589.. function:: gethostbyname_ex(hostname)
 590
 591   Translate a host name to IPv4 address format, extended interface. Return a
 592   triple ``(hostname, aliaslist, ipaddrlist)`` where *hostname* is the primary
 593   host name responding to the given *ip_address*, *aliaslist* is a (possibly
 594   empty) list of alternative host names for the same address, and *ipaddrlist* is
 595   a list of IPv4 addresses for the same interface on the same host (often but not
 596   always a single address). :func:`gethostbyname_ex` does not support IPv6 name
 597   resolution, and :func:`getaddrinfo` should be used instead for IPv4/v6 dual
 598   stack support.
 599
 600
 601.. function:: gethostname()
 602
 603   Return a string containing the hostname of the machine where  the Python
 604   interpreter is currently executing.
 605
 606   Note: :func:`gethostname` doesn't always return the fully qualified domain
 607   name; use :func:`getfqdn` for that.
 608
 609
 610.. function:: gethostbyaddr(ip_address)
 611
 612   Return a triple ``(hostname, aliaslist, ipaddrlist)`` where *hostname* is the
 613   primary host name responding to the given *ip_address*, *aliaslist* is a
 614   (possibly empty) list of alternative host names for the same address, and
 615   *ipaddrlist* is a list of IPv4/v6 addresses for the same interface on the same
 616   host (most likely containing only a single address). To find the fully qualified
 617   domain name, use the function :func:`getfqdn`. :func:`gethostbyaddr` supports
 618   both IPv4 and IPv6.
 619
 620
 621.. function:: getnameinfo(sockaddr, flags)
 622
 623   Translate a socket address *sockaddr* into a 2-tuple ``(host, port)``. Depending
 624   on the settings of *flags*, the result can contain a fully-qualified domain name
 625   or numeric address representation in *host*.  Similarly, *port* can contain a
 626   string port name or a numeric port number.
 627
 628
 629.. function:: getprotobyname(protocolname)
 630
 631   Translate an Internet protocol name (for example, ``'icmp'``) to a constant
 632   suitable for passing as the (optional) third argument to the :func:`.socket`
 633   function.  This is usually only needed for sockets opened in "raw" mode
 634   (:const:`SOCK_RAW`); for the normal socket modes, the correct protocol is chosen
 635   automatically if the protocol is omitted or zero.
 636
 637
 638.. function:: getservbyname(servicename[, protocolname])
 639
 640   Translate an Internet service name and protocol name to a port number for that
 641   service.  The optional protocol name, if given, should be ``'tcp'`` or
 642   ``'udp'``, otherwise any protocol will match.
 643
 644
 645.. function:: getservbyport(port[, protocolname])
 646
 647   Translate an Internet port number and protocol name to a service name for that
 648   service.  The optional protocol name, if given, should be ``'tcp'`` or
 649   ``'udp'``, otherwise any protocol will match.
 650
 651
 652.. function:: ntohl(x)
 653
 654   Convert 32-bit positive integers from network to host byte order.  On machines
 655   where the host byte order is the same as network byte order, this is a no-op;
 656   otherwise, it performs a 4-byte swap operation.
 657
 658
 659.. function:: ntohs(x)
 660
 661   Convert 16-bit positive integers from network to host byte order.  On machines
 662   where the host byte order is the same as network byte order, this is a no-op;
 663   otherwise, it performs a 2-byte swap operation.
 664
 665
 666.. function:: htonl(x)
 667
 668   Convert 32-bit positive integers from host to network byte order.  On machines
 669   where the host byte order is the same as network byte order, this is a no-op;
 670   otherwise, it performs a 4-byte swap operation.
 671
 672
 673.. function:: htons(x)
 674
 675   Convert 16-bit positive integers from host to network byte order.  On machines
 676   where the host byte order is the same as network byte order, this is a no-op;
 677   otherwise, it performs a 2-byte swap operation.
 678
 679
 680.. function:: inet_aton(ip_string)
 681
 682   Convert an IPv4 address from dotted-quad string format (for example,
 683   '123.45.67.89') to 32-bit packed binary format, as a bytes object four characters in
 684   length.  This is useful when conversing with a program that uses the standard C
 685   library and needs objects of type :c:type:`struct in_addr`, which is the C type
 686   for the 32-bit packed binary this function returns.
 687
 688   :func:`inet_aton` also accepts strings with less than three dots; see the
 689   Unix manual page :manpage:`inet(3)` for details.
 690
 691   If the IPv4 address string passed to this function is invalid,
 692   :exc:`OSError` will be raised. Note that exactly what is valid depends on
 693   the underlying C implementation of :c:func:`inet_aton`.
 694
 695   :func:`inet_aton` does not support IPv6, and :func:`inet_pton` should be used
 696   instead for IPv4/v6 dual stack support.
 697
 698
 699.. function:: inet_ntoa(packed_ip)
 700
 701   Convert a 32-bit packed IPv4 address (a :term:`bytes-like object` four
 702   bytes in length) to its standard dotted-quad string representation (for example,
 703   '123.45.67.89').  This is useful when conversing with a program that uses the
 704   standard C library and needs objects of type :c:type:`struct in_addr`, which
 705   is the C type for the 32-bit packed binary data this function takes as an
 706   argument.
 707
 708   If the byte sequence passed to this function is not exactly 4 bytes in
 709   length, :exc:`OSError` will be raised. :func:`inet_ntoa` does not
 710   support IPv6, and :func:`inet_ntop` should be used instead for IPv4/v6 dual
 711   stack support.
 712
 713   .. versionchanged:: 3.5
 714      Writable :term:`bytes-like object` is now accepted.
 715
 716
 717.. function:: inet_pton(address_family, ip_string)
 718
 719   Convert an IP address from its family-specific string format to a packed,
 720   binary format. :func:`inet_pton` is useful when a library or network protocol
 721   calls for an object of type :c:type:`struct in_addr` (similar to
 722   :func:`inet_aton`) or :c:type:`struct in6_addr`.
 723
 724   Supported values for *address_family* are currently :const:`AF_INET` and
 725   :const:`AF_INET6`. If the IP address string *ip_string* is invalid,
 726   :exc:`OSError` will be raised. Note that exactly what is valid depends on
 727   both the value of *address_family* and the underlying implementation of
 728   :c:func:`inet_pton`.
 729
 730   Availability: Unix (maybe not all platforms), Windows.
 731
 732   .. versionchanged:: 3.4
 733      Windows support added
 734
 735
 736.. function:: inet_ntop(address_family, packed_ip)
 737
 738   Convert a packed IP address (a :term:`bytes-like object` of some number of
 739   bytes) to its standard, family-specific string representation (for
 740   example, ``'7.10.0.5'`` or ``'5aef:2b::8'``).
 741   :func:`inet_ntop` is useful when a library or network protocol returns an
 742   object of type :c:type:`struct in_addr` (similar to :func:`inet_ntoa`) or
 743   :c:type:`struct in6_addr`.
 744
 745   Supported values for *address_family* are currently :const:`AF_INET` and
 746   :const:`AF_INET6`. If the bytes object *packed_ip* is not the correct
 747   length for the specified address family, :exc:`ValueError` will be raised.
 748   :exc:`OSError` is raised for errors from the call to :func:`inet_ntop`.
 749
 750   Availability: Unix (maybe not all platforms), Windows.
 751
 752   .. versionchanged:: 3.4
 753      Windows support added
 754
 755   .. versionchanged:: 3.5
 756      Writable :term:`bytes-like object` is now accepted.
 757
 758
 759..
 760   XXX: Are sendmsg(), recvmsg() and CMSG_*() available on any
 761   non-Unix platforms?  The old (obsolete?) 4.2BSD form of the
 762   interface, in which struct msghdr has no msg_control or
 763   msg_controllen members, is not currently supported.
 764
 765.. function:: CMSG_LEN(length)
 766
 767   Return the total length, without trailing padding, of an ancillary
 768   data item with associated data of the given *length*.  This value
 769   can often be used as the buffer size for :meth:`~socket.recvmsg` to
 770   receive a single item of ancillary data, but :rfc:`3542` requires
 771   portable applications to use :func:`CMSG_SPACE` and thus include
 772   space for padding, even when the item will be the last in the
 773   buffer.  Raises :exc:`OverflowError` if *length* is outside the
 774   permissible range of values.
 775
 776   Availability: most Unix platforms, possibly others.
 777
 778   .. versionadded:: 3.3
 779
 780
 781.. function:: CMSG_SPACE(length)
 782
 783   Return the buffer size needed for :meth:`~socket.recvmsg` to
 784   receive an ancillary data item with associated data of the given
 785   *length*, along with any trailing padding.  The buffer space needed
 786   to receive multiple items is the sum of the :func:`CMSG_SPACE`
 787   values for their associated data lengths.  Raises
 788   :exc:`OverflowError` if *length* is outside the permissible range
 789   of values.
 790
 791   Note that some systems might support ancillary data without
 792   providing this function.  Also note that setting the buffer size
 793   using the results of this function may not precisely limit the
 794   amount of ancillary data that can be received, since additional
 795   data may be able to fit into the padding area.
 796
 797   Availability: most Unix platforms, possibly others.
 798
 799   .. versionadded:: 3.3
 800
 801
 802.. function:: getdefaulttimeout()
 803
 804   Return the default timeout in seconds (float) for new socket objects. A value
 805   of ``None`` indicates that new socket objects have no timeout. When the socket
 806   module is first imported, the default is ``None``.
 807
 808
 809.. function:: setdefaulttimeout(timeout)
 810
 811   Set the default timeout in seconds (float) for new socket objects.  When
 812   the socket module is first imported, the default is ``None``.  See
 813   :meth:`~socket.settimeout` for possible values and their respective
 814   meanings.
 815
 816
 817.. function:: sethostname(name)
 818
 819   Set the machine's hostname to *name*.  This will raise an
 820   :exc:`OSError` if you don't have enough rights.
 821
 822   Availability: Unix.
 823
 824   .. versionadded:: 3.3
 825
 826
 827.. function:: if_nameindex()
 828
 829   Return a list of network interface information
 830   (index int, name string) tuples.
 831   :exc:`OSError` if the system call fails.
 832
 833   Availability: Unix.
 834
 835   .. versionadded:: 3.3
 836
 837
 838.. function:: if_nametoindex(if_name)
 839
 840   Return a network interface index number corresponding to an
 841   interface name.
 842   :exc:`OSError` if no interface with the given name exists.
 843
 844   Availability: Unix.
 845
 846   .. versionadded:: 3.3
 847
 848
 849.. function:: if_indextoname(if_index)
 850
 851   Return a network interface name corresponding to an
 852   interface index number.
 853   :exc:`OSError` if no interface with the given index exists.
 854
 855   Availability: Unix.
 856
 857   .. versionadded:: 3.3
 858
 859
 860.. _socket-objects:
 861
 862Socket Objects
 863--------------
 864
 865Socket objects have the following methods.  Except for
 866:meth:`~socket.makefile`, these correspond to Unix system calls applicable
 867to sockets.
 868
 869.. versionchanged:: 3.2
 870   Support for the :term:`context manager` protocol was added.  Exiting the
 871   context manager is equivalent to calling :meth:`~socket.close`.
 872
 873
 874.. method:: socket.accept()
 875
 876   Accept a connection. The socket must be bound to an address and listening for
 877   connections. The return value is a pair ``(conn, address)`` where *conn* is a
 878   *new* socket object usable to send and receive data on the connection, and
 879   *address* is the address bound to the socket on the other end of the connection.
 880
 881   The newly created socket is :ref:`non-inheritable <fd_inheritance>`.
 882
 883   .. versionchanged:: 3.4
 884      The socket is now non-inheritable.
 885
 886   .. versionchanged:: 3.5
 887      If the system call is interrupted and the signal handler does not raise
 888      an exception, the method now retries the system call instead of raising
 889      an :exc:`InterruptedError` exception (see :pep:`475` for the rationale).
 890
 891
 892.. method:: socket.bind(address)
 893
 894   Bind the socket to *address*.  The socket must not already be bound. (The format
 895   of *address* depends on the address family --- see above.)
 896
 897
 898.. method:: socket.close()
 899
 900   Mark the socket closed.  The underlying system resource (e.g. a file
 901   descriptor) is also closed when all file objects from :meth:`makefile()`
 902   are closed.  Once that happens, all future operations on the socket
 903   object will fail. The remote end will receive no more data (after
 904   queued data is flushed).
 905
 906   Sockets are automatically closed when they are garbage-collected, but
 907   it is recommended to :meth:`close` them explicitly, or to use a
 908   :keyword:`with` statement around them.
 909
 910   .. versionchanged:: 3.6
 911      :exc:`OSError` is now raised if an error occurs when the underlying
 912      :c:func:`close` call is made.
 913
 914   .. note::
 915
 916      :meth:`close()` releases the resource associated with a connection but
 917      does not necessarily close the connection immediately.  If you want
 918      to close the connection in a timely fashion, call :meth:`shutdown()`
 919      before :meth:`close()`.
 920
 921
 922.. method:: socket.connect(address)
 923
 924   Connect to a remote socket at *address*. (The format of *address* depends on the
 925   address family --- see above.)
 926
 927   If the connection is interrupted by a signal, the method waits until the
 928   connection completes, or raise a :exc:`socket.timeout` on timeout, if the
 929   signal handler doesn't raise an exception and the socket is blocking or has
 930   a timeout. For non-blocking sockets, the method raises an
 931   :exc:`InterruptedError` exception if the connection is interrupted by a
 932   signal (or the exception raised by the signal handler).
 933
 934   .. versionchanged:: 3.5
 935      The method now waits until the connection completes instead of raising an
 936      :exc:`InterruptedError` exception if the connection is interrupted by a
 937      signal, the signal handler doesn't raise an exception and the socket is
 938      blocking or has a timeout (see the :pep:`475` for the rationale).
 939
 940
 941.. method:: socket.connect_ex(address)
 942
 943   Like ``connect(address)``, but return an error indicator instead of raising an
 944   exception for errors returned by the C-level :c:func:`connect` call (other
 945   problems, such as "host not found," can still raise exceptions).  The error
 946   indicator is ``0`` if the operation succeeded, otherwise the value of the
 947   :c:data:`errno` variable.  This is useful to support, for example, asynchronous
 948   connects.
 949
 950
 951.. method:: socket.detach()
 952
 953   Put the socket object into closed state without actually closing the
 954   underlying file descriptor.  The file descriptor is returned, and can
 955   be reused for other purposes.
 956
 957   .. versionadded:: 3.2
 958
 959
 960.. method:: socket.dup()
 961
 962   Duplicate the socket.
 963
 964   The newly created socket is :ref:`non-inheritable <fd_inheritance>`.
 965
 966   .. versionchanged:: 3.4
 967      The socket is now non-inheritable.
 968
 969
 970.. method:: socket.fileno()
 971
 972   Return the socket's file descriptor (a small integer), or -1 on failure. This
 973   is useful with :func:`select.select`.
 974
 975   Under Windows the small integer returned by this method cannot be used where a
 976   file descriptor can be used (such as :func:`os.fdopen`).  Unix does not have
 977   this limitation.
 978
 979.. method:: socket.get_inheritable()
 980
 981   Get the :ref:`inheritable flag <fd_inheritance>` of the socket's file
 982   descriptor or socket's handle: ``True`` if the socket can be inherited in
 983   child processes, ``False`` if it cannot.
 984
 985   .. versionadded:: 3.4
 986
 987
 988.. method:: socket.getpeername()
 989
 990   Return the remote address to which the socket is connected.  This is useful to
 991   find out the port number of a remote IPv4/v6 socket, for instance. (The format
 992   of the address returned depends on the address family --- see above.)  On some
 993   systems this function is not supported.
 994
 995
 996.. method:: socket.getsockname()
 997
 998   Return the socket's own address.  This is useful to find out the port number of
 999   an IPv4/v6 socket, for instance. (The format of the address returned depends on
1000   the address family --- see above.)
1001
1002
1003.. method:: socket.getsockopt(level, optname[, buflen])
1004
1005   Return the value of the given socket option (see the Unix man page
1006   :manpage:`getsockopt(2)`).  The needed symbolic constants (:const:`SO_\*` etc.)
1007   are defined in this module.  If *buflen* is absent, an integer option is assumed
1008   and its integer value is returned by the function.  If *buflen* is present, it
1009   specifies the maximum length of the buffer used to receive the option in, and
1010   this buffer is returned as a bytes object.  It is up to the caller to decode the
1011   contents of the buffer (see the optional built-in module :mod:`struct` for a way
1012   to decode C structures encoded as byte strings).
1013
1014
1015.. method:: socket.gettimeout()
1016
1017   Return the timeout in seconds (float) associated with socket operations,
1018   or ``None`` if no timeout is set.  This reflects the last call to
1019   :meth:`setblocking` or :meth:`settimeout`.
1020
1021
1022.. method:: socket.ioctl(control, option)
1023
1024   :platform: Windows
1025
1026   The :meth:`ioctl` method is a limited interface to the WSAIoctl system
1027   interface.  Please refer to the `Win32 documentation
1028   <https://msdn.microsoft.com/en-us/library/ms741621%28VS.85%29.aspx>`_ for more
1029   information.
1030
1031   On other platforms, the generic :func:`fcntl.fcntl` and :func:`fcntl.ioctl`
1032   functions may be used; they accept a socket object as their first argument.
1033
1034   Currently only the following control codes are supported:
1035   ``SIO_RCVALL``, ``SIO_KEEPALIVE_VALS``, and ``SIO_LOOPBACK_FAST_PATH``.
1036
1037   .. versionchanged:: 3.6
1038      ``SIO_LOOPBACK_FAST_PATH`` was added.
1039
1040.. method:: socket.listen([backlog])
1041
1042   Enable a server to accept connections.  If *backlog* is specified, it must
1043   be at least 0 (if it is lower, it is set to 0); it specifies the number of
1044   unaccepted connections that the system will allow before refusing new
1045   connections. If not specified, a default reasonable value is chosen.
1046
1047   .. versionchanged:: 3.5
1048      The *backlog* parameter is now optional.
1049
1050.. method:: socket.makefile(mode='r', buffering=None, *, encoding=None, \
1051                            errors=None, newline=None)
1052
1053   .. index:: single: I/O control; buffering
1054
1055   Return a :term:`file object` associated with the socket.  The exact returned
1056   type depends on the arguments given to :meth:`makefile`.  These arguments are
1057   interpreted the same way as by the built-in :func:`open` function, except
1058   the only supported *mode* values are ``'r'`` (default), ``'w'`` and ``'b'``.
1059
1060   The socket must be in blocking mode; it can have a timeout, but the file
1061   object's internal buffer may end up in an inconsistent state if a timeout
1062   occurs.
1063
1064   Closing the file object returned by :meth:`makefile` won't close the
1065   original socket unless all other file objects have been closed and
1066   :meth:`socket.close` has been called on the socket object.
1067
1068   .. note::
1069
1070      On Windows, the file-like object created by :meth:`makefile` cannot be
1071      used where a file object with a file descriptor is expected, such as the
1072      stream arguments of :meth:`subprocess.Popen`.
1073
1074
1075.. method:: socket.recv(bufsize[, flags])
1076
1077   Receive data from the socket.  The return value is a bytes object representing the
1078   data received.  The maximum amount of data to be received at once is specified
1079   by *bufsize*.  See the Unix manual page :manpage:`recv(2)` for the meaning of
1080   the optional argument *flags*; it defaults to zero.
1081
1082   .. note::
1083
1084      For best match with hardware and network realities, the value of  *bufsize*
1085      should be a relatively small power of 2, for example, 4096.
1086
1087   .. versionchanged:: 3.5
1088      If the system call is interrupted and the signal handler does not raise
1089      an exception, the method now retries the system call instead of raising
1090      an :exc:`InterruptedError` exception (see :pep:`475` for the rationale).
1091
1092
1093.. method:: socket.recvfrom(bufsize[, flags])
1094
1095   Receive data from the socket.  The return value is a pair ``(bytes, address)``
1096   where *bytes* is a bytes object representing the data received and *address* is the
1097   address of the socket sending the data.  See the Unix manual page
1098   :manpage:`recv(2)` for the meaning of the optional argument *flags*; it defaults
1099   to zero. (The format of *address* depends on the address family --- see above.)
1100
1101   .. versionchanged:: 3.5
1102      If the system call is interrupted and the signal handler does not raise
1103      an exception, the method now retries the system call instead of raising
1104      an :exc:`InterruptedError` exception (see :pep:`475` for the rationale).
1105
1106
1107.. method:: socket.recvmsg(bufsize[, ancbufsize[, flags]])
1108
1109   Receive normal data (up to *bufsize* bytes) and ancillary data from
1110   the socket.  The *ancbufsize* argument sets the size in bytes of
1111   the internal buffer used to receive the ancillary data; it defaults
1112   to 0, meaning that no ancillary data will be received.  Appropriate
1113   buffer sizes for ancillary data can be calculated using
1114   :func:`CMSG_SPACE` or :func:`CMSG_LEN`, and items which do not fit
1115   into the buffer might be truncated or discarded.  The *flags*
1116   argument defaults to 0 and has the same meaning as for
1117   :meth:`recv`.
1118
1119   The return value is a 4-tuple: ``(data, ancdata, msg_flags,
1120   address)``.  The *data* item is a :class:`bytes` object holding the
1121   non-ancillary data received.  The *ancdata* item is a list of zero
1122   or more tuples ``(cmsg_level, cmsg_type, cmsg_data)`` representing
1123   the ancillary data (control messages) received: *cmsg_level* and
1124   *cmsg_type* are integers specifying the protocol level and
1125   protocol-specific type respectively, and *cmsg_data* is a
1126   :class:`bytes` object holding the associated data.  The *msg_flags*
1127   item is the bitwise OR of various flags indicating conditions on
1128   the received message; see your system documentation for details.
1129   If the receiving socket is unconnected, *address* is the address of
1130   the sending socket, if available; otherwise, its value is
1131   unspecified.
1132
1133   On some systems, :meth:`sendmsg` and :meth:`recvmsg` can be used to
1134   pass file descriptors between processes over an :const:`AF_UNIX`
1135   socket.  When this facility is used (it is often restricted to
1136   :const:`SOCK_STREAM` sockets), :meth:`recvmsg` will return, in its
1137   ancillary data, items of the form ``(socket.SOL_SOCKET,
1138   socket.SCM_RIGHTS, fds)``, where *fds* is a :class:`bytes` object
1139   representing the new file descriptors as a binary array of the
1140   native C :c:type:`int` type.  If :meth:`recvmsg` raises an
1141   exception after the system call returns, it will first attempt to
1142   close any file descriptors received via this mechanism.
1143
1144   Some systems do not indicate the truncated length of ancillary data
1145   items which have been only partially received.  If an item appears
1146   to extend beyond the end of the buffer, :meth:`recvmsg` will issue
1147   a :exc:`RuntimeWarning`, and will return the part of it which is
1148   inside the buffer provided it has not been truncated before the
1149   start of its associated data.
1150
1151   On systems which support the :const:`SCM_RIGHTS` mechanism, the
1152   following function will receive up to *maxfds* file descriptors,
1153   returning the message data and a list containing the descriptors
1154   (while ignoring unexpected conditions such as unrelated control
1155   messages being received).  See also :meth:`sendmsg`. ::
1156
1157      import socket, array
1158
1159      def recv_fds(sock, msglen, maxfds):
1160          fds = array.array("i")   # Array of ints
1161          msg, ancdata, flags, addr = sock.recvmsg(msglen, socket.CMSG_LEN(maxfds * fds.itemsize))
1162          for cmsg_level, cmsg_type, cmsg_data in ancdata:
1163              if (cmsg_level == socket.SOL_SOCKET and cmsg_type == socket.SCM_RIGHTS):
1164                  # Append data, ignoring any truncated integers at the end.
1165                  fds.fromstring(cmsg_data[:len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
1166          return msg, list(fds)
1167
1168   Availability: most Unix platforms, possibly others.
1169
1170   .. versionadded:: 3.3
1171
1172   .. versionchanged:: 3.5
1173      If the system call is interrupted and the signal handler does not raise
1174      an exception, the method now retries the system call instead of raising
1175      an :exc:`InterruptedError` exception (see :pep:`475` for the rationale).
1176
1177
1178.. method:: socket.recvmsg_into(buffers[, ancbufsize[, flags]])
1179
1180   Receive normal data and ancillary data from the socket, behaving as
1181   :meth:`recvmsg` would, but scatter the non-ancillary data into a
1182   series of buffers instead of returning a new bytes object.  The
1183   *buffers* argument must be an iterable of objects that export
1184   writable buffers (e.g. :class:`bytearray` objects); these will be
1185   filled with successive chunks of the non-ancillary data until it
1186   has all been written or there are no more buffers.  The operating
1187   system may set a limit (:func:`~os.sysconf` value ``SC_IOV_MAX``)
1188   on the number of buffers that can be used.  The *ancbufsize* and
1189   *flags* arguments have the same meaning as for :meth:`recvmsg`.
1190
1191   The return value is a 4-tuple: ``(nbytes, ancdata, msg_flags,
1192   address)``, where *nbytes* is the total number of bytes of
1193   non-ancillary data written into the buffers, and *ancdata*,
1194   *msg_flags* and *address* are the same as for :meth:`recvmsg`.
1195
1196   Example::
1197
1198      >>> import socket
1199      >>> s1, s2 = socket.socketpair()
1200      >>> b1 = bytearray(b'----')
1201      >>> b2 = bytearray(b'0123456789')
1202      >>> b3 = bytearray(b'--------------')
1203      >>> s1.send(b'Mary had a little lamb')
1204      22
1205      >>> s2.recvmsg_into([b1, memoryview(b2)[2:9], b3])
1206      (22, [], 0, None)
1207      >>> [b1, b2, b3]
1208      [bytearray(b'Mary'), bytearray(b'01 had a 9'), bytearray(b'little lamb---')]
1209
1210   Availability: most Unix platforms, possibly others.
1211
1212   .. versionadded:: 3.3
1213
1214
1215.. method:: socket.recvfrom_into(buffer[, nbytes[, flags]])
1216
1217   Receive data from the socket, writing it into *buffer* instead of creating a
1218   new bytestring.  The return value is a pair ``(nbytes, address)`` where *nbytes* is
1219   the number of bytes received and *address* is the address of the socket sending
1220   the data.  See the Unix manual page :manpage:`recv(2)` for the meaning of the
1221   optional argument *flags*; it defaults to zero.  (The format of *address*
1222   depends on the address family --- see above.)
1223
1224
1225.. method:: socket.recv_into(buffer[, nbytes[, flags]])
1226
1227   Receive up to *nbytes* bytes from the socket, storing the data into a buffer
1228   rather than creating a new bytestring.  If *nbytes* is not specified (or 0),
1229   receive up to the size available in the given buffer.  Returns the number of
1230   bytes received.  See the Unix manual page :manpage:`recv(2)` for the meaning
1231   of the optional argument *flags*; it defaults to zero.
1232
1233
1234.. method:: socket.send(bytes[, flags])
1235
1236   Send data to the socket.  The socket must be connected to a remote socket.  The
1237   optional *flags* argument has the same meaning as for :meth:`recv` above.
1238   Returns the number of bytes sent. Applications are responsible for checking that
1239   all data has been sent; if only some of the data was transmitted, the
1240   application needs to attempt delivery of the remaining data. For further
1241   information on this topic, consult the :ref:`socket-howto`.
1242
1243   .. versionchanged:: 3.5
1244      If the system call is interrupted and the signal handler does not raise
1245      an exception, the method now retries the system call instead of raising
1246      an :exc:`InterruptedError` exception (see :pep:`475` for the rationale).
1247
1248
1249.. method:: socket.sendall(bytes[, flags])
1250
1251   Send data to the socket.  The socket must be connected to a remote socket.  The
1252   optional *flags* argument has the same meaning as for :meth:`recv` above.
1253   Unlike :meth:`send`, this method continues to send data from *bytes* until
1254   either all data has been sent or an error occurs.  ``None`` is returned on
1255   success.  On error, an exception is raised, and there is no way to determine how
1256   much data, if any, was successfully sent.
1257
1258   .. versionchanged:: 3.5
1259      The socket timeout is no more reset each time data is sent successfully.
1260      The socket timeout is now the maximum total duration to send all data.
1261
1262   .. versionchanged:: 3.5
1263      If the system call is interrupted and the signal handler does not raise
1264      an exception, the method now retries the system call instead of raising
1265      an :exc:`InterruptedError` exception (see :pep:`475` for the rationale).
1266
1267
1268.. method:: socket.sendto(bytes, address)
1269            socket.sendto(bytes, flags, address)
1270
1271   Send data to the socket.  The socket should not be connected to a remote socket,
1272   since the destination socket is specified by *address*.  The optional *flags*
1273   argument has the same meaning as for :meth:`recv` above.  Return the number of
1274   bytes sent. (…

Large files files are truncated, but you can click here to view the full file