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 20.. include:: ../includes/wasm-notavail.rst 21 22.. index:: pair: object; socket 23 24The Python interface is a straightforward transliteration of the Unix system 25call and library interface for sockets to Python's object-oriented style: the 26:func:`.socket` function returns a :dfn:`socket object` whose methods implement 27the various socket system calls. Parameter types are somewhat higher-level than 28in the C interface: as with :meth:`read` and :meth:`write` operations on Python 29files, buffer allocation on receive operations is automatic, and buffer length 30is implicit on send operations. 31 32 33.. seealso:: 34 35 Module :mod:`socketserver` 36 Classes that simplify writing network servers. 37 38 Module :mod:`ssl` 39 A TLS/SSL wrapper for socket objects. 40 41 42Socket families 43--------------- 44 45Depending on the system and the build options, various socket families 46are supported by this module. 47 48The address format required by a particular socket object is automatically 49selected based on the address family specified when the socket object was 50created. Socket addresses are represented as follows: 51 52- The address of an :const:`AF_UNIX` socket bound to a file system node 53 is represented as a string, using the file system encoding and the 54 ``'surrogateescape'`` error handler (see :pep:`383`). An address in 55 Linux's abstract namespace is returned as a :term:`bytes-like object` with 56 an initial null byte; note that sockets in this namespace can 57 communicate with normal file system sockets, so programs intended to 58 run on Linux may need to deal with both types of address. A string or 59 bytes-like object can be used for either type of address when 60 passing it as an argument. 61 62 .. versionchanged:: 3.3 63 Previously, :const:`AF_UNIX` socket paths were assumed to use UTF-8 64 encoding. 65 66 .. versionchanged:: 3.5 67 Writable :term:`bytes-like object` is now accepted. 68 69.. _host_port: 70 71- A pair ``(host, port)`` is used for the :const:`AF_INET` address family, 72 where *host* is a string representing either a hostname in internet domain 73 notation like ``'daring.cwi.nl'`` or an IPv4 address like ``'100.50.200.5'``, 74 and *port* is an integer. 75 76 - For IPv4 addresses, two special forms are accepted instead of a host 77 address: ``''`` represents :const:`INADDR_ANY`, which is used to bind to all 78 interfaces, and the string ``'<broadcast>'`` represents 79 :const:`INADDR_BROADCAST`. This behavior is not compatible with IPv6, 80 therefore, you may want to avoid these if you intend to support IPv6 with your 81 Python programs. 82 83- For :const:`AF_INET6` address family, a four-tuple ``(host, port, flowinfo, 84 scope_id)`` is used, where *flowinfo* and *scope_id* represent the ``sin6_flowinfo`` 85 and ``sin6_scope_id`` members in :const:`struct sockaddr_in6` in C. For 86 :mod:`socket` module methods, *flowinfo* and *scope_id* can be omitted just for 87 backward compatibility. Note, however, omission of *scope_id* can cause problems 88 in manipulating scoped IPv6 addresses. 89 90 .. versionchanged:: 3.7 91 For multicast addresses (with *scope_id* meaningful) *address* may not contain 92 ``%scope_id`` (or ``zone id``) part. This information is superfluous and may 93 be safely omitted (recommended). 94 95- :const:`AF_NETLINK` sockets are represented as pairs ``(pid, groups)``. 96 97- Linux-only support for TIPC is available using the :const:`AF_TIPC` 98 address family. TIPC is an open, non-IP based networked protocol designed 99 for use in clustered computer environments. Addresses are represented by a 100 tuple, and the fields depend on the address type. The general tuple form is 101 ``(addr_type, v1, v2, v3 [, scope])``, where: 102 103 - *addr_type* is one of :const:`TIPC_ADDR_NAMESEQ`, :const:`TIPC_ADDR_NAME`, 104 or :const:`TIPC_ADDR_ID`. 105 - *scope* is one of :const:`TIPC_ZONE_SCOPE`, :const:`TIPC_CLUSTER_SCOPE`, and 106 :const:`TIPC_NODE_SCOPE`. 107 - If *addr_type* is :const:`TIPC_ADDR_NAME`, then *v1* is the server type, *v2* is 108 the port identifier, and *v3* should be 0. 109 110 If *addr_type* is :const:`TIPC_ADDR_NAMESEQ`, then *v1* is the server type, *v2* 111 is the lower port number, and *v3* is the upper port number. 112 113 If *addr_type* is :const:`TIPC_ADDR_ID`, then *v1* is the node, *v2* is the 114 reference, and *v3* should be set to 0. 115 116- A tuple ``(interface, )`` is used for the :const:`AF_CAN` address family, 117 where *interface* is a string representing a network interface name like 118 ``'can0'``. The network interface name ``''`` can be used to receive packets 119 from all network interfaces of this family. 120 121 - :const:`CAN_ISOTP` protocol require a tuple ``(interface, rx_addr, tx_addr)`` 122 where both additional parameters are unsigned long integer that represent a 123 CAN identifier (standard or extended). 124 - :const:`CAN_J1939` protocol require a tuple ``(interface, name, pgn, addr)`` 125 where additional parameters are 64-bit unsigned integer representing the 126 ECU name, a 32-bit unsigned integer representing the Parameter Group Number 127 (PGN), and an 8-bit integer representing the address. 128 129- A string or a tuple ``(id, unit)`` is used for the :const:`SYSPROTO_CONTROL` 130 protocol of the :const:`PF_SYSTEM` family. The string is the name of a 131 kernel control using a dynamically assigned ID. The tuple can be used if ID 132 and unit number of the kernel control are known or if a registered ID is 133 used. 134 135 .. versionadded:: 3.3 136 137- :const:`AF_BLUETOOTH` supports the following protocols and address 138 formats: 139 140 - :const:`BTPROTO_L2CAP` accepts ``(bdaddr, psm)`` where ``bdaddr`` is 141 the Bluetooth address as a string and ``psm`` is an integer. 142 143 - :const:`BTPROTO_RFCOMM` accepts ``(bdaddr, channel)`` where ``bdaddr`` 144 is the Bluetooth address as a string and ``channel`` is an integer. 145 146 - :const:`BTPROTO_HCI` accepts ``(device_id,)`` where ``device_id`` is 147 either an integer or a string with the Bluetooth address of the 148 interface. (This depends on your OS; NetBSD and DragonFlyBSD expect 149 a Bluetooth address while everything else expects an integer.) 150 151 .. versionchanged:: 3.2 152 NetBSD and DragonFlyBSD support added. 153 154 - :const:`BTPROTO_SCO` accepts ``bdaddr`` where ``bdaddr`` is a 155 :class:`bytes` object containing the Bluetooth address in a 156 string format. (ex. ``b'12:23:34:45:56:67'``) This protocol is not 157 supported under FreeBSD. 158 159- :const:`AF_ALG` is a Linux-only socket based interface to Kernel 160 cryptography. An algorithm socket is configured with a tuple of two to four 161 elements ``(type, name [, feat [, mask]])``, where: 162 163 - *type* is the algorithm type as string, e.g. ``aead``, ``hash``, 164 ``skcipher`` or ``rng``. 165 166 - *name* is the algorithm name and operation mode as string, e.g. 167 ``sha256``, ``hmac(sha256)``, ``cbc(aes)`` or ``drbg_nopr_ctr_aes256``. 168 169 - *feat* and *mask* are unsigned 32bit integers. 170 171 .. availability:: Linux >= 2.6.38. 172 173 Some algorithm types require more recent Kernels. 174 175 .. versionadded:: 3.6 176 177- :const:`AF_VSOCK` allows communication between virtual machines and 178 their hosts. The sockets are represented as a ``(CID, port)`` tuple 179 where the context ID or CID and port are integers. 180 181 .. availability:: Linux >= 3.9 182 183 See :manpage:`vsock(7)` 184 185 .. versionadded:: 3.7 186 187- :const:`AF_PACKET` is a low-level interface directly to network devices. 188 The packets are represented by the tuple 189 ``(ifname, proto[, pkttype[, hatype[, addr]]])`` where: 190 191 - *ifname* - String specifying the device name. 192 - *proto* - An in network-byte-order integer specifying the Ethernet 193 protocol number. 194 - *pkttype* - Optional integer specifying the packet type: 195 196 - ``PACKET_HOST`` (the default) - Packet addressed to the local host. 197 - ``PACKET_BROADCAST`` - Physical-layer broadcast packet. 198 - ``PACKET_MULTICAST`` - Packet sent to a physical-layer multicast address. 199 - ``PACKET_OTHERHOST`` - Packet to some other host that has been caught by 200 a device driver in promiscuous mode. 201 - ``PACKET_OUTGOING`` - Packet originating from the local host that is 202 looped back to a packet socket. 203 - *hatype* - Optional integer specifying the ARP hardware address type. 204 - *addr* - Optional bytes-like object specifying the hardware physical 205 address, whose interpretation depends on the device. 206 207 .. availability:: Linux >= 2.2. 208 209- :const:`AF_QIPCRTR` is a Linux-only socket based interface for communicating 210 with services running on co-processors in Qualcomm platforms. The address 211 family is represented as a ``(node, port)`` tuple where the *node* and *port* 212 are non-negative integers. 213 214 .. availability:: Linux >= 4.7. 215 216 .. versionadded:: 3.8 217 218- :const:`IPPROTO_UDPLITE` is a variant of UDP which allows you to specify 219 what portion of a packet is covered with the checksum. It adds two socket 220 options that you can change. 221 ``self.setsockopt(IPPROTO_UDPLITE, UDPLITE_SEND_CSCOV, length)`` will 222 change what portion of outgoing packets are covered by the checksum and 223 ``self.setsockopt(IPPROTO_UDPLITE, UDPLITE_RECV_CSCOV, length)`` will 224 filter out packets which cover too little of their data. In both cases 225 ``length`` should be in ``range(8, 2**16, 8)``. 226 227 Such a socket should be constructed with 228 ``socket(AF_INET, SOCK_DGRAM, IPPROTO_UDPLITE)`` for IPv4 or 229 ``socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDPLITE)`` for IPv6. 230 231 .. availability:: Linux >= 2.6.20, FreeBSD >= 10.1 232 233 .. versionadded:: 3.9 234 235If you use a hostname in the *host* portion of IPv4/v6 socket address, the 236program may show a nondeterministic behavior, as Python uses the first address 237returned from the DNS resolution. The socket address will be resolved 238differently into an actual IPv4/v6 address, depending on the results from DNS 239resolution and/or the host configuration. For deterministic behavior use a 240numeric address in *host* portion. 241 242All errors raise exceptions. The normal exceptions for invalid argument types 243and out-of-memory conditions can be raised. Errors 244related to socket or address semantics raise :exc:`OSError` or one of its 245subclasses. 246 247Non-blocking mode is supported through :meth:`~socket.setblocking`. A 248generalization of this based on timeouts is supported through 249:meth:`~socket.settimeout`. 250 251 252Module contents 253--------------- 254 255The module :mod:`socket` exports the following elements. 256 257 258Exceptions 259^^^^^^^^^^ 260 261.. exception:: error 262 263 A deprecated alias of :exc:`OSError`. 264 265 .. versionchanged:: 3.3 266 Following :pep:`3151`, this class was made an alias of :exc:`OSError`. 267 268 269.. exception:: herror 270 271 A subclass of :exc:`OSError`, this exception is raised for 272 address-related errors, i.e. for functions that use *h_errno* in the POSIX 273 C API, including :func:`gethostbyname_ex` and :func:`gethostbyaddr`. 274 The accompanying value is a pair ``(h_errno, string)`` representing an 275 error returned by a library call. *h_errno* is a numeric value, while 276 *string* represents the description of *h_errno*, as returned by the 277 :c:func:`hstrerror` C function. 278 279 .. versionchanged:: 3.3 280 This class was made a subclass of :exc:`OSError`. 281 282.. exception:: gaierror 283 284 A subclass of :exc:`OSError`, this exception is raised for 285 address-related errors by :func:`getaddrinfo` and :func:`getnameinfo`. 286 The accompanying value is a pair ``(error, string)`` representing an error 287 returned by a library call. *string* represents the description of 288 *error*, as returned by the :c:func:`gai_strerror` C function. The 289 numeric *error* value will match one of the :const:`EAI_\*` constants 290 defined in this module. 291 292 .. versionchanged:: 3.3 293 This class was made a subclass of :exc:`OSError`. 294 295.. exception:: timeout 296 297 A deprecated alias of :exc:`TimeoutError`. 298 299 A subclass of :exc:`OSError`, this exception is raised when a timeout 300 occurs on a socket which has had timeouts enabled via a prior call to 301 :meth:`~socket.settimeout` (or implicitly through 302 :func:`~socket.setdefaulttimeout`). The accompanying value is a string 303 whose value is currently always "timed out". 304 305 .. versionchanged:: 3.3 306 This class was made a subclass of :exc:`OSError`. 307 308 .. versionchanged:: 3.10 309 This class was made an alias of :exc:`TimeoutError`. 310 311 312Constants 313^^^^^^^^^ 314 315 The AF_* and SOCK_* constants are now :class:`AddressFamily` and 316 :class:`SocketKind` :class:`.IntEnum` collections. 317 318 .. versionadded:: 3.4 319 320.. data:: AF_UNIX 321 AF_INET 322 AF_INET6 323 324 These constants represent the address (and protocol) families, used for the 325 first argument to :func:`.socket`. If the :const:`AF_UNIX` constant is not 326 defined then this protocol is unsupported. More constants may be available 327 depending on the system. 328 329 330.. data:: SOCK_STREAM 331 SOCK_DGRAM 332 SOCK_RAW 333 SOCK_RDM 334 SOCK_SEQPACKET 335 336 These constants represent the socket types, used for the second argument to 337 :func:`.socket`. More constants may be available depending on the system. 338 (Only :const:`SOCK_STREAM` and :const:`SOCK_DGRAM` appear to be generally 339 useful.) 340 341.. data:: SOCK_CLOEXEC 342 SOCK_NONBLOCK 343 344 These two constants, if defined, can be combined with the socket types and 345 allow you to set some flags atomically (thus avoiding possible race 346 conditions and the need for separate calls). 347 348 .. seealso:: 349 350 `Secure File Descriptor Handling <https://udrepper.livejournal.com/20407.html>`_ 351 for a more thorough explanation. 352 353 .. availability:: Linux >= 2.6.27. 354 355 .. versionadded:: 3.2 356 357.. data:: SO_* 358 SOMAXCONN 359 MSG_* 360 SOL_* 361 SCM_* 362 IPPROTO_* 363 IPPORT_* 364 INADDR_* 365 IP_* 366 IPV6_* 367 EAI_* 368 AI_* 369 NI_* 370 TCP_* 371 372 Many constants of these forms, documented in the Unix documentation on sockets 373 and/or the IP protocol, are also defined in the socket module. They are 374 generally used in arguments to the :meth:`setsockopt` and :meth:`getsockopt` 375 methods of socket objects. In most cases, only those symbols that are defined 376 in the Unix header files are defined; for a few symbols, default values are 377 provided. 378 379 .. versionchanged:: 3.6 380 ``SO_DOMAIN``, ``SO_PROTOCOL``, ``SO_PEERSEC``, ``SO_PASSSEC``, 381 ``TCP_USER_TIMEOUT``, ``TCP_CONGESTION`` were added. 382 383 .. versionchanged:: 3.6.5 384 On Windows, ``TCP_FASTOPEN``, ``TCP_KEEPCNT`` appear if run-time Windows 385 supports. 386 387 .. versionchanged:: 3.7 388 ``TCP_NOTSENT_LOWAT`` was added. 389 390 On Windows, ``TCP_KEEPIDLE``, ``TCP_KEEPINTVL`` appear if run-time Windows 391 supports. 392 393 .. versionchanged:: 3.10 394 ``IP_RECVTOS`` was added. 395 Added ``TCP_KEEPALIVE``. On MacOS this constant can be used in the same 396 way that ``TCP_KEEPIDLE`` is used on Linux. 397 398 .. versionchanged:: 3.11 399 Added ``TCP_CONNECTION_INFO``. On MacOS this constant can be used in the 400 same way that ``TCP_INFO`` is used on Linux and BSD. 401 402.. data:: AF_CAN 403 PF_CAN 404 SOL_CAN_* 405 CAN_* 406 407 Many constants of these forms, documented in the Linux documentation, are 408 also defined in the socket module. 409 410 .. availability:: Linux >= 2.6.25, NetBSD >= 8. 411 412 .. versionadded:: 3.3 413 414 .. versionchanged:: 3.11 415 NetBSD support was added. 416 417.. data:: CAN_BCM 418 CAN_BCM_* 419 420 CAN_BCM, in the CAN protocol family, is the broadcast manager (BCM) protocol. 421 Broadcast manager constants, documented in the Linux documentation, are also 422 defined in the socket module. 423 424 .. availability:: Linux >= 2.6.25. 425 426 .. note:: 427 The :data:`CAN_BCM_CAN_FD_FRAME` flag is only available on Linux >= 4.8. 428 429 .. versionadded:: 3.4 430 431.. data:: CAN_RAW_FD_FRAMES 432 433 Enables CAN FD support in a CAN_RAW socket. This is disabled by default. 434 This allows your application to send both CAN and CAN FD frames; however, 435 you must accept both CAN and CAN FD frames when reading from the socket. 436 437 This constant is documented in the Linux documentation. 438 439 .. availability:: Linux >= 3.6. 440 441 .. versionadded:: 3.5 442 443.. data:: CAN_RAW_JOIN_FILTERS 444 445 Joins the applied CAN filters such that only CAN frames that match all 446 given CAN filters are passed to user space. 447 448 This constant is documented in the Linux documentation. 449 450 .. availability:: Linux >= 4.1. 451 452 .. versionadded:: 3.9 453 454.. data:: CAN_ISOTP 455 456 CAN_ISOTP, in the CAN protocol family, is the ISO-TP (ISO 15765-2) protocol. 457 ISO-TP constants, documented in the Linux documentation. 458 459 .. availability:: Linux >= 2.6.25. 460 461 .. versionadded:: 3.7 462 463.. data:: CAN_J1939 464 465 CAN_J1939, in the CAN protocol family, is the SAE J1939 protocol. 466 J1939 constants, documented in the Linux documentation. 467 468 .. availability:: Linux >= 5.4. 469 470 .. versionadded:: 3.9 471 472 473.. data:: AF_PACKET 474 PF_PACKET 475 PACKET_* 476 477 Many constants of these forms, documented in the Linux documentation, are 478 also defined in the socket module. 479 480 .. availability:: Linux >= 2.2. 481 482 483.. data:: AF_RDS 484 PF_RDS 485 SOL_RDS 486 RDS_* 487 488 Many constants of these forms, documented in the Linux documentation, are 489 also defined in the socket module. 490 491 .. availability:: Linux >= 2.6.30. 492 493 .. versionadded:: 3.3 494 495 496.. data:: SIO_RCVALL 497 SIO_KEEPALIVE_VALS 498 SIO_LOOPBACK_FAST_PATH 499 RCVALL_* 500 501 Constants for Windows' WSAIoctl(). The constants are used as arguments to the 502 :meth:`~socket.socket.ioctl` method of socket objects. 503 504 .. versionchanged:: 3.6 505 ``SIO_LOOPBACK_FAST_PATH`` was added. 506 507 508.. data:: TIPC_* 509 510 TIPC related constants, matching the ones exported by the C socket API. See 511 the TIPC documentation for more information. 512 513.. data:: AF_ALG 514 SOL_ALG 515 ALG_* 516 517 Constants for Linux Kernel cryptography. 518 519 .. availability:: Linux >= 2.6.38. 520 521 .. versionadded:: 3.6 522 523 524.. data:: AF_VSOCK 525 IOCTL_VM_SOCKETS_GET_LOCAL_CID 526 VMADDR* 527 SO_VM* 528 529 Constants for Linux host/guest communication. 530 531 .. availability:: Linux >= 4.8. 532 533 .. versionadded:: 3.7 534 535.. data:: AF_LINK 536 537 .. availability:: BSD, macOS. 538 539 .. versionadded:: 3.4 540 541.. data:: has_ipv6 542 543 This constant contains a boolean value which indicates if IPv6 is supported on 544 this platform. 545 546.. data:: BDADDR_ANY 547 BDADDR_LOCAL 548 549 These are string constants containing Bluetooth addresses with special 550 meanings. For example, :const:`BDADDR_ANY` can be used to indicate 551 any address when specifying the binding socket with 552 :const:`BTPROTO_RFCOMM`. 553 554.. data:: HCI_FILTER 555 HCI_TIME_STAMP 556 HCI_DATA_DIR 557 558 For use with :const:`BTPROTO_HCI`. :const:`HCI_FILTER` is not 559 available for NetBSD or DragonFlyBSD. :const:`HCI_TIME_STAMP` and 560 :const:`HCI_DATA_DIR` are not available for FreeBSD, NetBSD, or 561 DragonFlyBSD. 562 563.. data:: AF_QIPCRTR 564 565 Constant for Qualcomm's IPC router protocol, used to communicate with 566 service providing remote processors. 567 568 .. availability:: Linux >= 4.7. 569 570.. data:: SCM_CREDS2 571 LOCAL_CREDS 572 LOCAL_CREDS_PERSISTENT 573 574 LOCAL_CREDS and LOCAL_CREDS_PERSISTENT can be used 575 with SOCK_DGRAM, SOCK_STREAM sockets, equivalent to 576 Linux/DragonFlyBSD SO_PASSCRED, while LOCAL_CREDS 577 sends the credentials at first read, LOCAL_CREDS_PERSISTENT 578 sends for each read, SCM_CREDS2 must be then used for 579 the latter for the message type. 580 581 .. versionadded:: 3.11 582 583 .. availability:: FreeBSD. 584 585.. data:: SO_INCOMING_CPU 586 587 Constant to optimize CPU locality, to be used in conjunction with 588 :data:`SO_REUSEPORT`. 589 590 .. versionadded:: 3.11 591 592 .. availability:: Linux >= 3.9 593 594Functions 595^^^^^^^^^ 596 597Creating sockets 598'''''''''''''''' 599 600The following functions all create :ref:`socket objects <socket-objects>`. 601 602 603.. class:: socket(family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None) 604 605 Create a new socket using the given address family, socket type and protocol 606 number. The address family should be :const:`AF_INET` (the default), 607 :const:`AF_INET6`, :const:`AF_UNIX`, :const:`AF_CAN`, :const:`AF_PACKET`, 608 or :const:`AF_RDS`. The socket type should be :const:`SOCK_STREAM` (the 609 default), :const:`SOCK_DGRAM`, :const:`SOCK_RAW` or perhaps one of the other 610 ``SOCK_`` constants. The protocol number is usually zero and may be omitted 611 or in the case where the address family is :const:`AF_CAN` the protocol 612 should be one of :const:`CAN_RAW`, :const:`CAN_BCM`, :const:`CAN_ISOTP` or 613 :const:`CAN_J1939`. 614 615 If *fileno* is specified, the values for *family*, *type*, and *proto* are 616 auto-detected from the specified file descriptor. Auto-detection can be 617 overruled by calling the function with explicit *family*, *type*, or *proto* 618 arguments. This only affects how Python represents e.g. the return value 619 of :meth:`socket.getpeername` but not the actual OS resource. Unlike 620 :func:`socket.fromfd`, *fileno* will return the same socket and not a 621 duplicate. This may help close a detached socket using 622 :meth:`socket.close()`. 623 624 The newly created socket is :ref:`non-inheritable <fd_inheritance>`. 625 626 .. audit-event:: socket.__new__ self,family,type,protocol socket.socket 627 628 .. versionchanged:: 3.3 629 The AF_CAN family was added. 630 The AF_RDS family was added. 631 632 .. versionchanged:: 3.4 633 The CAN_BCM protocol was added. 634 635 .. versionchanged:: 3.4 636 The returned socket is now non-inheritable. 637 638 .. versionchanged:: 3.7 639 The CAN_ISOTP protocol was added. 640 641 .. versionchanged:: 3.7 642 When :const:`SOCK_NONBLOCK` or :const:`SOCK_CLOEXEC` 643 bit flags are applied to *type* they are cleared, and 644 :attr:`socket.type` will not reflect them. They are still passed 645 to the underlying system ``socket()`` call. Therefore, 646 647 :: 648 649 sock = socket.socket( 650 socket.AF_INET, 651 socket.SOCK_STREAM | socket.SOCK_NONBLOCK) 652 653 will still create a non-blocking socket on OSes that support 654 ``SOCK_NONBLOCK``, but ``sock.type`` will be set to 655 ``socket.SOCK_STREAM``. 656 657 .. versionchanged:: 3.9 658 The CAN_J1939 protocol was added. 659 660 .. versionchanged:: 3.10 661 The IPPROTO_MPTCP protocol was added. 662 663.. function:: socketpair([family[, type[, proto]]]) 664 665 Build a pair of connected socket objects using the given address family, socket 666 type, and protocol number. Address family, socket type, and protocol number are 667 as for the :func:`.socket` function above. The default family is :const:`AF_UNIX` 668 if defined on the platform; otherwise, the default is :const:`AF_INET`. 669 670 The newly created sockets are :ref:`non-inheritable <fd_inheritance>`. 671 672 .. versionchanged:: 3.2 673 The returned socket objects now support the whole socket API, rather 674 than a subset. 675 676 .. versionchanged:: 3.4 677 The returned sockets are now non-inheritable. 678 679 .. versionchanged:: 3.5 680 Windows support added. 681 682 683.. function:: create_connection(address, timeout=GLOBAL_DEFAULT, source_address=None, *, all_errors=False) 684 685 Connect to a TCP service listening on the internet *address* (a 2-tuple 686 ``(host, port)``), and return the socket object. This is a higher-level 687 function than :meth:`socket.connect`: if *host* is a non-numeric hostname, 688 it will try to resolve it for both :data:`AF_INET` and :data:`AF_INET6`, 689 and then try to connect to all possible addresses in turn until a 690 connection succeeds. This makes it easy to write clients that are 691 compatible to both IPv4 and IPv6. 692 693 Passing the optional *timeout* parameter will set the timeout on the 694 socket instance before attempting to connect. If no *timeout* is 695 supplied, the global default timeout setting returned by 696 :func:`getdefaulttimeout` is used. 697 698 If supplied, *source_address* must be a 2-tuple ``(host, port)`` for the 699 socket to bind to as its source address before connecting. If host or port 700 are '' or 0 respectively the OS default behavior will be used. 701 702 When a connection cannot be created, an exception is raised. By default, 703 it is the exception from the last address in the list. If *all_errors* 704 is ``True``, it is an :exc:`ExceptionGroup` containing the errors of all 705 attempts. 706 707 .. versionchanged:: 3.2 708 *source_address* was added. 709 710 .. versionchanged:: 3.11 711 *all_errors* was added. 712 713 714.. function:: create_server(address, *, family=AF_INET, backlog=None, reuse_port=False, dualstack_ipv6=False) 715 716 Convenience function which creates a TCP socket bound to *address* (a 2-tuple 717 ``(host, port)``) and return the socket object. 718 719 *family* should be either :data:`AF_INET` or :data:`AF_INET6`. 720 *backlog* is the queue size passed to :meth:`socket.listen`; if not specified 721 , a default reasonable value is chosen. 722 *reuse_port* dictates whether to set the :data:`SO_REUSEPORT` socket option. 723 724 If *dualstack_ipv6* is true and the platform supports it the socket will 725 be able to accept both IPv4 and IPv6 connections, else it will raise 726 :exc:`ValueError`. Most POSIX platforms and Windows are supposed to support 727 this functionality. 728 When this functionality is enabled the address returned by 729 :meth:`socket.getpeername` when an IPv4 connection occurs will be an IPv6 730 address represented as an IPv4-mapped IPv6 address. 731 If *dualstack_ipv6* is false it will explicitly disable this functionality 732 on platforms that enable it by default (e.g. Linux). 733 This parameter can be used in conjunction with :func:`has_dualstack_ipv6`: 734 735 :: 736 737 import socket 738 739 addr = ("", 8080) # all interfaces, port 8080 740 if socket.has_dualstack_ipv6(): 741 s = socket.create_server(addr, family=socket.AF_INET6, dualstack_ipv6=True) 742 else: 743 s = socket.create_server(addr) 744 745 .. note:: 746 On POSIX platforms the :data:`SO_REUSEADDR` socket option is set in order to 747 immediately reuse previous sockets which were bound on the same *address* 748 and remained in TIME_WAIT state. 749 750 .. versionadded:: 3.8 751 752.. function:: has_dualstack_ipv6() 753 754 Return ``True`` if the platform supports creating a TCP socket which can 755 handle both IPv4 and IPv6 connections. 756 757 .. versionadded:: 3.8 758 759.. function:: fromfd(fd, family, type, proto=0) 760 761 Duplicate the file descriptor *fd* (an integer as returned by a file object's 762 :meth:`fileno` method) and build a socket object from the result. Address 763 family, socket type and protocol number are as for the :func:`.socket` function 764 above. The file descriptor should refer to a socket, but this is not checked --- 765 subsequent operations on the object may fail if the file descriptor is invalid. 766 This function is rarely needed, but can be used to get or set socket options on 767 a socket passed to a program as standard input or output (such as a server 768 started by the Unix inet daemon). The socket is assumed to be in blocking mode. 769 770 The newly created socket is :ref:`non-inheritable <fd_inheritance>`. 771 772 .. versionchanged:: 3.4 773 The returned socket is now non-inheritable. 774 775 776.. function:: fromshare(data) 777 778 Instantiate a socket from data obtained from the :meth:`socket.share` 779 method. The socket is assumed to be in blocking mode. 780 781 .. availability:: Windows. 782 783 .. versionadded:: 3.3 784 785 786.. data:: SocketType 787 788 This is a Python type object that represents the socket object type. It is the 789 same as ``type(socket(...))``. 790 791 792Other functions 793''''''''''''''' 794 795The :mod:`socket` module also offers various network-related services: 796 797 798.. function:: close(fd) 799 800 Close a socket file descriptor. This is like :func:`os.close`, but for 801 sockets. On some platforms (most noticeable Windows) :func:`os.close` 802 does not work for socket file descriptors. 803 804 .. versionadded:: 3.7 805 806.. function:: getaddrinfo(host, port, family=0, type=0, proto=0, flags=0) 807 808 Translate the *host*/*port* argument into a sequence of 5-tuples that contain 809 all the necessary arguments for creating a socket connected to that service. 810 *host* is a domain name, a string representation of an IPv4/v6 address 811 or ``None``. *port* is a string service name such as ``'http'``, a numeric 812 port number or ``None``. By passing ``None`` as the value of *host* 813 and *port*, you can pass ``NULL`` to the underlying C API. 814 815 The *family*, *type* and *proto* arguments can be optionally specified 816 in order to narrow the list of addresses returned. Passing zero as a 817 value for each of these arguments selects the full range of results. 818 The *flags* argument can be one or several of the ``AI_*`` constants, 819 and will influence how results are computed and returned. 820 For example, :const:`AI_NUMERICHOST` will disable domain name resolution 821 and will raise an error if *host* is a domain name. 822 823 The function returns a list of 5-tuples with the following structure: 824 825 ``(family, type, proto, canonname, sockaddr)`` 826 827 In these tuples, *family*, *type*, *proto* are all integers and are 828 meant to be passed to the :func:`.socket` function. *canonname* will be 829 a string representing the canonical name of the *host* if 830 :const:`AI_CANONNAME` is part of the *flags* argument; else *canonname* 831 will be empty. *sockaddr* is a tuple describing a socket address, whose 832 format depends on the returned *family* (a ``(address, port)`` 2-tuple for 833 :const:`AF_INET`, a ``(address, port, flowinfo, scope_id)`` 4-tuple for 834 :const:`AF_INET6`), and is meant to be passed to the :meth:`socket.connect` 835 method. 836 837 .. audit-event:: socket.getaddrinfo host,port,family,type,protocol socket.getaddrinfo 838 839 The following example fetches address information for a hypothetical TCP 840 connection to ``example.org`` on port 80 (results may differ on your 841 system if IPv6 isn't enabled):: 842 843 >>> socket.getaddrinfo("example.org", 80, proto=socket.IPPROTO_TCP) 844 [(socket.AF_INET6, socket.SOCK_STREAM, 845 6, '', ('2606:2800:220:1:248:1893:25c8:1946', 80, 0, 0)), 846 (socket.AF_INET, socket.SOCK_STREAM, 847 6, '', ('93.184.216.34', 80))] 848 849 .. versionchanged:: 3.2 850 parameters can now be passed using keyword arguments. 851 852 .. versionchanged:: 3.7 853 for IPv6 multicast addresses, string representing an address will not 854 contain ``%scope_id`` part. 855 856.. function:: getfqdn([name]) 857 858 Return a fully qualified domain name for *name*. If *name* is omitted or empty, 859 it is interpreted as the local host. To find the fully qualified name, the 860 hostname returned by :func:`gethostbyaddr` is checked, followed by aliases for the 861 host, if available. The first name which includes a period is selected. In 862 case no fully qualified domain name is available and *name* was provided, 863 it is returned unchanged. If *name* was empty or equal to ``'0.0.0.0'``, 864 the hostname from :func:`gethostname` is returned. 865 866 867.. function:: gethostbyname(hostname) 868 869 Translate a host name to IPv4 address format. The IPv4 address is returned as a 870 string, such as ``'100.50.200.5'``. If the host name is an IPv4 address itself 871 it is returned unchanged. See :func:`gethostbyname_ex` for a more complete 872 interface. :func:`gethostbyname` does not support IPv6 name resolution, and 873 :func:`getaddrinfo` should be used instead for IPv4/v6 dual stack support. 874 875 .. audit-event:: socket.gethostbyname hostname socket.gethostbyname 876 877 .. availability:: not WASI. 878 879 880.. function:: gethostbyname_ex(hostname) 881 882 Translate a host name to IPv4 address format, extended interface. Return a 883 triple ``(hostname, aliaslist, ipaddrlist)`` where *hostname* is the host's 884 primary host name, *aliaslist* is a (possibly 885 empty) list of alternative host names for the same address, and *ipaddrlist* is 886 a list of IPv4 addresses for the same interface on the same host (often but not 887 always a single address). :func:`gethostbyname_ex` does not support IPv6 name 888 resolution, and :func:`getaddrinfo` should be used instead for IPv4/v6 dual 889 stack support. 890 891 .. audit-event:: socket.gethostbyname hostname socket.gethostbyname_ex 892 893 .. availability:: not WASI. 894 895 896.. function:: gethostname() 897 898 Return a string containing the hostname of the machine where the Python 899 interpreter is currently executing. 900 901 .. audit-event:: socket.gethostname "" socket.gethostname 902 903 Note: :func:`gethostname` doesn't always return the fully qualified domain 904 name; use :func:`getfqdn` for that. 905 906 .. availability:: not WASI. 907 908 909.. function:: gethostbyaddr(ip_address) 910 911 Return a triple ``(hostname, aliaslist, ipaddrlist)`` where *hostname* is the 912 primary host name responding to the given *ip_address*, *aliaslist* is a 913 (possibly empty) list of alternative host names for the same address, and 914 *ipaddrlist* is a list of IPv4/v6 addresses for the same interface on the same 915 host (most likely containing only a single address). To find the fully qualified 916 domain name, use the function :func:`getfqdn`. :func:`gethostbyaddr` supports 917 both IPv4 and IPv6. 918 919 .. audit-event:: socket.gethostbyaddr ip_address socket.gethostbyaddr 920 921 .. availability:: not WASI. 922 923 924.. function:: getnameinfo(sockaddr, flags) 925 926 Translate a socket address *sockaddr* into a 2-tuple ``(host, port)``. Depending 927 on the settings of *flags*, the result can contain a fully qualified domain name 928 or numeric address representation in *host*. Similarly, *port* can contain a 929 string port name or a numeric port number. 930 931 For IPv6 addresses, ``%scope_id`` is appended to the host part if *sockaddr* 932 contains meaningful *scope_id*. Usually this happens for multicast addresses. 933 934 For more information about *flags* you can consult :manpage:`getnameinfo(3)`. 935 936 .. audit-event:: socket.getnameinfo sockaddr socket.getnameinfo 937 938 .. availability:: not WASI. 939 940 941.. function:: getprotobyname(protocolname) 942 943 Translate an internet protocol name (for example, ``'icmp'``) to a constant 944 suitable for passing as the (optional) third argument to the :func:`.socket` 945 function. This is usually only needed for sockets opened in "raw" mode 946 (:const:`SOCK_RAW`); for the normal socket modes, the correct protocol is chosen 947 automatically if the protocol is omitted or zero. 948 949 .. availability:: not WASI. 950 951 952.. function:: getservbyname(servicename[, protocolname]) 953 954 Translate an internet service name and protocol name to a port number for that 955 service. The optional protocol name, if given, should be ``'tcp'`` or 956 ``'udp'``, otherwise any protocol will match. 957 958 .. audit-event:: socket.getservbyname servicename,protocolname socket.getservbyname 959 960 .. availability:: not WASI. 961 962 963.. function:: getservbyport(port[, protocolname]) 964 965 Translate an internet port number and protocol name to a service name for that 966 service. The optional protocol name, if given, should be ``'tcp'`` or 967 ``'udp'``, otherwise any protocol will match. 968 969 .. audit-event:: socket.getservbyport port,protocolname socket.getservbyport 970 971 .. availability:: not WASI. 972 973 974.. function:: ntohl(x) 975 976 Convert 32-bit positive integers from network to host byte order. On machines 977 where the host byte order is the same as network byte order, this is a no-op; 978 otherwise, it performs a 4-byte swap operation. 979 980 981.. function:: ntohs(x) 982 983 Convert 16-bit positive integers from network to host byte order. On machines 984 where the host byte order is the same as network byte order, this is a no-op; 985 otherwise, it performs a 2-byte swap operation. 986 987 .. versionchanged:: 3.10 988 Raises :exc:`OverflowError` if *x* does not fit in a 16-bit unsigned 989 integer. 990 991 992.. function:: htonl(x) 993 994 Convert 32-bit positive integers from host to network byte order. On machines 995 where the host byte order is the same as network byte order, this is a no-op; 996 otherwise, it performs a 4-byte swap operation. 997 998 999.. function:: htons(x) 1000 1001 Convert 16-bit positive integers from host to network byte order. On machines 1002 where the host byte order is the same as network byte order, this is a no-op; 1003 otherwise, it performs a 2-byte swap operation. 1004 1005 .. versionchanged:: 3.10 1006 Raises :exc:`OverflowError` if *x* does not fit in a 16-bit unsigned 1007 integer. 1008 1009 1010.. function:: inet_aton(ip_string) 1011 1012 Convert an IPv4 address from dotted-quad string format (for example, 1013 '123.45.67.89') to 32-bit packed binary format, as a bytes object four characters in 1014 length. This is useful when conversing with a program that uses the standard C 1015 library and needs objects of type :c:struct:`in_addr`, which is the C type 1016 for the 32-bit packed binary this function returns. 1017 1018 :func:`inet_aton` also accepts strings with less than three dots; see the 1019 Unix manual page :manpage:`inet(3)` for details. 1020 1021 If the IPv4 address string passed to this function is invalid, 1022 :exc:`OSError` will be raised. Note that exactly what is valid depends on 1023 the underlying C implementation of :c:func:`inet_aton`. 1024 1025 :func:`inet_aton` does not support IPv6, and :func:`inet_pton` should be used 1026 instead for IPv4/v6 dual stack support. 1027 1028 1029.. function:: inet_ntoa(packed_ip) 1030 1031 Convert a 32-bit packed IPv4 address (a :term:`bytes-like object` four 1032 bytes in length) to its standard dotted-quad string representation (for example, 1033 '123.45.67.89'). This is useful when conversing with a program that uses the 1034 standard C library and needs objects of type :c:struct:`in_addr`, which 1035 is the C type for the 32-bit packed binary data this function takes as an 1036 argument. 1037 1038 If the byte sequence passed to this function is not exactly 4 bytes in 1039 length, :exc:`OSError` will be raised. :func:`inet_ntoa` does not 1040 support IPv6, and :func:`inet_ntop` should be used instead for IPv4/v6 dual 1041 stack support. 1042 1043 .. versionchanged:: 3.5 1044 Writable :term:`bytes-like object` is now accepted. 1045 1046 1047.. function:: inet_pton(address_family, ip_string) 1048 1049 Convert an IP address from its family-specific string format to a packed, 1050 binary format. :func:`inet_pton` is useful when a library or network protocol 1051 calls for an object of type :c:struct:`in_addr` (similar to 1052 :func:`inet_aton`) or :c:struct:`in6_addr`. 1053 1054 Supported values for *address_family* are currently :const:`AF_INET` and 1055 :const:`AF_INET6`. If the IP address string *ip_string* is invalid, 1056 :exc:`OSError` will be raised. Note that exactly what is valid depends on 1057 both the value of *address_family* and the underlying implementation of 1058 :c:func:`inet_pton`. 1059 1060 .. availability:: Unix, Windows. 1061 1062 .. versionchanged:: 3.4 1063 Windows support added 1064 1065 1066.. function:: inet_ntop(address_family, packed_ip) 1067 1068 Convert a packed IP address (a :term:`bytes-like object` of some number of 1069 bytes) to its standard, family-specific string representation (for 1070 example, ``'7.10.0.5'`` or ``'5aef:2b::8'``). 1071 :func:`inet_ntop` is useful when a library or network protocol returns an 1072 object of type :c:struct:`in_addr` (similar to :func:`inet_ntoa`) or 1073 :c:struct:`in6_addr`. 1074 1075 Supported values for *address_family* are currently :const:`AF_INET` and 1076 :const:`AF_INET6`. If the bytes object *packed_ip* is not the correct 1077 length for the specified address family, :exc:`ValueError` will be raised. 1078 :exc:`OSError` is raised for errors from the call to :func:`inet_ntop`. 1079 1080 .. availability:: Unix, Windows. 1081 1082 .. versionchanged:: 3.4 1083 Windows support added 1084 1085 .. versionchanged:: 3.5 1086 Writable :term:`bytes-like object` is now accepted. 1087 1088 1089.. 1090 XXX: Are sendmsg(), recvmsg() and CMSG_*() available on any 1091 non-Unix platforms? The old (obsolete?) 4.2BSD form of the 1092 interface, in which struct msghdr has no msg_control or 1093 msg_controllen members, is not currently supported. 1094 1095.. function:: CMSG_LEN(length) 1096 1097 Return the total length, without trailing padding, of an ancillary 1098 data item with associated data of the given *length*. This value 1099 can often be used as the buffer size for :meth:`~socket.recvmsg` to 1100 receive a single item of ancillary data, but :rfc:`3542` requires 1101 portable applications to use :func:`CMSG_SPACE` and thus include 1102 space for padding, even when the item will be the last in the 1103 buffer. Raises :exc:`OverflowError` if *length* is outside the 1104 permissible range of values. 1105 1106 .. availability:: Unix, not Emscripten, not WASI. 1107 1108 Most Unix platforms. 1109 1110 .. versionadded:: 3.3 1111 1112 1113.. function:: CMSG_SPACE(length) 1114 1115 Return the buffer size needed for :meth:`~socket.recvmsg` to 1116 receive an ancillary data item with associated data of the given 1117 *length*, along with any trailing padding. The buffer space needed 1118 to receive multiple items is the sum of the :func:`CMSG_SPACE` 1119 values for their associated data lengths. Raises 1120 :exc:`OverflowError` if *length* is outside the permissible range 1121 of values. 1122 1123 Note that some systems might support ancillary data without 1124 providing this function. Also note that setting the buffer size 1125 using the results of this function may not precisely limit the 1126 amount of ancillary data that can be received, since additional 1127 data may be able to fit into the padding area. 1128 1129 .. availability:: Unix, not Emscripten, not WASI. 1130 1131 most Unix platforms. 1132 1133 .. versionadded:: 3.3 1134 1135 1136.. function:: getdefaulttimeout() 1137 1138 Return the default timeout in seconds (float) for new socket objects. A value 1139 of ``None`` indicates that new socket objects have no timeout. When the socket 1140 module is first imported, the default is ``None``. 1141 1142 1143.. function:: setdefaulttimeout(timeout) 1144 1145 Set the default timeout in seconds (float) for new socket objects. When 1146 the socket module is first imported, the default is ``None``. See 1147 :meth:`~socket.settimeout` for possible values and their respective 1148 meanings. 1149 1150 1151.. function:: sethostname(name) 1152 1153 Set the machine's hostname to *name*. This will raise an 1154 :exc:`OSError` if you don't have enough rights. 1155 1156 .. audit-event:: socket.sethostname name socket.sethostname 1157 1158 .. availability:: Unix. 1159 1160 .. versionadded:: 3.3 1161 1162 1163.. function:: if_nameindex() 1164 1165 Return a list of network interface information 1166 (index int, name string) tuples. 1167 :exc:`OSError` if the system call fails. 1168 1169 .. availability:: Unix, Windows, not Emscripten, not WASI. 1170 1171 .. versionadded:: 3.3 1172 1173 .. versionchanged:: 3.8 1174 Windows support was added. 1175 1176 .. note:: 1177 1178 On Windows network interfaces have different names in different contexts 1179 (all names are examples): 1180 1181 * UUID: ``{FB605B73-AAC2-49A6-9A2F-25416AEA0573}`` 1182 * name: ``ethernet_32770`` 1183 * friendly name: ``vEthernet (nat)`` 1184 * description: ``Hyper-V Virtual Ethernet Adapter`` 1185 1186 This function returns names of the second form from the list, ``ethernet_32770`` 1187 in this example case. 1188 1189 1190.. function:: if_nametoindex(if_name) 1191 1192 Return a network interface index number corresponding to an 1193 interface name. 1194 :exc:`OSError` if no interface with the given name exists. 1195 1196 .. availability:: Unix, Windows, not Emscripten, not WASI. 1197 1198 .. versionadded:: 3.3 1199 1200 .. versionchanged:: 3.8 1201 Windows support was added. 1202 1203 .. seealso:: 1204 "Interface name" is a name as documented in :func:`if_nameindex`. 1205 1206 1207.. function:: if_indextoname(if_index) 1208 1209 Return a network interface name corresponding to an 1210 interface index number. 1211 :exc:`OSError` if no interface with the given index exists. 1212 1213 .. availability:: Unix, Windows, not Emscripten, not WASI. 1214 1215 .. versionadded:: 3.3 1216 1217 .. versionchanged:: 3.8 1218 Windows support was added. 1219 1220 .. seealso:: 1221 "Interface name" is a name as documented in :func:`if_nameindex`. 1222 1223 1224.. function:: send_fds(sock, buffers, fds[, flags[, address]]) 1225 1226 Send the list of file descriptors *fds* over an :const:`AF_UNIX` socket *sock*. 1227 The *fds* parameter is a sequence of file descriptors. 1228 Consult :meth:`sendmsg` for the documentation of these parameters. 1229 1230 .. availability:: Unix, Windows, not Emscripten, not WASI. 1231 1232 Unix platforms supporting :meth:`~socket.sendmsg` 1233 and :const:`SCM_RIGHTS` mechanism. 1234 1235 .. versionadded:: 3.9 1236 1237 1238.. function:: recv_fds(sock, bufsize, maxfds[, flags]) 1239 1240 Receive up to *maxfds* file descriptors from an :const:`AF_UNIX` socket *sock*. 1241 Return ``(msg, list(fds), flags, addr)``. 1242 Consult :meth:`recvmsg` for the documentation of these parameters. 1243 1244 .. availability:: Unix, Windows, not Emscripten, not WASI. 1245 1246 Unix platforms supporting :meth:`~socket.sendmsg` 1247 and :const:`SCM_RIGHTS` mechanism. 1248 1249 .. versionadded:: 3.9 1250 1251 .. note:: 1252 1253 Any truncated integers at the end of the list of file descriptors. 1254 1255 1256.. _socket-objects: 1257 1258Socket Objects 1259-------------- 1260 1261Socket objects have the following methods. Except for 1262:meth:`~socket.makefile`, these correspond to Unix system calls applicable 1263to sockets. 1264 1265.. versionchanged:: 3.2 1266 Support for the :term:`context manager` protocol was added. Exiting the 1267 context manager is equivalent to calling :meth:`~socket.close`. 1268 1269 1270.. method:: socket.accept() 1271 1272 Accept a connection. The socket must be bound to an address and listening for 1273 connections. The return value is a pair ``(conn, address)`` where *conn* is a 1274 *new* socket object usable to send and receive data on the connection, and 1275 *address* is the address bound to the socket on the other end of the connection. 1276 1277 The newly created socket is :ref:`non-inheritable <fd_inheritance>`. 1278 1279 .. versionchanged:: 3.4 1280 The socket is now non-inheritable. 1281 1282 .. versionchanged:: 3.5 1283 If the system call is interrupted and the signal handler does not raise 1284 an exception, the method now retries the system call instead of raising 1285 an :exc:`InterruptedError` exception (see :pep:`475` for the rationale). 1286 1287 1288.. method:: socket.bind(address) 1289 1290 Bind the socket to *address*. The socket must not already be bound. (The format 1291 of *address* depends on the address family --- see above.) 1292 1293 .. audit-event:: socket.bind self,address socket.socket.bind 1294 1295 .. availability:: not WASI. 1296 1297 1298.. method:: socket.close() 1299 1300 Mark the socket closed. The underlying system resource (e.g. a file 1301 descriptor) is also closed when all file objects from :meth:`makefile()` 1302 are closed. Once that happens, all future operations on the socket 1303 object will fail. The remote end will receive no more data (after 1304 queued data is flushed). 1305 1306 Sockets are automatically closed when they are garbage-collected, but 1307 it is recommended to :meth:`close` them explicitly, or to use a 1308 :keyword:`with` statement around them. 1309 1310 .. versionchanged:: 3.6 1311 :exc:`OSError` is now raised if an error occurs when the underlying 1312 :c:func:`close` call is made. 1313 1314 .. note:: 1315 1316 :meth:`close()` releases the resource associated with a connection but 1317 does not necessarily close the connection immediately. If you want 1318 to close the connection in a timely fashion, call :meth:`shutdown()` 1319 before :meth:`close()`. 1320 1321 1322.. method:: socket.connect(address) 1323 1324 Connect to a remote socket at *address*. (The format of *address* depends on the 1325 address family --- see above.) 1326 1327 If the connection is interrupted by a signal, the method waits until the 1328 connection completes, or raise a :exc:`TimeoutError` on timeout, if the 1329 signal handler doesn't raise an exception and the socket is blocking or has 1330 a timeout. For non-blocking sockets, the method raises an 1331 :exc:`InterruptedError` exception if the connection is interrupted by a 1332 signal (or the exception raised by the signal handler). 1333 1334 .. audit-event:: socket.connect self,address socket.socket.connect 1335 1336 .. versionchanged:: 3.5 1337 The method now waits until the connection completes instead of raising an 1338 :exc:`InterruptedError` exception if the connection is interrupted by a 1339 signal, the signal handler doesn't raise an exception and the socket is 1340 blocking or has a timeout (see the :pep:`475` for the rationale). 1341 1342 .. availability:: not WASI. 1343 1344 1345.. method:: socket.connect_ex(address) 1346 1347 Like ``connect(address)``, but return an error indicator instead of raising an 1348 exception for errors returned by the C-level :c:func:`connect` call (other 1349 problems, such as "host not found," can still raise exceptions). The error 1350 indicator is ``0`` if the operation succeeded, otherwise the value of the 1351 :c:data:`errno` variable. This is useful to support, for example, asynchronous 1352 connects. 1353 1354 .. audit-event:: socket.connect self,address socket.socket.connect_ex 1355 1356 .. availability:: not WASI. 1357 1358.. method:: socket.detach() 1359 1360 Put the socket object into closed state without actually closing the 1361 underlying file descriptor. The file descriptor is returned, and can 1362 be reused for other purposes. 1363 1364 .. versionadded:: 3.2 1365 1366 1367.. method:: socket.dup() 1368 1369 Duplicate the socket. 1370 1371 The newly created socket is :ref:`non-inheritable <fd_inheritance>`. 1372 1373 .. versionchanged:: 3.4 1374 The socket is now non-inheritable. 1375 1376 .. availability:: not WASI. 1377 1378 1379.. method:: socket.fileno() 1380 1381 Return the socket's file descriptor (a small integer), or -1 on failure. This 1382 is useful with :func:`select.select`. 1383 1384 Under Windows the small integer returned by this method cannot be used where a 1385 file descriptor can be used (such as :func:`os.fdopen`). Unix does not have 1386 this limitation. 1387 1388.. method:: socket.get_inheritable() 1389 1390 Get the :ref:`inheritable flag <fd_inheritance>` of the socket's file 1391 descriptor or socket's handle: ``True`` if the socket can be inherited in 1392 child processes, ``False`` if it cannot. 1393 1394 .. versionadded:: 3.4 1395 1396 1397.. method:: socket.getpeername() 1398 1399 Return the remote address to which the socket is connected. This is useful to 1400 find out the port number of a remote IPv4/v6 socket, for instance. (The format 1401 of the address returned depends on the address family --- see above.) On some 1402 systems this function is not supported. 1403 1404 1405.. method:: socket.getsockname() 1406 1407 Return the socket's own address. This is useful to find out the port number of 1408 an IPv4/v6 socket, for instance. (The format of the address returned depends on 1409 the address family --- see above.) 1410 1411 1412.. method:: socket.getsockopt(level, optname[, buflen]) 1413 1414 Return the value of the given socket option (see the Unix man page 1415 :manpage:`getsockopt(2)`). The needed symbolic constants (:const:`SO_\*` etc.) 1416 are defined in this module. If *buflen* is absent, an integer option is assumed 1417 and its integer value is returned by the function. If *buflen* is present, it 1418 specifies the maximum length of the buffer used to receive the option in, and 1419 this buffer is returned as a bytes object. It is up to the caller to decode the 1420 contents of the buffer (see the optional built-in module :mod:`struct` for a way 1421 to decode C structures encoded as byte strings). 1422 1423 .. availability:: not WASI. 1424 1425 1426.. method:: socket.getblocking() 1427 1428 Return ``True`` if socket is in blocking mode, ``False`` if in 1429 non-blocking. 1430 1431 This is equivalent to checking ``socket.gettimeout() != 0``. 1432 1433 .. versionadded:: 3.7 1434 1435 1436.. method:: socket.gettimeout() 1437 1438 Return the timeout in seconds (float) associated with socket operations, 1439 or ``None`` if no timeout is set. This reflects the last call to 1440 :meth:`setblocking` or :meth:`settimeout`. 1441 1442 1443.. method:: socket.ioctl(control, option) 1444 1445 :platform: Windows 1446 1447 The :meth:`ioctl` method is a limited interface to the WSAIoctl system 1448 interface. Please refer to the `Win32 documentation 1449 <https://msdn.microsoft.com/en-us/library/ms741621%28VS.85%29.aspx>`_ for more 1450 information. 1451 1452 On other platforms, the generic :func:`fcntl.fcntl` and :func:`fcntl.ioctl` 1453 functions may be used; they accept a socket object as their first argument. 1454 1455 Currently only the following control codes are supported: 1456 ``SIO_RCVALL``, ``SIO_KEEPALIVE_VALS``, and ``SIO_LOOPBACK_FAST_PATH``. 1457 1458 .. versionchanged:: 3.6 1459 ``SIO_LOOPBACK_FAST_PATH`` was added. 1460 1461.. method:: socket.listen([backlog]) 1462 1463 Enable a server to accept connections. If *backlog* is specified, it must 1464 be at least 0 (if it is lower, it is set to 0); it specifies the number of 1465 unaccepted connections that the system will allow before refusing new 1466 connections. If not specified, a default reasonable value is chosen. 1467 1468 .. availability:: not WASI. 1469 1470 .. versionchanged:: 3.5 1471 The *backlog* parameter is now optional. 1472 1473 1474.. method:: socket.makefile(mode='r', buffering=None, *, encoding=None, \ 1475 errors=None, newline=None) 1476 1477 .. index:: single: I/O control; buffering 1478 1479 Return a :term:`file object` associated with the socket. The exact returned 1480 type depends on the arguments given to :meth:`makefile`. These arguments are 1481 interpreted the same way as by the built-in :func:`open` function, except 1482 the only supported *mode* values are ``'r'`` (default), ``'w'`` and ``'b'``. 1483 1484 The socket must be in blocking mode; it can have a timeout, but the file 1485 object's internal buffer may end up in an inconsistent state if a timeout 1486 occurs. 1487 1488 Closing the file object returned by :meth:`makefile` won't close the 1489 original socket unless all other file objects have been closed and 1490 :meth:`socket.close` has been called on the socket object. 1491 1492 .. note:: 1493 1494 On Windows, the file-like object created by :meth:`makefile` cannot be 1495 used where a file object with a file descriptor is expected, such as the 1496 stream arguments of :meth:`subprocess.Popen`. 1497 1498 1499.. method:: socket.recv(bufsize[, flags]) 1500 1501 Receive data from the socket. The return value is a bytes object representing the 1502 data received. The maximum amount of data to be received at once is specified 1503 by *bufsize*. See the Unix manual page :manpage:`recv(2)` for the meaning of 1504 the optional argument *flags*; it defaults to zero. 1505 1506 .. note:: 1507 1508 For best match with hardware and network realities, the value of *bufsize* 1509 should be a relatively small power of 2, for example, 4096. 1510 1511 .. versionchanged:: 3.5 1512 If the system call is interrupted and the signal handler does not raise 1513 an exception, the method now retries the system call instead of raising 1514 an :exc:`InterruptedError` exception (see :pep:`475` for the rationale). 1515 1516 1517.. method:: socket.recvfrom(bufsize[, flags]) 1518 1519 Receive data from the socket. The return value is a pair ``(bytes, address)`` 1520 where *bytes* is a bytes object representing the data received and *address* is the 1521 address of the socket sending the data. See the Unix manual page 1522 :manpage:`recv(2)` for the meaning of the optional argument *flags*; it defaults 1523 to zero. (The format of *address* depends on the address family --- see above.) 1524 1525 .. versionchanged:: 3.5 1526 If the system call is interrupted and the signal handler does not raise 1527 an exception, the method now retries the system call instead of raising 1528 an :exc:`InterruptedError` exception (see :pep:`475` for the rationale). 1529 1530 .. versionchanged:: 3.7 1531 For multicast IPv6 address, first item of *address* does not contain 1532 ``%scope_id`` part anymore. In order to get full IPv6 address use 1533 :func:`getnameinfo`. 1534 1535.. method:: socket.recvmsg(bufsize[, ancbufsize[, flags]]) 1536 1537 Receive normal data (up to *bufsize* bytes) and ancillary data from 1538 the socket. The *ancbufsize* argument sets the size in bytes of 1539 the internal buffer used to receive the ancillary data; it defaults 1540 to 0, meaning that no ancillary data will be received. Appropriate 1541 buffer sizes for ancillary data can be calculated using 1542 :func:`CMSG_SPACE` or :func:`CMSG_LEN`, and items which do not fit 1543 into the buffer might be truncated or discarded. The *flags* 1544 argument defaults to 0 and has the same meaning as for 1545 :meth:`recv`. 1546 1547 The return value is a 4-tuple: ``(data, ancdata, msg_flags, 1548 address)``. The *data* item is a :class:`bytes` object holding the 1549 non-ancillary data received. The *ancdata* item is a list of zero 1550 or more tuples ``(cmsg_level, cmsg_type, cmsg_data)`` representing 1551 the ancillary data (control messages) received: *cmsg_level* and 1552 *cmsg_type* are integers specifying the protocol level and 1553 protocol-specific type respectively, and *cmsg_data* is a 1554 :class:`bytes` object holding the associated data. The *msg_flags* 1555 item is the bitwise OR of various flags indicating conditions on 1556 the received message; see your system documentation for details. 1557 If the receiving socket is unconnected, *address* is the address of 1558 the sending socket, if available; otherwise, its value is 1559 unspecified. 1560 1561 On some systems, :meth:`sendmsg` and :meth:`recvmsg` can be used to 1562 pass file descriptors between processes over an :const:`AF_UNIX` 1563 socket. When this facility is used (it is often restricted to 1564 :const:`SOCK_STREAM` sockets), :meth:`recvmsg` will return, in its 1565 ancillary data, items of the form ``(socket.SOL_SOCKET, 1566 socket.SCM_RIGHTS, fds)``, where *fds* is a :class:`bytes` object 1567 representing the new file descriptors as a binary array of the 1568 native C :c:expr:`int` type. If :meth:`recvmsg` raises an 1569 exception after the system call returns, it will first attempt to 1570 close any file descriptors received via this mechanism. 1571 1572 Some systems do not indicate the truncated length of ancillary data 1573 items which have been only partially received. If an item appears 1574 to extend beyond the end of the buffer, :meth:`recvmsg` will issue 1575 a :exc:`RuntimeWarning`, and will return the part of it which is 1576 inside the buffer provided it has not been truncated before the 1577 start of its associated data. 1578 1579 On systems which support the :const:`SCM_RIGHTS` mechanism, the 1580 following function will receive up to *maxfds* file descriptors, 1581 returning the message data and a list containing the descriptors 1582 (while ignoring unexpected conditions such as unrelated control 1583 messages being received). See also :meth:`sendmsg`. :: 1584 1585 import socket, array 1586 1587 def recv_fds(sock, msglen, maxfds): 1588 fds = array.array("i") # Array of ints 1589 msg, ancdata, flags, addr = sock.recvmsg(msglen, socket.CMSG_LEN(maxfds * fds.itemsize)) 1590 for cmsg_level, cmsg_type, cmsg_data in ancdata: 1591 if cmsg_level == socket.SOL_SOCKET and cmsg_type == socket.SCM_RIGHTS: 1592 # Append data, ignoring any truncated integers at the end. 1593 fds.frombytes(cmsg_data[:len(cmsg_data) - (len(cmsg_data) % fds.itemsize)]) 1594 return msg, list(fds) 1595 1596 .. availability:: Unix. 1597 1598 Most Unix platforms. 1599 1600 .. versionadded:: 3.3 1601 1602 .. versionchanged:: 3.5 1603 If the system call is interrupted and the signal handler does not raise 1604 an exception, the method now retries the system call instead of raising 1605 an :exc:`InterruptedError` exception (see :pep:`475` for the rationale). 1606 1607 1608.. method:: socket.recvmsg_into(buffers[, ancbufsize[, flags]]) 1609 1610 Receive normal data and ancillary data from the socket, behaving as 1611 :meth:`recvmsg` would, but scatter the non-ancillary data into a 1612 series of buffers instead of returning a new bytes object. The 1613 *buffers* argument must be an iterable of objects that export 1614 writable buffers (e.g. :class:`bytearray` objects); these will be 1615 filled with successive chunks of the non-ancillary data until it 1616 has all been written or there are no more buffers. The operating 1617 system may set a limit (:func:`~os.sysconf` value ``SC_IOV_MAX``) 1618 on the number of buffers that can be used. The *ancbufsize* and 1619 *flags* arguments have the same meaning as for :meth:`recvmsg`. 1620 1621 The return value is a 4-tuple: ``(nbytes, ancdata, msg_flags, 1622 address)``, where *nbytes* is the total number of bytes of 1623 non-ancillary data written into the buffers, and *ancdata*, 1624 *msg_flags* and *address* are the same as for :meth:`recvmsg`. 1625 1626 Example:: 1627 1628 >>> import socket 1629 >>> s1, s2 = socket.socketpair() 1630 >>> b1 = bytearray(b'----') 1631 >>> b2 = bytearray(b'0123456789') 1632 >>> b3 = bytearray(b'--------------') 1633 >>> s1.send(b'Mary had a little lamb') 1634 22 1635 >>> s2.recvmsg_into([b1, memoryview(b2)[2:9], b3]) 1636 (22, [], 0, None) 1637 >>> [b1, b2, b3] 1638 [bytearray(b'Mary'), bytearray(b'01 had a 9'), bytearray(b'little lamb---')] 1639 1640 .. availability:: Unix. 1641 1642 Most Unix platforms. 1643 1644 .. versionadded:: 3.3 1645 1646 1647.. method:: socket.recvfrom_into(buffer[, nbytes[, flags]]) 1648 1649 Receive data from the socket, writing it into *buffer* instead of creating a 1650 new bytestring. The return value is a pair ``(nbytes, address)`` where *nbytes* is 1651 the number of bytes received and *address* is the address of the socket sending 1652 the data. See the Unix manual page :manpage:`recv(2)` for the meaning of the 1653 optional argument *flags*; it defaults to zero. (The format of *address* 1654 depends on the address family --- see above.) 1655 1656 1657.. method:: socket.recv_into(buffer[, nbytes[, flags]]) 1658 1659 Receive up to *nbytes* bytes from the socket, storing the data into a buffer 1660 rather than creating a new bytestring. If *nbytes* is not specified (or 0), 1661 receive up to the size available in the given buffer. Returns the number of 1662 bytes received. See the Unix manual page :manpage:`recv(2)` for the meaning 1663 of the optional argument *flags*; it defaults to zero. 1664 1665 1666.. method:: socket.send(bytes[, flags]) 1667 1668 Send data to the socket. The socket must be connected to a remote socket. The 1669 optional *flags* argument has the same meaning as for :meth:`recv` above. 1670 Returns the number of bytes sent. Applications are responsible for checking that 1671 all data has been sent; if only some of the data was transmitted, the 1672 application needs to attempt delivery of the remaining data. For further 1673 information on this topic, consult the :ref:`socket-howto`. 1674 1675 .. versionchanged:: 3.5 1676 If the system call is interrupted and the signal handler does not raise 1677 an exception, the method now retries the system call instead of raising 1678 an :exc:`InterruptedError` exception (see :pep:`475` for the rationale). 1679 1680 1681.. method:: socket.sendall(bytes[, flags]) 1682 1683 Send data to the socket. The socket must be connected to a remote socket. The 1684 optional *flags* argument has the same meaning as for :meth:`recv` above. 1685 Unlike :meth:`send`, this method continues to send data from *bytes* until 1686 either all data has been sent or an error occurs. ``None`` is returned on 1687 success. On error, an exception is raised, and there is no way to determine how 1688 much data, if any, was successfully sent. 1689 1690 .. versionchanged:: 3.5 1691 The socket timeout is no longer reset each time data is sent successfully. 1692 The socket timeout is now the maximum total duration to send all data. 1693 1694 .. versionchanged:: 3.5 1695 If the system call is interrupted and the signal handler does not raise 1696 an exception, the method now retries the system call instead of raising 1697 an :exc:`InterruptedError` exception (see :pep:`475` for the rationale). 1698 1699 1700.. method:: socket.sendto(bytes, address) 1701 socket.sendto(bytes, flags, address) 1702 1703 Send data to the socket. The socket should not be connected to a remote socket, 1704 since the destination socket is specified by *address*. The optional *flags* 1705 argument has the same meaning as for :meth:`recv` above. Return the number of 1706 bytes sent. (The format of *address* depends on the address family --- see 1707 above.) 1708 1709 .. audit-event:: socket.sendto self,address socket.socket.sendto 1710 1711 .. versionchanged:: 3.5 1712 If the system call is interrupted and the signal handler does not raise 1713 an exception, the method now retries the system call instead of raising 1714 an :exc:`InterruptedError` exception (see :pep:`475` for the rationale). 1715 1716 1717.. method:: socket.sendmsg(buffers[, ancdata[, flags[, address]]]) 1718 1719 Send normal and ancillary data to the socket, gathering the 1720 non-ancillary data from a series of buffers and concatenating it 1721 into a single message. The *buffers* argument specifies the 1722 non-ancillary data as an iterable of 1723 :term:`bytes-like objects <bytes-like object>` 1724 (e.g. :class:`bytes` objects); the operating system may set a limit 1725 (:func:`~os.sysconf` value ``SC_IOV_MAX``) on the number of buffers 1726 that can be used. The *ancdata* argument specifies the ancillary 1727 data (control messages) as an iterable of zero or more tuples 1728 ``(cmsg_level, cmsg_type, cmsg_data)``, where *cmsg_level* and 1729 *cmsg_type* are integers specifying the protocol level and 1730 protocol-specific type respectively, and *cmsg_data* is a 1731 bytes-like object holding the associated data. Note that 1732 some systems (in particular, systems without :func:`CMSG_SPACE`) 1733 might support sending only one control message per call. The 1734 *flags* argument defaults to 0 and has the same meaning as for 1735 :meth:`send`. If *address* is supplied and not ``None``, it sets a 1736 destination address for the message. The return value is the 1737 number of bytes of non-ancillary data sent. 1738 1739 The following function sends the list of file descriptors *fds* 1740 over an :const:`AF_UNIX` socket, on systems which support the 1741 :const:`SCM_RIGHTS` mechanism. See also :meth:`recvmsg`. :: 1742 1743 import socket, array 1744 1745 def send_fds(sock, msg, fds): 1746 return sock.sendmsg([msg], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", fds))]) 1747 1748 .. availability:: Unix, not WASI. 1749 1750 Most Unix platforms. 1751 1752 .. audit-event:: socket.sendmsg self,address socket.socket.sendmsg 1753 1754 .. versionadded:: 3.3 1755 1756 .. versionchanged:: 3.5 1757 If the system call is interrupted and the signal handler does not raise 1758 an exception, the method now retries the system call instead of raising 1759 an :exc:`InterruptedError` exception (see :pep:`475` for the rationale). 1760 1761.. method:: socket.sendmsg_afalg([msg], *, op[, iv[, assoclen[, flags]]]) 1762 1763 Specialized version of :meth:`~socket.sendmsg` for :const:`AF_ALG` socket. 1764 Set mode, IV, AEAD associated data length and flags for :const:`AF_ALG` socket. 1765 1766 .. availability:: Linux >= 2.6.38. 1767 1768 .. versionadded:: 3.6 1769 1770.. method:: socket.sendfile(file, offset=0, count=None) 1771 1772 Send a file until EOF is reached by using high-performance 1773 :mod:`os.sendfile` and return the total number of bytes which were sent. 1774 *file* must be a regular file object opened in binary mode. If 1775 :mod:`os.sendfile` is not available (e.g. Windows) or *file* is not a 1776 regular file :meth:`send` will be used instead. *offset* tells from where to 1777 start reading the file. If specified, *count* is the total number of bytes 1778 to transmit as opposed to sending the file until EOF is reached. File 1779 position is updated on return or also in case of error in which case 1780 :meth:`file.tell() <io.IOBase.tell>` can be used to figure out the number of 1781 bytes which were sent. The socket must be of :const:`SOCK_STREAM` type. 1782 Non-blocking sockets are not supported. 1783 1784 .. versionadded:: 3.5 1785 1786.. method:: socket.set_inheritable(inheritable) 1787 1788 Set the :ref:`inheritable flag <fd_inheritance>` of the socket's file 1789 descriptor or socket's handle. 1790 1791 .. versionadded:: 3.4 1792 1793 1794.. method:: socket.setblocking(flag) 1795 1796 Set blocking or non-blocking mode of the socket: if *flag* is false, the 1797 socket is set to non-blocking, else to blocking mode. 1798 1799 This method is a shorthand for certain :meth:`~socket.settimeout` calls: 1800 1801 * ``sock.setblocking(True)`` is equivalent to ``sock.settimeout(None)`` 1802 1803 * ``sock.setblocking(False)`` is equivalent to ``sock.settimeout(0.0)`` 1804 1805 .. versionchanged:: 3.7 1806 The method no longer applies :const:`SOCK_NONBLOCK` flag on 1807 :attr:`socket.type`. 1808 1809 1810.. method:: socket.settimeout(value) 1811 1812 Set a timeout on blocking socket operations. The *value* argument can be a 1813 nonnegative floating point number expressing seconds, or ``None``. 1814 If a non-zero value is given, subsequent socket operations will raise a 1815 :exc:`timeout` exception if the timeout period *value* has elapsed before 1816 the operation has completed. If zero is given, the socket is put in 1817 non-blocking mode. If ``None`` is given, the socket is put in blocking mode. 1818 1819 For further information, please consult the :ref:`notes on socket timeouts <socket-timeouts>`. 1820 1821 .. versionchanged:: 3.7 1822 The method no longer toggles :const:`SOCK_NONBLOCK` flag on 1823 :attr:`socket.type`. 1824 1825 1826.. method:: socket.setsockopt(level, optname, value: int) 1827.. method:: socket.setsockopt(level, optname, value: buffer) 1828 :noindex: 1829.. method:: socket.setsockopt(level, optname, None, optlen: int) 1830 :noindex: 1831 1832 .. index:: pair: module; struct 1833 1834 Set the value of the given socket option (see the Unix manual page 1835 :manpage:`setsockopt(2)`). The needed symbolic constants are defined in the 1836 :mod:`socket` module (:const:`SO_\*` etc.). The value can be an integer, 1837 ``None`` or a :term:`bytes-like object` representing a buffer. In the later 1838 case it is up to the caller to ensure that the bytestring contains the 1839 proper bits (see the optional built-in module :mod:`struct` for a way to 1840 encode C structures as bytestrings). When *value* is set to ``None``, 1841 *optlen* argument is required. It's equivalent to call :c:func:`setsockopt` C 1842 function with ``optval=NULL`` and ``optlen=optlen``. 1843 1844 .. versionchanged:: 3.5 1845 Writable :term:`bytes-like object` is now accepted. 1846 1847 .. versionchanged:: 3.6 1848 setsockopt(level, optname, None, optlen: int) form added. 1849 1850 .. availability:: not WASI. 1851 1852 1853.. method:: socket.shutdown(how) 1854 1855 Shut down one or both halves of the connection. If *how* is :const:`SHUT_RD`, 1856 further receives are disallowed. If *how* is :const:`SHUT_WR`, further sends 1857 are disallowed. If *how* is :const:`SHUT_RDWR`, further sends and receives are 1858 disallowed. 1859 1860 .. availability:: not WASI. 1861 1862 1863.. method:: socket.share(process_id) 1864 1865 Duplicate a socket and prepare it for sharing with a target process. The 1866 target process must be provided with *process_id*. The resulting bytes object 1867 can then be passed to the target process using some form of interprocess 1868 communication and the socket can be recreated there using :func:`fromshare`. 1869 Once this method has been called, it is safe to close the socket since 1870 the operating system has already duplicated it for the target process. 1871 1872 .. availability:: Windows. 1873 1874 .. versionadded:: 3.3 1875 1876 1877Note that there are no methods :meth:`read` or :meth:`write`; use 1878:meth:`~socket.recv` and :meth:`~socket.send` without *flags* argument instead. 1879 1880Socket objects also have these (read-only) attributes that correspond to the 1881values given to the :class:`~socket.socket` constructor. 1882 1883 1884.. attribute:: socket.family 1885 1886 The socket family. 1887 1888 1889.. attribute:: socket.type 1890 1891 The socket type. 1892 1893 1894.. attribute:: socket.proto 1895 1896 The socket protocol. 1897 1898 1899 1900.. _socket-timeouts: 1901 1902Notes on socket timeouts 1903------------------------ 1904 1905A socket object can be in one of three modes: blocking, non-blocking, or 1906timeout. Sockets are by default always created in blocking mode, but this 1907can be changed by calling :func:`setdefaulttimeout`. 1908 1909* In *blocking mode*, operations block until complete or the system returns 1910 an error (such as connection timed out). 1911 1912* In *non-blocking mode*, operations fail (with an error that is unfortunately 1913 system-dependent) if they cannot be completed immediately: functions from the 1914 :mod:`select` module can be used to know when and whether a socket is available 1915 for reading or writing. 1916 1917* In *timeout mode*, operations fail if they cannot be completed within the 1918 timeout specified for the socket (they raise a :exc:`timeout` exception) 1919 or if the system returns an error. 1920 1921.. note:: 1922 At the operating system level, sockets in *timeout mode* are internally set 1923 in non-blocking mode. Also, the blocking and timeout modes are shared between 1924 file descriptors and socket objects that refer to the same network endpoint. 1925 This implementation detail can have visible consequences if e.g. you decide 1926 to use the :meth:`~socket.fileno()` of a socket. 1927 1928Timeouts and the ``connect`` method 1929^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1930 1931The :meth:`~socket.connect` operation is also subject to the timeout 1932setting, and in general it is recommended to call :meth:`~socket.settimeout` 1933before calling :meth:`~socket.connect` or pass a timeout parameter to 1934:meth:`create_connection`. However, the system network stack may also 1935return a connection timeout error of its own regardless of any Python socket 1936timeout setting. 1937 1938Timeouts and the ``accept`` method 1939^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1940 1941If :func:`getdefaulttimeout` is not :const:`None`, sockets returned by 1942the :meth:`~socket.accept` method inherit that timeout. Otherwise, the 1943behaviour depends on settings of the listening socket: 1944 1945* if the listening socket is in *blocking mode* or in *timeout mode*, 1946 the socket returned by :meth:`~socket.accept` is in *blocking mode*; 1947 1948* if the listening socket is in *non-blocking mode*, whether the socket 1949 returned by :meth:`~socket.accept` is in blocking or non-blocking mode 1950 is operating system-dependent. If you want to ensure cross-platform 1951 behaviour, it is recommended you manually override this setting. 1952 1953 1954.. _socket-example: 1955 1956Example 1957------- 1958 1959Here are four minimal example programs using the TCP/IP protocol: a server that 1960echoes all data that it receives back (servicing only one client), and a client 1961using it. Note that a server must perform the sequence :func:`.socket`, 1962:meth:`~socket.bind`, :meth:`~socket.listen`, :meth:`~socket.accept` (possibly 1963repeating the :meth:`~socket.accept` to service more than one client), while a 1964client only needs the sequence :func:`.socket`, :meth:`~socket.connect`. Also 1965note that the server does not :meth:`~socket.sendall`/:meth:`~socket.recv` on 1966the socket it is listening on but on the new socket returned by 1967:meth:`~socket.accept`. 1968 1969The first two examples support IPv4 only. :: 1970 1971 # Echo server program 1972 import socket 1973 1974 HOST = '' # Symbolic name meaning all available interfaces 1975 PORT = 50007 # Arbitrary non-privileged port 1976 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: 1977 s.bind((HOST, PORT)) 1978 s.listen(1) 1979 conn, addr = s.accept() 1980 with conn: 1981 print('Connected by', addr) 1982 while True: 1983 data = conn.recv(1024) 1984 if not data: break 1985 conn.sendall(data) 1986 1987:: 1988 1989 # Echo client program 1990 import socket 1991 1992 HOST = 'daring.cwi.nl' # The remote host 1993 PORT = 50007 # The same port as used by the server 1994 with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: 1995 s.connect((HOST, PORT)) 1996 s.sendall(b'Hello, world') 1997 data = s.recv(1024) 1998 print('Received', repr(data)) 1999 2000The next two examples are identical to the above two, but support both IPv4 and 2001IPv6. The server side will listen to the first address family available (it 2002should listen to both instead). On most of IPv6-ready systems, IPv6 will take 2003precedence and the server may not accept IPv4 traffic. The client side will try 2004to connect to the all addresses returned as a result of the name resolution, and 2005sends traffic to the first one connected successfully. :: 2006 2007 # Echo server program 2008 import socket 2009 import sys 2010 2011 HOST = None # Symbolic name meaning all available interfaces 2012 PORT = 50007 # Arbitrary non-privileged port 2013 s = None 2014 for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, 2015 socket.SOCK_STREAM, 0, socket.AI_PASSIVE): 2016 af, socktype, proto, canonname, sa = res 2017 try: 2018 s = socket.socket(af, socktype, proto) 2019 except OSError as msg: 2020 s = None 2021 continue 2022 try: 2023 s.bind(sa) 2024 s.listen(1) 2025 except OSError as msg: 2026 s.close() 2027 s = None 2028 continue 2029 break 2030 if s is None: 2031 print('could not open socket') 2032 sys.exit(1) 2033 conn, addr = s.accept() 2034 with conn: 2035 print('Connected by', addr) 2036 while True: 2037 data = conn.recv(1024) 2038 if not data: break 2039 conn.send(data) 2040 2041:: 2042 2043 # Echo client program 2044 import socket 2045 import sys 2046 2047 HOST = 'daring.cwi.nl' # The remote host 2048 PORT = 50007 # The same port as used by the server 2049 s = None 2050 for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM): 2051 af, socktype, proto, canonname, sa = res 2052 try: 2053 s = socket.socket(af, socktype, proto) 2054 except OSError as msg: 2055 s = None 2056 continue 2057 try: 2058 s.connect(sa) 2059 except OSError as msg: 2060 s.close() 2061 s = None 2062 continue 2063 break 2064 if s is None: 2065 print('could not open socket') 2066 sys.exit(1) 2067 with s: 2068 s.sendall(b'Hello, world') 2069 data = s.recv(1024) 2070 print('Received', repr(data)) 2071 2072The next example shows how to write a very simple network sniffer with raw 2073sockets on Windows. The example requires administrator privileges to modify 2074the interface:: 2075 2076 import socket 2077 2078 # the public network interface 2079 HOST = socket.gethostbyname(socket.gethostname()) 2080 2081 # create a raw socket and bind it to the public interface 2082 s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP) 2083 s.bind((HOST, 0)) 2084 2085 # Include IP headers 2086 s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) 2087 2088 # receive all packets 2089 s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON) 2090 2091 # receive a packet 2092 print(s.recvfrom(65565)) 2093 2094 # disabled promiscuous mode 2095 s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF) 2096 2097The next example shows how to use the socket interface to communicate to a CAN 2098network using the raw socket protocol. To use CAN with the broadcast 2099manager protocol instead, open a socket with:: 2100 2101 socket.socket(socket.AF_CAN, socket.SOCK_DGRAM, socket.CAN_BCM) 2102 2103After binding (:const:`CAN_RAW`) or connecting (:const:`CAN_BCM`) the socket, you 2104can use the :meth:`socket.send` and :meth:`socket.recv` operations (and 2105their counterparts) on the socket object as usual. 2106 2107This last example might require special privileges:: 2108 2109 import socket 2110 import struct 2111 2112 2113 # CAN frame packing/unpacking (see 'struct can_frame' in <linux/can.h>) 2114 2115 can_frame_fmt = "=IB3x8s" 2116 can_frame_size = struct.calcsize(can_frame_fmt) 2117 2118 def build_can_frame(can_id, data): 2119 can_dlc = len(data) 2120 data = data.ljust(8, b'\x00') 2121 return struct.pack(can_frame_fmt, can_id, can_dlc, data) 2122 2123 def dissect_can_frame(frame): 2124 can_id, can_dlc, data = struct.unpack(can_frame_fmt, frame) 2125 return (can_id, can_dlc, data[:can_dlc]) 2126 2127 2128 # create a raw socket and bind it to the 'vcan0' interface 2129 s = socket.socket(socket.AF_CAN, socket.SOCK_RAW, socket.CAN_RAW) 2130 s.bind(('vcan0',)) 2131 2132 while True: 2133 cf, addr = s.recvfrom(can_frame_size) 2134 2135 print('Received: can_id=%x, can_dlc=%x, data=%s' % dissect_can_frame(cf)) 2136 2137 try: 2138 s.send(cf) 2139 except OSError: 2140 print('Error sending CAN frame') 2141 2142 try: 2143 s.send(build_can_frame(0x01, b'\x01\x02\x03')) 2144 except OSError: 2145 print('Error sending CAN frame') 2146 2147Running an example several times with too small delay between executions, could 2148lead to this error:: 2149 2150 OSError: [Errno 98] Address already in use 2151 2152This is because the previous execution has left the socket in a ``TIME_WAIT`` 2153state, and can't be immediately reused. 2154 2155There is a :mod:`socket` flag to set, in order to prevent this, 2156:data:`socket.SO_REUSEADDR`:: 2157 2158 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 2159 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 2160 s.bind((HOST, PORT)) 2161 2162the :data:`SO_REUSEADDR` flag tells the kernel to reuse a local socket in 2163``TIME_WAIT`` state, without waiting for its natural timeout to expire. 2164 2165 2166.. seealso:: 2167 2168 For an introduction to socket programming (in C), see the following papers: 2169 2170 - *An Introductory 4.3BSD Interprocess Communication Tutorial*, by Stuart Sechrest 2171 2172 - *An Advanced 4.3BSD Interprocess Communication Tutorial*, by Samuel J. Leffler et 2173 al, 2174 2175 both in the UNIX Programmer's Manual, Supplementary Documents 1 (sections 2176 PS1:7 and PS1:8). The platform-specific reference material for the various 2177 socket-related system calls are also a valuable source of information on the 2178 details of socket semantics. For Unix, refer to the manual pages; for Windows, 2179 see the WinSock (or Winsock 2) specification. For IPv6-ready APIs, readers may 2180 want to refer to :rfc:`3493` titled Basic Socket Interface Extensions for IPv6. 2181