Debian Codegraph @

Doc/library/socket.rst

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