Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(19)

Delta Between Two Patch Sets: Doc/library/socket.rst

Issue 16802: fileno argument to socket.socket() undocumented
Left Patch Set: Created 6 years, 12 months ago
Right Patch Set: Created 4 years, 4 months ago
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
Left: Side by side diff | Download
Right: Side by side diff | Download
« no previous file with change/comment | « no previous file | no next file » | no next file with change/comment »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
LEFTRIGHT
1 :mod:`socket` --- Low-level networking interface 1 :mod:`socket` --- Low-level networking interface
2 ================================================ 2 ================================================
3 3
4 .. module:: socket 4 .. module:: socket
5 :synopsis: Low-level networking interface. 5 :synopsis: Low-level networking interface.
6 6
7 7
8 This module provides access to the BSD *socket* interface. It is available on 8 This module provides access to the BSD *socket* interface. It is available on
9 all modern Unix systems, Windows, MacOS, OS/2, and probably additional 9 all modern Unix systems, Windows, MacOS, and probably additional platforms.
10 platforms.
11 10
12 .. note:: 11 .. note::
13 12
14 Some behavior may be platform dependent, since calls are made to the operatin g 13 Some behavior may be platform dependent, since calls are made to the operatin g
15 system socket APIs. 14 system socket APIs.
16 15
17 .. index:: object: socket 16 .. index:: object: socket
18 17
19 The Python interface is a straightforward transliteration of the Unix system 18 The Python interface is a straightforward transliteration of the Unix system
20 call and library interface for sockets to Python's object-oriented style: the 19 call and library interface for sockets to Python's object-oriented style: the
21 :func:`socket` function returns a :dfn:`socket object` whose methods implement 20 :func:`.socket` function returns a :dfn:`socket object` whose methods implement
22 the various socket system calls. Parameter types are somewhat higher-level than 21 the various socket system calls. Parameter types are somewhat higher-level than
23 in the C interface: as with :meth:`read` and :meth:`write` operations on Python 22 in the C interface: as with :meth:`read` and :meth:`write` operations on Python
24 files, buffer allocation on receive operations is automatic, and buffer length 23 files, buffer allocation on receive operations is automatic, and buffer length
25 is implicit on send operations. 24 is implicit on send operations.
26 25
27 26
28 .. seealso:: 27 .. seealso::
29 28
30 Module :mod:`socketserver` 29 Module :mod:`socketserver`
31 Classes that simplify writing network servers. 30 Classes that simplify writing network servers.
32 31
33 Module :mod:`ssl` 32 Module :mod:`ssl`
34 A TLS/SSL wrapper for socket objects. 33 A TLS/SSL wrapper for socket objects.
35 34
36 35
37 Socket families 36 Socket families
38 --------------- 37 ---------------
39 38
40 Depending on the system and the build options, various socket families 39 Depending on the system and the build options, various socket families
41 are supported by this module. 40 are supported by this module.
42 41
43 Socket addresses are represented as follows: 42 The address format required by a particular socket object is automatically
44 43 selected based on the address family specified when the socket object was
45 - A single string is used for the :const:`AF_UNIX` address family. 44 created. Socket addresses are represented as follows:
45
46 - The address of an :const:`AF_UNIX` socket bound to a file system node
47 is represented as a string, using the file system encoding and the
48 ``'surrogateescape'`` error handler (see :pep:`383`). An address in
49 Linux's abstract namespace is returned as a :term:`bytes-like object` with
50 an initial null byte; note that sockets in this namespace can
51 communicate with normal file system sockets, so programs intended to
52 run on Linux may need to deal with both types of address. A string or
53 bytes-like object can be used for either type of address when
54 passing it as an argument.
55
56 .. versionchanged:: 3.3
57 Previously, :const:`AF_UNIX` socket paths were assumed to use UTF-8
58 encoding.
59
60 .. versionchanged: 3.5
61 Writable :term:`bytes-like object` is now accepted.
46 62
47 - A pair ``(host, port)`` is used for the :const:`AF_INET` address family, 63 - A pair ``(host, port)`` is used for the :const:`AF_INET` address family,
48 where *host* is a string representing either a hostname in Internet domain 64 where *host* is a string representing either a hostname in Internet domain
49 notation like ``'daring.cwi.nl'`` or an IPv4 address like ``'100.50.200.5'``, 65 notation like ``'daring.cwi.nl'`` or an IPv4 address like ``'100.50.200.5'``,
50 and *port* is an integer. 66 and *port* is an integer.
51 67
52 - For :const:`AF_INET6` address family, a four-tuple ``(host, port, flowinfo, 68 - For :const:`AF_INET6` address family, a four-tuple ``(host, port, flowinfo,
53 scopeid)`` is used, where *flowinfo* and *scopeid* represent the ``sin6_flowin fo`` 69 scopeid)`` is used, where *flowinfo* and *scopeid* represent the ``sin6_flowin fo``
54 and ``sin6_scope_id`` members in :const:`struct sockaddr_in6` in C. For 70 and ``sin6_scope_id`` members in :const:`struct sockaddr_in6` in C. For
55 :mod:`socket` module methods, *flowinfo* and *scopeid* can be omitted just for 71 :mod:`socket` module methods, *flowinfo* and *scopeid* can be omitted just for
(...skipping 14 matching lines...) Expand all
70 :const:`TIPC_NODE_SCOPE`. 86 :const:`TIPC_NODE_SCOPE`.
71 - If *addr_type* is :const:`TIPC_ADDR_NAME`, then *v1* is the server type, *v2 * is 87 - If *addr_type* is :const:`TIPC_ADDR_NAME`, then *v1* is the server type, *v2 * is
72 the port identifier, and *v3* should be 0. 88 the port identifier, and *v3* should be 0.
73 89
74 If *addr_type* is :const:`TIPC_ADDR_NAMESEQ`, then *v1* is the server type, *v2* 90 If *addr_type* is :const:`TIPC_ADDR_NAMESEQ`, then *v1* is the server type, *v2*
75 is the lower port number, and *v3* is the upper port number. 91 is the lower port number, and *v3* is the upper port number.
76 92
77 If *addr_type* is :const:`TIPC_ADDR_ID`, then *v1* is the node, *v2* is the 93 If *addr_type* is :const:`TIPC_ADDR_ID`, then *v1* is the node, *v2* is the
78 reference, and *v3* should be set to 0. 94 reference, and *v3* should be set to 0.
79 95
80 If *addr_type* is :const:`TIPC_ADDR_ID`, then *v1* is the node, *v2* is the 96 - A tuple ``(interface, )`` is used for the :const:`AF_CAN` address family,
81 reference, and *v3* should be set to 0. 97 where *interface* is a string representing a network interface name like
82 98 ``'can0'``. The network interface name ``''`` can be used to receive packets
83 - Certain other address families (:const:`AF_BLUETOOTH`, :const:`AF_PACKET`) 99 from all network interfaces of this family.
100
101 - A string or a tuple ``(id, unit)`` is used for the :const:`SYSPROTO_CONTROL`
102 protocol of the :const:`PF_SYSTEM` family. The string is the name of a
103 kernel control using a dynamically-assigned ID. The tuple can be used if ID
104 and unit number of the kernel control are known or if a registered ID is
105 used.
106
107 .. versionadded:: 3.3
108
109 - :const:`AF_BLUETOOTH` supports the following protocols and address
110 formats:
111
112 - :const:`BTPROTO_L2CAP` accepts ``(bdaddr, psm)`` where ``bdaddr`` is
113 the Bluetooth address as a string and ``psm`` is an integer.
114
115 - :const:`BTPROTO_RFCOMM` accepts ``(bdaddr, channel)`` where ``bdaddr``
116 is the Bluetooth address as a string and ``channel`` is an integer.
117
118 - :const:`BTPROTO_HCI` accepts ``(device_id,)`` where ``device_id`` is
119 either an integer or a string with the Bluetooth address of the
120 interface. (This depends on your OS; NetBSD and DragonFlyBSD expect
121 a Bluetooth address while everything else expects an integer.)
122
123 .. versionchanged:: 3.2
124 NetBSD and DragonFlyBSD support added.
125
126 - :const:`BTPROTO_SCO` accepts ``bdaddr`` where ``bdaddr`` is a
127 :class:`bytes` object containing the Bluetooth address in a
128 string format. (ex. ``b'12:23:34:45:56:67'``) This protocol is not
129 supported under FreeBSD.
130
131 - Certain other address families (:const:`AF_PACKET`, :const:`AF_CAN`)
84 support specific representations. 132 support specific representations.
85 133
86 .. XXX document them! 134 .. XXX document them!
87 135
88 For IPv4 addresses, two special forms are accepted instead of a host address: 136 For IPv4 addresses, two special forms are accepted instead of a host address:
89 the empty string represents :const:`INADDR_ANY`, and the string 137 the empty string represents :const:`INADDR_ANY`, and the string
90 ``'<broadcast>'`` represents :const:`INADDR_BROADCAST`. This behavior is not 138 ``'<broadcast>'`` represents :const:`INADDR_BROADCAST`. This behavior is not
91 compatible with IPv6, therefore, you may want to avoid these if you intend 139 compatible with IPv6, therefore, you may want to avoid these if you intend
92 to support IPv6 with your Python programs. 140 to support IPv6 with your Python programs.
93 141
94 If you use a hostname in the *host* portion of IPv4/v6 socket address, the 142 If you use a hostname in the *host* portion of IPv4/v6 socket address, the
95 program may show a nondeterministic behavior, as Python uses the first address 143 program may show a nondeterministic behavior, as Python uses the first address
96 returned from the DNS resolution. The socket address will be resolved 144 returned from the DNS resolution. The socket address will be resolved
97 differently into an actual IPv4/v6 address, depending on the results from DNS 145 differently into an actual IPv4/v6 address, depending on the results from DNS
98 resolution and/or the host configuration. For deterministic behavior use a 146 resolution and/or the host configuration. For deterministic behavior use a
99 numeric address in *host* portion. 147 numeric address in *host* portion.
100 148
101 All errors raise exceptions. The normal exceptions for invalid argument types 149 All errors raise exceptions. The normal exceptions for invalid argument types
102 and out-of-memory conditions can be raised; errors related to socket or address 150 and out-of-memory conditions can be raised; starting from Python 3.3, errors
103 semantics raise :exc:`socket.error` or one of its subclasses. 151 related to socket or address semantics raise :exc:`OSError` or one of its
152 subclasses (they used to raise :exc:`socket.error`).
104 153
105 Non-blocking mode is supported through :meth:`~socket.setblocking`. A 154 Non-blocking mode is supported through :meth:`~socket.setblocking`. A
106 generalization of this based on timeouts is supported through 155 generalization of this based on timeouts is supported through
107 :meth:`~socket.settimeout`. 156 :meth:`~socket.settimeout`.
108 157
109 158
110 Module contents 159 Module contents
111 --------------- 160 ---------------
112 161
113 The module :mod:`socket` exports the following constants and functions: 162 The module :mod:`socket` exports the following elements.
114 163
164
165 Exceptions
166 ^^^^^^^^^^
115 167
116 .. exception:: error 168 .. exception:: error
117 169
118 .. index:: module: errno 170 A deprecated alias of :exc:`OSError`.
119 171
120 A subclass of :exc:`IOError`, this exception is raised for socket-related 172 .. versionchanged:: 3.3
121 errors. It is recommended that you inspect its ``errno`` attribute to 173 Following :pep:`3151`, this class was made an alias of :exc:`OSError`.
122 discriminate between different kinds of errors.
123
124 .. seealso::
125 The :mod:`errno` module contains symbolic names for the error codes
126 defined by the underlying operating system.
127 174
128 175
129 .. exception:: herror 176 .. exception:: herror
130 177
131 A subclass of :exc:`socket.error`, this exception is raised for 178 A subclass of :exc:`OSError`, this exception is raised for
132 address-related errors, i.e. for functions that use *h_errno* in the POSIX 179 address-related errors, i.e. for functions that use *h_errno* in the POSIX
133 C API, including :func:`gethostbyname_ex` and :func:`gethostbyaddr`. 180 C API, including :func:`gethostbyname_ex` and :func:`gethostbyaddr`.
134 The accompanying value is a pair ``(h_errno, string)`` representing an 181 The accompanying value is a pair ``(h_errno, string)`` representing an
135 error returned by a library call. *h_errno* is a numeric value, while 182 error returned by a library call. *h_errno* is a numeric value, while
136 *string* represents the description of *h_errno*, as returned by the 183 *string* represents the description of *h_errno*, as returned by the
137 :c:func:`hstrerror` C function. 184 :c:func:`hstrerror` C function.
138 185
186 .. versionchanged:: 3.3
187 This class was made a subclass of :exc:`OSError`.
139 188
140 .. exception:: gaierror 189 .. exception:: gaierror
141 190
142 A subclass of :exc:`socket.error`, this exception is raised for 191 A subclass of :exc:`OSError`, this exception is raised for
143 address-related errors by :func:`getaddrinfo` and :func:`getnameinfo`. 192 address-related errors by :func:`getaddrinfo` and :func:`getnameinfo`.
144 The accompanying value is a pair ``(error, string)`` representing an error 193 The accompanying value is a pair ``(error, string)`` representing an error
145 returned by a library call. *string* represents the description of 194 returned by a library call. *string* represents the description of
146 *error*, as returned by the :c:func:`gai_strerror` C function. The 195 *error*, as returned by the :c:func:`gai_strerror` C function. The
147 numeric *error* value will match one of the :const:`EAI_\*` constants 196 numeric *error* value will match one of the :const:`EAI_\*` constants
148 defined in this module. 197 defined in this module.
149 198
199 .. versionchanged:: 3.3
200 This class was made a subclass of :exc:`OSError`.
150 201
151 .. exception:: timeout 202 .. exception:: timeout
152 203
153 A subclass of :exc:`socket.error`, this exception is raised when a timeout 204 A subclass of :exc:`OSError`, this exception is raised when a timeout
154 occurs on a socket which has had timeouts enabled via a prior call to 205 occurs on a socket which has had timeouts enabled via a prior call to
155 :meth:`~socket.settimeout` (or implicitly through 206 :meth:`~socket.settimeout` (or implicitly through
156 :func:`~socket.setdefaulttimeout`). The accompanying value is a string 207 :func:`~socket.setdefaulttimeout`). The accompanying value is a string
157 whose value is currently always "timed out". 208 whose value is currently always "timed out".
158 209
210 .. versionchanged:: 3.3
211 This class was made a subclass of :exc:`OSError`.
212
213
214 Constants
215 ^^^^^^^^^
216
217 The AF_* and SOCK_* constants are now :class:`AddressFamily` and
218 :class:`SocketKind` :class:`.IntEnum` collections.
219
220 .. versionadded:: 3.4
159 221
160 .. data:: AF_UNIX 222 .. data:: AF_UNIX
161 AF_INET 223 AF_INET
162 AF_INET6 224 AF_INET6
163 225
164 These constants represent the address (and protocol) families, used for the 226 These constants represent the address (and protocol) families, used for the
165 first argument to :func:`socket`. If the :const:`AF_UNIX` constant is not 227 first argument to :func:`.socket`. If the :const:`AF_UNIX` constant is not
166 defined then this protocol is unsupported. More constants may be available 228 defined then this protocol is unsupported. More constants may be available
167 depending on the system. 229 depending on the system.
168 230
169 231
170 .. data:: SOCK_STREAM 232 .. data:: SOCK_STREAM
171 SOCK_DGRAM 233 SOCK_DGRAM
172 SOCK_RAW 234 SOCK_RAW
173 SOCK_RDM 235 SOCK_RDM
174 SOCK_SEQPACKET 236 SOCK_SEQPACKET
175 237
176 These constants represent the socket types, used for the second argument to 238 These constants represent the socket types, used for the second argument to
177 :func:`socket`. More constants may be available depending on the system. 239 :func:`.socket`. More constants may be available depending on the system.
178 (Only :const:`SOCK_STREAM` and :const:`SOCK_DGRAM` appear to be generally 240 (Only :const:`SOCK_STREAM` and :const:`SOCK_DGRAM` appear to be generally
179 useful.) 241 useful.)
180 242
181 .. data:: SOCK_CLOEXEC 243 .. data:: SOCK_CLOEXEC
182 SOCK_NONBLOCK 244 SOCK_NONBLOCK
183 245
184 These two constants, if defined, can be combined with the socket types and 246 These two constants, if defined, can be combined with the socket types and
185 allow you to set some flags atomically (thus avoiding possible race 247 allow you to set some flags atomically (thus avoiding possible race
186 conditions and the need for separate calls). 248 conditions and the need for separate calls).
187 249
188 .. seealso:: 250 .. seealso::
189 251
190 `Secure File Descriptor Handling <http://udrepper.livejournal.com/20407.ht ml>`_ 252 `Secure File Descriptor Handling <http://udrepper.livejournal.com/20407.ht ml>`_
191 for a more thorough explanation. 253 for a more thorough explanation.
192 254
193 Availability: Linux >= 2.6.27. 255 Availability: Linux >= 2.6.27.
194 256
195 .. versionadded:: 3.2 257 .. versionadded:: 3.2
196 258
197 .. data:: SO_* 259 .. data:: SO_*
198 SOMAXCONN 260 SOMAXCONN
199 MSG_* 261 MSG_*
200 SOL_* 262 SOL_*
263 SCM_*
201 IPPROTO_* 264 IPPROTO_*
202 IPPORT_* 265 IPPORT_*
203 INADDR_* 266 INADDR_*
204 IP_* 267 IP_*
205 IPV6_* 268 IPV6_*
206 EAI_* 269 EAI_*
207 AI_* 270 AI_*
208 NI_* 271 NI_*
209 TCP_* 272 TCP_*
210 273
211 Many constants of these forms, documented in the Unix documentation on socket s 274 Many constants of these forms, documented in the Unix documentation on socket s
212 and/or the IP protocol, are also defined in the socket module. They are 275 and/or the IP protocol, are also defined in the socket module. They are
213 generally used in arguments to the :meth:`setsockopt` and :meth:`getsockopt` 276 generally used in arguments to the :meth:`setsockopt` and :meth:`getsockopt`
214 methods of socket objects. In most cases, only those symbols that are define d 277 methods of socket objects. In most cases, only those symbols that are define d
215 in the Unix header files are defined; for a few symbols, default values are 278 in the Unix header files are defined; for a few symbols, default values are
216 provided. 279 provided.
217 280
281 .. data:: AF_CAN
282 PF_CAN
283 SOL_CAN_*
284 CAN_*
285
286 Many constants of these forms, documented in the Linux documentation, are
287 also defined in the socket module.
288
289 Availability: Linux >= 2.6.25.
290
291 .. versionadded:: 3.3
292
293 .. data:: CAN_BCM
294 CAN_BCM_*
295
296 CAN_BCM, in the CAN protocol family, is the broadcast manager (BCM) protocol.
297 Broadcast manager constants, documented in the Linux documentation, are also
298 defined in the socket module.
299
300 Availability: Linux >= 2.6.25.
301
302 .. versionadded:: 3.4
303
304 .. data:: CAN_RAW_FD_FRAMES
305
306 Enables CAN FD support in a CAN_RAW socket. This is disabled by default.
307 This allows your application to send both CAN and CAN FD frames; however,
308 you one must accept both CAN and CAN FD frames when reading from the socket.
309
310 This constant is documented in the Linux documentation.
311
312 Availability: Linux >= 3.6.
313
314 .. versionadded:: 3.5
315
316 .. data:: AF_RDS
317 PF_RDS
318 SOL_RDS
319 RDS_*
320
321 Many constants of these forms, documented in the Linux documentation, are
322 also defined in the socket module.
323
324 Availability: Linux >= 2.6.30.
325
326 .. versionadded:: 3.3
327
328
218 .. data:: SIO_* 329 .. data:: SIO_*
219 RCVALL_* 330 RCVALL_*
220 331
221 Constants for Windows' WSAIoctl(). The constants are used as arguments to the 332 Constants for Windows' WSAIoctl(). The constants are used as arguments to the
222 :meth:`ioctl` method of socket objects. 333 :meth:`~socket.socket.ioctl` method of socket objects.
223 334
224 335
225 .. data:: TIPC_* 336 .. data:: TIPC_*
226 337
227 TIPC related constants, matching the ones exported by the C socket API. See 338 TIPC related constants, matching the ones exported by the C socket API. See
228 the TIPC documentation for more information. 339 the TIPC documentation for more information.
229 340
341 .. data:: AF_LINK
342
343 Availability: BSD, OSX.
344
345 .. versionadded:: 3.4
230 346
231 .. data:: has_ipv6 347 .. data:: has_ipv6
232 348
233 This constant contains a boolean value which indicates if IPv6 is supported o n 349 This constant contains a boolean value which indicates if IPv6 is supported o n
234 this platform. 350 this platform.
351
352 .. data:: BDADDR_ANY
353 BDADDR_LOCAL
354
355 These are string constants containing Bluetooth addresses with special
356 meanings. For example, :const:`BDADDR_ANY` can be used to indicate
357 any address when specifying the binding socket with
358 :const:`BTPROTO_RFCOMM`.
359
360 .. data:: HCI_FILTER
361 HCI_TIME_STAMP
362 HCI_DATA_DIR
363
364 For use with :const:`BTPROTO_HCI`. :const:`HCI_FILTER` is not
365 available for NetBSD or DragonFlyBSD. :const:`HCI_TIME_STAMP` and
366 :const:`HCI_DATA_DIR` are not available for FreeBSD, NetBSD, or
367 DragonFlyBSD.
368
369 Functions
370 ^^^^^^^^^
371
372 Creating sockets
373 ''''''''''''''''
374
375 The following functions all create :ref:`socket objects <socket-objects>`.
376
377
378 .. function:: socket(family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None)
379
380 Create a new socket using the given address family, socket type and protocol
381 number. The address family should be :const:`AF_INET` (the default),
382 :const:`AF_INET6`, :const:`AF_UNIX`, :const:`AF_CAN` or :const:`AF_RDS`. The
383 socket type should be :const:`SOCK_STREAM` (the default),
384 :const:`SOCK_DGRAM`, :const:`SOCK_RAW` or perhaps one of the other ``SOCK_``
385 constants. The protocol number is usually zero and may be omitted or in the
386 case where the address family is :const:`AF_CAN` the protocol should be one
387 of :const:`CAN_RAW` or :const:`CAN_BCM`. If fileno is specified, the other
388 arguments are ignored, causing the socket with the specified file descriptor
389 to return. Unlike :meth:`fromfd`, fileno will return the same socket and not
390 a duplicate. This may help close a detached socket using
391 :meth:`socket.close()`.
392
393 The newly created socket is :ref:`non-inheritable <fd_inheritance>`.
394
395 .. versionchanged:: 3.3
396 The AF_CAN family was added.
397 The AF_RDS family was added.
398
399 .. versionchanged:: 3.4
400 The CAN_BCM protocol was added.
401
402 .. versionchanged:: 3.4
403 The returned socket is now non-inheritable.
404
405
406 .. function:: socketpair([family[, type[, proto]]])
407
408 Build a pair of connected socket objects using the given address family, sock et
409 type, and protocol number. Address family, socket type, and protocol number are
410 as for the :func:`.socket` function above. The default family is :const:`AF_U NIX`
411 if defined on the platform; otherwise, the default is :const:`AF_INET`.
412
413 The newly created sockets are :ref:`non-inheritable <fd_inheritance>`.
414
415 .. versionchanged:: 3.2
416 The returned socket objects now support the whole socket API, rather
417 than a subset.
418
419 .. versionchanged:: 3.4
420 The returned sockets are now non-inheritable.
421
422 .. versionchanged:: 3.5
423 Windows support added.
235 424
236 425
237 .. function:: create_connection(address[, timeout[, source_address]]) 426 .. function:: create_connection(address[, timeout[, source_address]])
238 427
239 Connect to a TCP service listening on the Internet *address* (a 2-tuple 428 Connect to a TCP service listening on the Internet *address* (a 2-tuple
240 ``(host, port)``), and return the socket object. This is a higher-level 429 ``(host, port)``), and return the socket object. This is a higher-level
241 function than :meth:`socket.connect`: if *host* is a non-numeric hostname, 430 function than :meth:`socket.connect`: if *host* is a non-numeric hostname,
242 it will try to resolve it for both :data:`AF_INET` and :data:`AF_INET6`, 431 it will try to resolve it for both :data:`AF_INET` and :data:`AF_INET6`,
243 and then try to connect to all possible addresses in turn until a 432 and then try to connect to all possible addresses in turn until a
244 connection succeeds. This makes it easy to write clients that are 433 connection succeeds. This makes it easy to write clients that are
245 compatible to both IPv4 and IPv6. 434 compatible to both IPv4 and IPv6.
246 435
247 Passing the optional *timeout* parameter will set the timeout on the 436 Passing the optional *timeout* parameter will set the timeout on the
248 socket instance before attempting to connect. If no *timeout* is 437 socket instance before attempting to connect. If no *timeout* is
249 supplied, the global default timeout setting returned by 438 supplied, the global default timeout setting returned by
250 :func:`getdefaulttimeout` is used. 439 :func:`getdefaulttimeout` is used.
251 440
252 If supplied, *source_address* must be a 2-tuple ``(host, port)`` for the 441 If supplied, *source_address* must be a 2-tuple ``(host, port)`` for the
253 socket to bind to as its source address before connecting. If host or port 442 socket to bind to as its source address before connecting. If host or port
254 are '' or 0 respectively the OS default behavior will be used. 443 are '' or 0 respectively the OS default behavior will be used.
255 444
256 .. versionchanged:: 3.2 445 .. versionchanged:: 3.2
257 *source_address* was added. 446 *source_address* was added.
258 447
259 .. versionchanged:: 3.2 448 .. versionchanged:: 3.2
260 support for the :keyword:`with` statement was added. 449 support for the :keyword:`with` statement was added.
261 450
262 451
452 .. function:: fromfd(fd, family, type, proto=0)
453
454 Duplicate the file descriptor *fd* (an integer as returned by a file object's
455 :meth:`fileno` method) and build a socket object from the result. Address
456 family, socket type and protocol number are as for the :func:`.socket` functi on
457 above. The file descriptor should refer to a socket, but this is not checked ---
458 subsequent operations on the object may fail if the file descriptor is invali d.
459 This function is rarely needed, but can be used to get or set socket options on
460 a socket passed to a program as standard input or output (such as a server
461 started by the Unix inet daemon). The socket is assumed to be in blocking mo de.
462
463 The newly created socket is :ref:`non-inheritable <fd_inheritance>`.
464
465 .. versionchanged:: 3.4
466 The returned socket is now non-inheritable.
467
468
469 .. function:: fromshare(data)
470
471 Instantiate a socket from data obtained from the :meth:`socket.share`
472 method. The socket is assumed to be in blocking mode.
473
474 Availability: Windows.
475
476 .. versionadded:: 3.3
477
478
479 .. data:: SocketType
480
481 This is a Python type object that represents the socket object type. It is th e
482 same as ``type(socket(...))``.
483
484
485 Other functions
486 '''''''''''''''
487
488 The :mod:`socket` module also offers various network-related services:
489
490
263 .. function:: getaddrinfo(host, port, family=0, type=0, proto=0, flags=0) 491 .. function:: getaddrinfo(host, port, family=0, type=0, proto=0, flags=0)
264 492
265 Translate the *host*/*port* argument into a sequence of 5-tuples that contain 493 Translate the *host*/*port* argument into a sequence of 5-tuples that contain
266 all the necessary arguments for creating a socket connected to that service. 494 all the necessary arguments for creating a socket connected to that service.
267 *host* is a domain name, a string representation of an IPv4/v6 address 495 *host* is a domain name, a string representation of an IPv4/v6 address
268 or ``None``. *port* is a string service name such as ``'http'``, a numeric 496 or ``None``. *port* is a string service name such as ``'http'``, a numeric
269 port number or ``None``. By passing ``None`` as the value of *host* 497 port number or ``None``. By passing ``None`` as the value of *host*
270 and *port*, you can pass ``NULL`` to the underlying C API. 498 and *port*, you can pass ``NULL`` to the underlying C API.
271 499
272 The *family*, *type* and *proto* arguments can be optionally specified 500 The *family*, *type* and *proto* arguments can be optionally specified
273 in order to narrow the list of addresses returned. Passing zero as a 501 in order to narrow the list of addresses returned. Passing zero as a
274 value for each of these arguments selects the full range of results. 502 value for each of these arguments selects the full range of results.
275 The *flags* argument can be one or several of the ``AI_*`` constants, 503 The *flags* argument can be one or several of the ``AI_*`` constants,
276 and will influence how results are computed and returned. 504 and will influence how results are computed and returned.
277 For example, :const:`AI_NUMERICHOST` will disable domain name resolution 505 For example, :const:`AI_NUMERICHOST` will disable domain name resolution
278 and will raise an error if *host* is a domain name. 506 and will raise an error if *host* is a domain name.
279 507
280 The function returns a list of 5-tuples with the following structure: 508 The function returns a list of 5-tuples with the following structure:
281 509
282 ``(family, type, proto, canonname, sockaddr)`` 510 ``(family, type, proto, canonname, sockaddr)``
283 511
284 In these tuples, *family*, *type*, *proto* are all integers and are 512 In these tuples, *family*, *type*, *proto* are all integers and are
285 meant to be passed to the :func:`socket` function. *canonname* will be 513 meant to be passed to the :func:`.socket` function. *canonname* will be
286 a string representing the canonical name of the *host* if 514 a string representing the canonical name of the *host* if
287 :const:`AI_CANONNAME` is part of the *flags* argument; else *canonname* 515 :const:`AI_CANONNAME` is part of the *flags* argument; else *canonname*
288 will be empty. *sockaddr* is a tuple describing a socket address, whose 516 will be empty. *sockaddr* is a tuple describing a socket address, whose
289 format depends on the returned *family* (a ``(address, port)`` 2-tuple for 517 format depends on the returned *family* (a ``(address, port)`` 2-tuple for
290 :const:`AF_INET`, a ``(address, port, flow info, scope id)`` 4-tuple for 518 :const:`AF_INET`, a ``(address, port, flow info, scope id)`` 4-tuple for
291 :const:`AF_INET6`), and is meant to be passed to the :meth:`socket.connect` 519 :const:`AF_INET6`), and is meant to be passed to the :meth:`socket.connect`
292 method. 520 method.
293 521
294 The following example fetches address information for a hypothetical TCP 522 The following example fetches address information for a hypothetical TCP
295 connection to ``www.python.org`` on port 80 (results may differ on your 523 connection to ``example.org`` on port 80 (results may differ on your
296 system if IPv6 isn't enabled):: 524 system if IPv6 isn't enabled)::
297 525
298 >>> socket.getaddrinfo("www.python.org", 80, proto=socket.SOL_TCP) 526 >>> socket.getaddrinfo("example.org", 80, proto=socket.IPPROTO_TCP)
299 [(2, 1, 6, '', ('82.94.164.162', 80)), 527 [(<AddressFamily.AF_INET6: 10>, <SocketType.SOCK_STREAM: 1>,
300 (10, 1, 6, '', ('2001:888:2000:d::a2', 80, 0, 0))] 528 6, '', ('2606:2800:220:1:248:1893:25c8:1946', 80, 0, 0)),
529 (<AddressFamily.AF_INET: 2>, <SocketType.SOCK_STREAM: 1>,
530 6, '', ('93.184.216.34', 80))]
301 531
302 .. versionchanged:: 3.2 532 .. versionchanged:: 3.2
303 parameters can now be passed as single keyword arguments. 533 parameters can now be passed using keyword arguments.
304 534
305 .. function:: getfqdn([name]) 535 .. function:: getfqdn([name])
306 536
307 Return a fully qualified domain name for *name*. If *name* is omitted or empt y, 537 Return a fully qualified domain name for *name*. If *name* is omitted or empt y,
308 it is interpreted as the local host. To find the fully qualified name, the 538 it is interpreted as the local host. To find the fully qualified name, the
309 hostname returned by :func:`gethostbyaddr` is checked, followed by aliases fo r the 539 hostname returned by :func:`gethostbyaddr` is checked, followed by aliases fo r the
310 host, if available. The first name which includes a period is selected. In 540 host, if available. The first name which includes a period is selected. In
311 case no fully qualified domain name is available, the hostname as returned by 541 case no fully qualified domain name is available, the hostname as returned by
312 :func:`gethostname` is returned. 542 :func:`gethostname` is returned.
313 543
(...skipping 23 matching lines...) Expand all
337 567
338 Return a string containing the hostname of the machine where the Python 568 Return a string containing the hostname of the machine where the Python
339 interpreter is currently executing. 569 interpreter is currently executing.
340 570
341 If you want to know the current machine's IP address, you may want to use 571 If you want to know the current machine's IP address, you may want to use
342 ``gethostbyname(gethostname())``. This operation assumes that there is a 572 ``gethostbyname(gethostname())``. This operation assumes that there is a
343 valid address-to-host mapping for the host, and the assumption does not 573 valid address-to-host mapping for the host, and the assumption does not
344 always hold. 574 always hold.
345 575
346 Note: :func:`gethostname` doesn't always return the fully qualified domain 576 Note: :func:`gethostname` doesn't always return the fully qualified domain
347 name; use ``getfqdn()`` (see above). 577 name; use :func:`getfqdn` for that.
348 578
349 579
350 .. function:: gethostbyaddr(ip_address) 580 .. function:: gethostbyaddr(ip_address)
351 581
352 Return a triple ``(hostname, aliaslist, ipaddrlist)`` where *hostname* is the 582 Return a triple ``(hostname, aliaslist, ipaddrlist)`` where *hostname* is the
353 primary host name responding to the given *ip_address*, *aliaslist* is a 583 primary host name responding to the given *ip_address*, *aliaslist* is a
354 (possibly empty) list of alternative host names for the same address, and 584 (possibly empty) list of alternative host names for the same address, and
355 *ipaddrlist* is a list of IPv4/v6 addresses for the same interface on the sam e 585 *ipaddrlist* is a list of IPv4/v6 addresses for the same interface on the sam e
356 host (most likely containing only a single address). To find the fully qualif ied 586 host (most likely containing only a single address). To find the fully qualif ied
357 domain name, use the function :func:`getfqdn`. :func:`gethostbyaddr` supports 587 domain name, use the function :func:`getfqdn`. :func:`gethostbyaddr` supports
358 both IPv4 and IPv6. 588 both IPv4 and IPv6.
359 589
360 590
361 .. function:: getnameinfo(sockaddr, flags) 591 .. function:: getnameinfo(sockaddr, flags)
362 592
363 Translate a socket address *sockaddr* into a 2-tuple ``(host, port)``. Depend ing 593 Translate a socket address *sockaddr* into a 2-tuple ``(host, port)``. Depend ing
364 on the settings of *flags*, the result can contain a fully-qualified domain n ame 594 on the settings of *flags*, the result can contain a fully-qualified domain n ame
365 or numeric address representation in *host*. Similarly, *port* can contain a 595 or numeric address representation in *host*. Similarly, *port* can contain a
366 string port name or a numeric port number. 596 string port name or a numeric port number.
367 597
368 598
369 .. function:: getprotobyname(protocolname) 599 .. function:: getprotobyname(protocolname)
370 600
371 Translate an Internet protocol name (for example, ``'icmp'``) to a constant 601 Translate an Internet protocol name (for example, ``'icmp'``) to a constant
372 suitable for passing as the (optional) third argument to the :func:`socket` 602 suitable for passing as the (optional) third argument to the :func:`.socket`
373 function. This is usually only needed for sockets opened in "raw" mode 603 function. This is usually only needed for sockets opened in "raw" mode
374 (:const:`SOCK_RAW`); for the normal socket modes, the correct protocol is cho sen 604 (:const:`SOCK_RAW`); for the normal socket modes, the correct protocol is cho sen
375 automatically if the protocol is omitted or zero. 605 automatically if the protocol is omitted or zero.
376 606
377 607
378 .. function:: getservbyname(servicename[, protocolname]) 608 .. function:: getservbyname(servicename[, protocolname])
379 609
380 Translate an Internet service name and protocol name to a port number for tha t 610 Translate an Internet service name and protocol name to a port number for tha t
381 service. The optional protocol name, if given, should be ``'tcp'`` or 611 service. The optional protocol name, if given, should be ``'tcp'`` or
382 ``'udp'``, otherwise any protocol will match. 612 ``'udp'``, otherwise any protocol will match.
383 613
384 614
385 .. function:: getservbyport(port[, protocolname]) 615 .. function:: getservbyport(port[, protocolname])
386 616
387 Translate an Internet port number and protocol name to a service name for tha t 617 Translate an Internet port number and protocol name to a service name for tha t
388 service. The optional protocol name, if given, should be ``'tcp'`` or 618 service. The optional protocol name, if given, should be ``'tcp'`` or
389 ``'udp'``, otherwise any protocol will match. 619 ``'udp'``, otherwise any protocol will match.
390
391
392 .. function:: socket([family[, type[, proto[, fileno]]]])
393
394 Create a new socket using the given address family, socket type and protocol
395 number. The address family should be :const:`AF_INET` (the default),
396 :const:`AF_INET6` or :const:`AF_UNIX`. The socket type should be
397 :const:`SOCK_STREAM` (the default), :const:`SOCK_DGRAM` or perhaps one of the
398 other ``SOCK_`` constants. The protocol number is usually zero and may be
399 omitted in that case.
400
401 .. note::
402 If a file descriptor *fileno* is specified, the other arguments
403 are ignored and and the socket with this file descriptor is returned. Unli ke
404 :meth:`fromfd`, this does not cause a duplication of the file descriptor
405 and therefore supports the special case of closing detached socket handles
406 on Windows using ``socket.socket(fileno=handle).close()``.
407
408
409 .. function:: socketpair([family[, type[, proto]]])
410
411 Build a pair of connected socket objects using the given address family, sock et
412 type, and protocol number. Address family, socket type, and protocol number are
413 as for the :func:`socket` function above. The default family is :const:`AF_UN IX`
414 if defined on the platform; otherwise, the default is :const:`AF_INET`.
415 Availability: Unix.
416
417 .. versionchanged:: 3.2
418 The returned socket objects now support the whole socket API, rather
419 than a subset.
420
421
422 .. function:: fromfd(fd, family, type[, proto])
423
424 Duplicate the file descriptor *fd* (an integer as returned by a file object's
425 :meth:`fileno` method) and build a socket object from the result. Address
426 family, socket type and protocol number are as for the :func:`socket` functio n
427 above. The file descriptor should refer to a socket, but this is not checked ---
428 subsequent operations on the object may fail if the file descriptor is invali d.
429 This function is rarely needed, but can be used to get or set socket options on
430 a socket passed to a program as standard input or output (such as a server
431 started by the Unix inet daemon). The socket is assumed to be in blocking mo de.
432 620
433 621
434 .. function:: ntohl(x) 622 .. function:: ntohl(x)
435 623
436 Convert 32-bit positive integers from network to host byte order. On machine s 624 Convert 32-bit positive integers from network to host byte order. On machine s
437 where the host byte order is the same as network byte order, this is a no-op; 625 where the host byte order is the same as network byte order, this is a no-op;
438 otherwise, it performs a 4-byte swap operation. 626 otherwise, it performs a 4-byte swap operation.
439 627
440 628
441 .. function:: ntohs(x) 629 .. function:: ntohs(x)
(...skipping 22 matching lines...) Expand all
464 Convert an IPv4 address from dotted-quad string format (for example, 652 Convert an IPv4 address from dotted-quad string format (for example,
465 '123.45.67.89') to 32-bit packed binary format, as a bytes object four charac ters in 653 '123.45.67.89') to 32-bit packed binary format, as a bytes object four charac ters in
466 length. This is useful when conversing with a program that uses the standard C 654 length. This is useful when conversing with a program that uses the standard C
467 library and needs objects of type :c:type:`struct in_addr`, which is the C ty pe 655 library and needs objects of type :c:type:`struct in_addr`, which is the C ty pe
468 for the 32-bit packed binary this function returns. 656 for the 32-bit packed binary this function returns.
469 657
470 :func:`inet_aton` also accepts strings with less than three dots; see the 658 :func:`inet_aton` also accepts strings with less than three dots; see the
471 Unix manual page :manpage:`inet(3)` for details. 659 Unix manual page :manpage:`inet(3)` for details.
472 660
473 If the IPv4 address string passed to this function is invalid, 661 If the IPv4 address string passed to this function is invalid,
474 :exc:`socket.error` will be raised. Note that exactly what is valid depends o n 662 :exc:`OSError` will be raised. Note that exactly what is valid depends on
475 the underlying C implementation of :c:func:`inet_aton`. 663 the underlying C implementation of :c:func:`inet_aton`.
476 664
477 :func:`inet_aton` does not support IPv6, and :func:`inet_pton` should be used 665 :func:`inet_aton` does not support IPv6, and :func:`inet_pton` should be used
478 instead for IPv4/v6 dual stack support. 666 instead for IPv4/v6 dual stack support.
479 667
480 668
481 .. function:: inet_ntoa(packed_ip) 669 .. function:: inet_ntoa(packed_ip)
482 670
483 Convert a 32-bit packed IPv4 address (a bytes object four characters in 671 Convert a 32-bit packed IPv4 address (a :term:`bytes-like object` four
484 length) to its standard dotted-quad string representation (for example, 672 bytes in length) to its standard dotted-quad string representation (for examp le,
485 '123.45.67.89'). This is useful when conversing with a program that uses the 673 '123.45.67.89'). This is useful when conversing with a program that uses the
486 standard C library and needs objects of type :c:type:`struct in_addr`, which 674 standard C library and needs objects of type :c:type:`struct in_addr`, which
487 is the C type for the 32-bit packed binary data this function takes as an 675 is the C type for the 32-bit packed binary data this function takes as an
488 argument. 676 argument.
489 677
490 If the byte sequence passed to this function is not exactly 4 bytes in 678 If the byte sequence passed to this function is not exactly 4 bytes in
491 length, :exc:`socket.error` will be raised. :func:`inet_ntoa` does not 679 length, :exc:`OSError` will be raised. :func:`inet_ntoa` does not
492 support IPv6, and :func:`inet_ntop` should be used instead for IPv4/v6 dual 680 support IPv6, and :func:`inet_ntop` should be used instead for IPv4/v6 dual
493 stack support. 681 stack support.
682
683 .. versionchanged: 3.5
684 Writable :term:`bytes-like object` is now accepted.
494 685
495 686
496 .. function:: inet_pton(address_family, ip_string) 687 .. function:: inet_pton(address_family, ip_string)
497 688
498 Convert an IP address from its family-specific string format to a packed, 689 Convert an IP address from its family-specific string format to a packed,
499 binary format. :func:`inet_pton` is useful when a library or network protocol 690 binary format. :func:`inet_pton` is useful when a library or network protocol
500 calls for an object of type :c:type:`struct in_addr` (similar to 691 calls for an object of type :c:type:`struct in_addr` (similar to
501 :func:`inet_aton`) or :c:type:`struct in6_addr`. 692 :func:`inet_aton`) or :c:type:`struct in6_addr`.
502 693
503 Supported values for *address_family* are currently :const:`AF_INET` and 694 Supported values for *address_family* are currently :const:`AF_INET` and
504 :const:`AF_INET6`. If the IP address string *ip_string* is invalid, 695 :const:`AF_INET6`. If the IP address string *ip_string* is invalid,
505 :exc:`socket.error` will be raised. Note that exactly what is valid depends o n 696 :exc:`OSError` will be raised. Note that exactly what is valid depends on
506 both the value of *address_family* and the underlying implementation of 697 both the value of *address_family* and the underlying implementation of
507 :c:func:`inet_pton`. 698 :c:func:`inet_pton`.
508 699
509 Availability: Unix (maybe not all platforms). 700 Availability: Unix (maybe not all platforms), Windows.
701
702 .. versionchanged:: 3.4
703 Windows support added
510 704
511 705
512 .. function:: inet_ntop(address_family, packed_ip) 706 .. function:: inet_ntop(address_family, packed_ip)
513 707
514 Convert a packed IP address (a bytes object of some number of characters) to its 708 Convert a packed IP address (a :term:`bytes-like object` of some number of
515 standard, family-specific string representation (for example, ``'7.10.0.5'`` or 709 bytes) to its standard, family-specific string representation (for
516 ``'5aef:2b::8'``). :func:`inet_ntop` is useful when a library or network prot ocol 710 example, ``'7.10.0.5'`` or ``'5aef:2b::8'``).
517 returns an object of type :c:type:`struct in_addr` (similar to :func:`inet_nt oa`) 711 :func:`inet_ntop` is useful when a library or network protocol returns an
518 or :c:type:`struct in6_addr`. 712 object of type :c:type:`struct in_addr` (similar to :func:`inet_ntoa`) or
713 :c:type:`struct in6_addr`.
519 714
520 Supported values for *address_family* are currently :const:`AF_INET` and 715 Supported values for *address_family* are currently :const:`AF_INET` and
521 :const:`AF_INET6`. If the string *packed_ip* is not the correct length for th e 716 :const:`AF_INET6`. If the bytes object *packed_ip* is not the correct
522 specified address family, :exc:`ValueError` will be raised. A 717 length for the specified address family, :exc:`ValueError` will be raised.
523 :exc:`socket.error` is raised for errors from the call to :func:`inet_ntop`. 718 A :exc:`OSError` is raised for errors from the call to :func:`inet_ntop`.
524 719
525 Availability: Unix (maybe not all platforms). 720 Availability: Unix (maybe not all platforms), Windows.
721
722 .. versionchanged:: 3.4
723 Windows support added
724
725 .. versionchanged: 3.5
726 Writable :term:`bytes-like object` is now accepted.
727
728
729 ..
730 XXX: Are sendmsg(), recvmsg() and CMSG_*() available on any
731 non-Unix platforms? The old (obsolete?) 4.2BSD form of the
732 interface, in which struct msghdr has no msg_control or
733 msg_controllen members, is not currently supported.
734
735 .. function:: CMSG_LEN(length)
736
737 Return the total length, without trailing padding, of an ancillary
738 data item with associated data of the given *length*. This value
739 can often be used as the buffer size for :meth:`~socket.recvmsg` to
740 receive a single item of ancillary data, but :rfc:`3542` requires
741 portable applications to use :func:`CMSG_SPACE` and thus include
742 space for padding, even when the item will be the last in the
743 buffer. Raises :exc:`OverflowError` if *length* is outside the
744 permissible range of values.
745
746 Availability: most Unix platforms, possibly others.
747
748 .. versionadded:: 3.3
749
750
751 .. function:: CMSG_SPACE(length)
752
753 Return the buffer size needed for :meth:`~socket.recvmsg` to
754 receive an ancillary data item with associated data of the given
755 *length*, along with any trailing padding. The buffer space needed
756 to receive multiple items is the sum of the :func:`CMSG_SPACE`
757 values for their associated data lengths. Raises
758 :exc:`OverflowError` if *length* is outside the permissible range
759 of values.
760
761 Note that some systems might support ancillary data without
762 providing this function. Also note that setting the buffer size
763 using the results of this function may not precisely limit the
764 amount of ancillary data that can be received, since additional
765 data may be able to fit into the padding area.
766
767 Availability: most Unix platforms, possibly others.
768
769 .. versionadded:: 3.3
526 770
527 771
528 .. function:: getdefaulttimeout() 772 .. function:: getdefaulttimeout()
529 773
530 Return the default timeout in seconds (float) for new socket objects. A value 774 Return the default timeout in seconds (float) for new socket objects. A value
531 of ``None`` indicates that new socket objects have no timeout. When the socke t 775 of ``None`` indicates that new socket objects have no timeout. When the socke t
532 module is first imported, the default is ``None``. 776 module is first imported, the default is ``None``.
533 777
534 778
535 .. function:: setdefaulttimeout(timeout) 779 .. function:: setdefaulttimeout(timeout)
536 780
537 Set the default timeout in seconds (float) for new socket objects. When 781 Set the default timeout in seconds (float) for new socket objects. When
538 the socket module is first imported, the default is ``None``. See 782 the socket module is first imported, the default is ``None``. See
539 :meth:`~socket.settimeout` for possible values and their respective 783 :meth:`~socket.settimeout` for possible values and their respective
540 meanings. 784 meanings.
541 785
542 786
543 .. data:: SocketType 787 .. function:: sethostname(name)
544 788
545 This is a Python type object that represents the socket object type. It is th e 789 Set the machine's hostname to *name*. This will raise a
546 same as ``type(socket(...))``. 790 :exc:`OSError` if you don't have enough rights.
791
792 Availability: Unix.
793
794 .. versionadded:: 3.3
795
796
797 .. function:: if_nameindex()
798
799 Return a list of network interface information
800 (index int, name string) tuples.
801 :exc:`OSError` if the system call fails.
802
803 Availability: Unix.
804
805 .. versionadded:: 3.3
806
807
808 .. function:: if_nametoindex(if_name)
809
810 Return a network interface index number corresponding to an
811 interface name.
812 :exc:`OSError` if no interface with the given name exists.
813
814 Availability: Unix.
815
816 .. versionadded:: 3.3
817
818
819 .. function:: if_indextoname(if_index)
820
821 Return a network interface name corresponding to a
822 interface index number.
823 :exc:`OSError` if no interface with the given index exists.
824
825 Availability: Unix.
826
827 .. versionadded:: 3.3
547 828
548 829
549 .. _socket-objects: 830 .. _socket-objects:
550 831
551 Socket Objects 832 Socket Objects
552 -------------- 833 --------------
553 834
554 Socket objects have the following methods. Except for :meth:`makefile` these 835 Socket objects have the following methods. Except for
555 correspond to Unix system calls applicable to sockets. 836 :meth:`~socket.makefile`, these correspond to Unix system calls applicable
837 to sockets.
556 838
557 839
558 .. method:: socket.accept() 840 .. method:: socket.accept()
559 841
560 Accept a connection. The socket must be bound to an address and listening for 842 Accept a connection. The socket must be bound to an address and listening for
561 connections. The return value is a pair ``(conn, address)`` where *conn* is a 843 connections. The return value is a pair ``(conn, address)`` where *conn* is a
562 *new* socket object usable to send and receive data on the connection, and 844 *new* socket object usable to send and receive data on the connection, and
563 *address* is the address bound to the socket on the other end of the connecti on. 845 *address* is the address bound to the socket on the other end of the connecti on.
564 846
847 The newly created socket is :ref:`non-inheritable <fd_inheritance>`.
848
849 .. versionchanged:: 3.4
850 The socket is now non-inheritable.
851
852 .. versionchanged:: 3.5
853 If the system call is interrupted and the signal handler does not raise
854 an exception, the method now retries the system call instead of raising
855 an :exc:`InterruptedError` exception (see :pep:`475` for the rationale).
856
565 857
566 .. method:: socket.bind(address) 858 .. method:: socket.bind(address)
567 859
568 Bind the socket to *address*. The socket must not already be bound. (The for mat 860 Bind the socket to *address*. The socket must not already be bound. (The for mat
569 of *address* depends on the address family --- see above.) 861 of *address* depends on the address family --- see above.)
570 862
571 863
572 .. method:: socket.close() 864 .. method:: socket.close()
573 865
574 Close the socket. All future operations on the socket object will fail. The 866 Mark the socket closed. The underlying system resource (e.g. a file
575 remote end will receive no more data (after queued data is flushed). Sockets are 867 descriptor) is also closed when all file objects from :meth:`makefile()`
576 automatically closed when they are garbage-collected. 868 are closed. Once that happens, all future operations on the socket
869 object will fail. The remote end will receive no more data (after
870 queued data is flushed).
871
872 Sockets are automatically closed when they are garbage-collected, but
873 it is recommended to :meth:`close` them explicitly, or to use a
874 :keyword:`with` statement around them.
577 875
578 .. note:: 876 .. note::
877
579 :meth:`close()` releases the resource associated with a connection but 878 :meth:`close()` releases the resource associated with a connection but
580 does not necessarily close the connection immediately. If you want 879 does not necessarily close the connection immediately. If you want
581 to close the connection in a timely fashion, call :meth:`shutdown()` 880 to close the connection in a timely fashion, call :meth:`shutdown()`
582 before :meth:`close()`. 881 before :meth:`close()`.
583 882
584 883
585 .. method:: socket.connect(address) 884 .. method:: socket.connect(address)
586 885
587 Connect to a remote socket at *address*. (The format of *address* depends on the 886 Connect to a remote socket at *address*. (The format of *address* depends on the
588 address family --- see above.) 887 address family --- see above.)
888
889 If the connection is interrupted by a signal, the method waits until the
890 connection completes, or raise a :exc:`socket.timeout` on timeout, if the
891 signal handler doesn't raise an exception and the socket is blocking or has
892 a timeout. For non-blocking sockets, the method raises an
893 :exc:`InterruptedError` exception if the connection is interrupted by a
894 signal (or the exception raised by the signal handler).
895
896 .. versionchanged:: 3.5
897 The method now waits until the connection completes instead of raising an
898 :exc:`InterruptedError` exception if the connection is interrupted by a
899 signal, the signal handler doesn't raise an exception and the socket is
900 blocking or has a timeout (see the :pep:`475` for the rationale).
589 901
590 902
591 .. method:: socket.connect_ex(address) 903 .. method:: socket.connect_ex(address)
592 904
593 Like ``connect(address)``, but return an error indicator instead of raising a n 905 Like ``connect(address)``, but return an error indicator instead of raising a n
594 exception for errors returned by the C-level :c:func:`connect` call (other 906 exception for errors returned by the C-level :c:func:`connect` call (other
595 problems, such as "host not found," can still raise exceptions). The error 907 problems, such as "host not found," can still raise exceptions). The error
596 indicator is ``0`` if the operation succeeded, otherwise the value of the 908 indicator is ``0`` if the operation succeeded, otherwise the value of the
597 :c:data:`errno` variable. This is useful to support, for example, asynchrono us 909 :c:data:`errno` variable. This is useful to support, for example, asynchrono us
598 connects. 910 connects.
599 911
600 912
601 .. method:: socket.detach() 913 .. method:: socket.detach()
602 914
603 Put the socket object into closed state without actually closing the 915 Put the socket object into closed state without actually closing the
604 underlying file descriptor. The file descriptor is returned, and can 916 underlying file descriptor. The file descriptor is returned, and can
605 be reused for other purposes. 917 be reused for other purposes.
606 918
607 .. versionadded:: 3.2 919 .. versionadded:: 3.2
608 920
609 921
922 .. method:: socket.dup()
923
924 Duplicate the socket.
925
926 The newly created socket is :ref:`non-inheritable <fd_inheritance>`.
927
928 .. versionchanged:: 3.4
929 The socket is now non-inheritable.
930
931
610 .. method:: socket.fileno() 932 .. method:: socket.fileno()
611 933
612 Return the socket's file descriptor (a small integer). This is useful with 934 Return the socket's file descriptor (a small integer). This is useful with
613 :func:`select.select`. 935 :func:`select.select`.
614 936
615 Under Windows the small integer returned by this method cannot be used where a 937 Under Windows the small integer returned by this method cannot be used where a
616 file descriptor can be used (such as :func:`os.fdopen`). Unix does not have 938 file descriptor can be used (such as :func:`os.fdopen`). Unix does not have
617 this limitation. 939 this limitation.
940
941
942 .. method:: socket.get_inheritable()
943
944 Get the :ref:`inheritable flag <fd_inheritance>` of the socket's file
945 descriptor or socket's handle: ``True`` if the socket can be inherited in
946 child processes, ``False`` if it cannot.
947
948 .. versionadded:: 3.4
618 949
619 950
620 .. method:: socket.getpeername() 951 .. method:: socket.getpeername()
621 952
622 Return the remote address to which the socket is connected. This is useful t o 953 Return the remote address to which the socket is connected. This is useful t o
623 find out the port number of a remote IPv4/v6 socket, for instance. (The forma t 954 find out the port number of a remote IPv4/v6 socket, for instance. (The forma t
624 of the address returned depends on the address family --- see above.) On som e 955 of the address returned depends on the address family --- see above.) On som e
625 systems this function is not supported. 956 systems this function is not supported.
626 957
627 958
(...skipping 28 matching lines...) Expand all
656 :platform: Windows 987 :platform: Windows
657 988
658 The :meth:`ioctl` method is a limited interface to the WSAIoctl system 989 The :meth:`ioctl` method is a limited interface to the WSAIoctl system
659 interface. Please refer to the `Win32 documentation 990 interface. Please refer to the `Win32 documentation
660 <http://msdn.microsoft.com/en-us/library/ms741621%28VS.85%29.aspx>`_ for more 991 <http://msdn.microsoft.com/en-us/library/ms741621%28VS.85%29.aspx>`_ for more
661 information. 992 information.
662 993
663 On other platforms, the generic :func:`fcntl.fcntl` and :func:`fcntl.ioctl` 994 On other platforms, the generic :func:`fcntl.fcntl` and :func:`fcntl.ioctl`
664 functions may be used; they accept a socket object as their first argument. 995 functions may be used; they accept a socket object as their first argument.
665 996
666 .. method:: socket.listen(backlog) 997 .. method:: socket.listen([backlog])
667 998
668 Listen for connections made to the socket. The *backlog* argument specifies the 999 Enable a server to accept connections. If *backlog* is specified, it must
669 maximum number of queued connections and should be at least 0; the maximum va lue 1000 be at least 0 (if it is lower, it is set to 0); it specifies the number of
670 is system-dependent (usually 5), the minimum value is forced to 0. 1001 unaccepted connections that the system will allow before refusing new
671 1002 connections. If not specified, a default reasonable value is chosen.
1003
1004 .. versionchanged:: 3.5
1005 The *backlog* parameter is now optional.
672 1006
673 .. method:: socket.makefile(mode='r', buffering=None, *, encoding=None, \ 1007 .. method:: socket.makefile(mode='r', buffering=None, *, encoding=None, \
674 errors=None, newline=None) 1008 errors=None, newline=None)
675 1009
676 .. index:: single: I/O control; buffering 1010 .. index:: single: I/O control; buffering
677 1011
678 Return a :term:`file object` associated with the socket. The exact returned 1012 Return a :term:`file object` associated with the socket. The exact returned
679 type depends on the arguments given to :meth:`makefile`. These arguments are 1013 type depends on the arguments given to :meth:`makefile`. These arguments are
680 interpreted the same way as by the built-in :func:`open` function. 1014 interpreted the same way as by the built-in :func:`open` function.
681 1015
682 Closing the file object won't close the socket unless there are no remaining 1016 The socket must be in blocking mode; it can have a timeout, but the file
683 references to the socket. The socket must be in blocking mode; it can have 1017 object's internal buffer may end up in a inconsistent state if a timeout
684 a timeout, but the file object's internal buffer may end up in a inconsistent 1018 occurs.
685 state if a timeout occurs. 1019
1020 Closing the file object returned by :meth:`makefile` won't close the
1021 original socket unless all other file objects have been closed and
1022 :meth:`socket.close` has been called on the socket object.
686 1023
687 .. note:: 1024 .. note::
688 1025
689 On Windows, the file-like object created by :meth:`makefile` cannot be 1026 On Windows, the file-like object created by :meth:`makefile` cannot be
690 used where a file object with a file descriptor is expected, such as the 1027 used where a file object with a file descriptor is expected, such as the
691 stream arguments of :meth:`subprocess.Popen`. 1028 stream arguments of :meth:`subprocess.Popen`.
692 1029
693 1030
694 .. method:: socket.recv(bufsize[, flags]) 1031 .. method:: socket.recv(bufsize[, flags])
695 1032
696 Receive data from the socket. The return value is a bytes object representin g the 1033 Receive data from the socket. The return value is a bytes object representin g the
697 data received. The maximum amount of data to be received at once is specifie d 1034 data received. The maximum amount of data to be received at once is specifie d
698 by *bufsize*. See the Unix manual page :manpage:`recv(2)` for the meaning of 1035 by *bufsize*. See the Unix manual page :manpage:`recv(2)` for the meaning of
699 the optional argument *flags*; it defaults to zero. 1036 the optional argument *flags*; it defaults to zero.
700 1037
701 .. note:: 1038 .. note::
702 1039
703 For best match with hardware and network realities, the value of *bufsize * 1040 For best match with hardware and network realities, the value of *bufsize *
704 should be a relatively small power of 2, for example, 4096. 1041 should be a relatively small power of 2, for example, 4096.
1042
1043 .. versionchanged:: 3.5
1044 If the system call is interrupted and the signal handler does not raise
1045 an exception, the method now retries the system call instead of raising
1046 an :exc:`InterruptedError` exception (see :pep:`475` for the rationale).
705 1047
706 1048
707 .. method:: socket.recvfrom(bufsize[, flags]) 1049 .. method:: socket.recvfrom(bufsize[, flags])
708 1050
709 Receive data from the socket. The return value is a pair ``(bytes, address)` ` 1051 Receive data from the socket. The return value is a pair ``(bytes, address)` `
710 where *bytes* is a bytes object representing the data received and *address* is the 1052 where *bytes* is a bytes object representing the data received and *address* is the
711 address of the socket sending the data. See the Unix manual page 1053 address of the socket sending the data. See the Unix manual page
712 :manpage:`recv(2)` for the meaning of the optional argument *flags*; it defau lts 1054 :manpage:`recv(2)` for the meaning of the optional argument *flags*; it defau lts
713 to zero. (The format of *address* depends on the address family --- see above .) 1055 to zero. (The format of *address* depends on the address family --- see above .)
1056
1057 .. versionchanged:: 3.5
1058 If the system call is interrupted and the signal handler does not raise
1059 an exception, the method now retries the system call instead of raising
1060 an :exc:`InterruptedError` exception (see :pep:`475` for the rationale).
1061
1062
1063 .. method:: socket.recvmsg(bufsize[, ancbufsize[, flags]])
1064
1065 Receive normal data (up to *bufsize* bytes) and ancillary data from
1066 the socket. The *ancbufsize* argument sets the size in bytes of
1067 the internal buffer used to receive the ancillary data; it defaults
1068 to 0, meaning that no ancillary data will be received. Appropriate
1069 buffer sizes for ancillary data can be calculated using
1070 :func:`CMSG_SPACE` or :func:`CMSG_LEN`, and items which do not fit
1071 into the buffer might be truncated or discarded. The *flags*
1072 argument defaults to 0 and has the same meaning as for
1073 :meth:`recv`.
1074
1075 The return value is a 4-tuple: ``(data, ancdata, msg_flags,
1076 address)``. The *data* item is a :class:`bytes` object holding the
1077 non-ancillary data received. The *ancdata* item is a list of zero
1078 or more tuples ``(cmsg_level, cmsg_type, cmsg_data)`` representing
1079 the ancillary data (control messages) received: *cmsg_level* and
1080 *cmsg_type* are integers specifying the protocol level and
1081 protocol-specific type respectively, and *cmsg_data* is a
1082 :class:`bytes` object holding the associated data. The *msg_flags*
1083 item is the bitwise OR of various flags indicating conditions on
1084 the received message; see your system documentation for details.
1085 If the receiving socket is unconnected, *address* is the address of
1086 the sending socket, if available; otherwise, its value is
1087 unspecified.
1088
1089 On some systems, :meth:`sendmsg` and :meth:`recvmsg` can be used to
1090 pass file descriptors between processes over an :const:`AF_UNIX`
1091 socket. When this facility is used (it is often restricted to
1092 :const:`SOCK_STREAM` sockets), :meth:`recvmsg` will return, in its
1093 ancillary data, items of the form ``(socket.SOL_SOCKET,
1094 socket.SCM_RIGHTS, fds)``, where *fds* is a :class:`bytes` object
1095 representing the new file descriptors as a binary array of the
1096 native C :c:type:`int` type. If :meth:`recvmsg` raises an
1097 exception after the system call returns, it will first attempt to
1098 close any file descriptors received via this mechanism.
1099
1100 Some systems do not indicate the truncated length of ancillary data
1101 items which have been only partially received. If an item appears
1102 to extend beyond the end of the buffer, :meth:`recvmsg` will issue
1103 a :exc:`RuntimeWarning`, and will return the part of it which is
1104 inside the buffer provided it has not been truncated before the
1105 start of its associated data.
1106
1107 On systems which support the :const:`SCM_RIGHTS` mechanism, the
1108 following function will receive up to *maxfds* file descriptors,
1109 returning the message data and a list containing the descriptors
1110 (while ignoring unexpected conditions such as unrelated control
1111 messages being received). See also :meth:`sendmsg`. ::
1112
1113 import socket, array
1114
1115 def recv_fds(sock, msglen, maxfds):
1116 fds = array.array("i") # Array of ints
1117 msg, ancdata, flags, addr = sock.recvmsg(msglen, socket.CMSG_LEN(maxfd s * fds.itemsize))
1118 for cmsg_level, cmsg_type, cmsg_data in ancdata:
1119 if (cmsg_level == socket.SOL_SOCKET and cmsg_type == socket.SCM_RI GHTS):
1120 # Append data, ignoring any truncated integers at the end.
1121 fds.fromstring(cmsg_data[:len(cmsg_data) - (len(cmsg_data) % f ds.itemsize)])
1122 return msg, list(fds)
1123
1124 Availability: most Unix platforms, possibly others.
1125
1126 .. versionadded:: 3.3
1127
1128 .. versionchanged:: 3.5
1129 If the system call is interrupted and the signal handler does not raise
1130 an exception, the method now retries the system call instead of raising
1131 an :exc:`InterruptedError` exception (see :pep:`475` for the rationale).
1132
1133
1134 .. method:: socket.recvmsg_into(buffers[, ancbufsize[, flags]])
1135
1136 Receive normal data and ancillary data from the socket, behaving as
1137 :meth:`recvmsg` would, but scatter the non-ancillary data into a
1138 series of buffers instead of returning a new bytes object. The
1139 *buffers* argument must be an iterable of objects that export
1140 writable buffers (e.g. :class:`bytearray` objects); these will be
1141 filled with successive chunks of the non-ancillary data until it
1142 has all been written or there are no more buffers. The operating
1143 system may set a limit (:func:`~os.sysconf` value ``SC_IOV_MAX``)
1144 on the number of buffers that can be used. The *ancbufsize* and
1145 *flags* arguments have the same meaning as for :meth:`recvmsg`.
1146
1147 The return value is a 4-tuple: ``(nbytes, ancdata, msg_flags,
1148 address)``, where *nbytes* is the total number of bytes of
1149 non-ancillary data written into the buffers, and *ancdata*,
1150 *msg_flags* and *address* are the same as for :meth:`recvmsg`.
1151
1152 Example::
1153
1154 >>> import socket
1155 >>> s1, s2 = socket.socketpair()
1156 >>> b1 = bytearray(b'----')
1157 >>> b2 = bytearray(b'0123456789')
1158 >>> b3 = bytearray(b'--------------')
1159 >>> s1.send(b'Mary had a little lamb')
1160 22
1161 >>> s2.recvmsg_into([b1, memoryview(b2)[2:9], b3])
1162 (22, [], 0, None)
1163 >>> [b1, b2, b3]
1164 [bytearray(b'Mary'), bytearray(b'01 had a 9'), bytearray(b'little lamb---' )]
1165
1166 Availability: most Unix platforms, possibly others.
1167
1168 .. versionadded:: 3.3
714 1169
715 1170
716 .. method:: socket.recvfrom_into(buffer[, nbytes[, flags]]) 1171 .. method:: socket.recvfrom_into(buffer[, nbytes[, flags]])
717 1172
718 Receive data from the socket, writing it into *buffer* instead of creating a 1173 Receive data from the socket, writing it into *buffer* instead of creating a
719 new bytestring. The return value is a pair ``(nbytes, address)`` where *nbyt es* is 1174 new bytestring. The return value is a pair ``(nbytes, address)`` where *nbyt es* is
720 the number of bytes received and *address* is the address of the socket sendi ng 1175 the number of bytes received and *address* is the address of the socket sendi ng
721 the data. See the Unix manual page :manpage:`recv(2)` for the meaning of the 1176 the data. See the Unix manual page :manpage:`recv(2)` for the meaning of the
722 optional argument *flags*; it defaults to zero. (The format of *address* 1177 optional argument *flags*; it defaults to zero. (The format of *address*
723 depends on the address family --- see above.) 1178 depends on the address family --- see above.)
(...skipping 10 matching lines...) Expand all
734 1189
735 .. method:: socket.send(bytes[, flags]) 1190 .. method:: socket.send(bytes[, flags])
736 1191
737 Send data to the socket. The socket must be connected to a remote socket. T he 1192 Send data to the socket. The socket must be connected to a remote socket. T he
738 optional *flags* argument has the same meaning as for :meth:`recv` above. 1193 optional *flags* argument has the same meaning as for :meth:`recv` above.
739 Returns the number of bytes sent. Applications are responsible for checking t hat 1194 Returns the number of bytes sent. Applications are responsible for checking t hat
740 all data has been sent; if only some of the data was transmitted, the 1195 all data has been sent; if only some of the data was transmitted, the
741 application needs to attempt delivery of the remaining data. For further 1196 application needs to attempt delivery of the remaining data. For further
742 information on this topic, consult the :ref:`socket-howto`. 1197 information on this topic, consult the :ref:`socket-howto`.
743 1198
1199 .. versionchanged:: 3.5
1200 If the system call is interrupted and the signal handler does not raise
1201 an exception, the method now retries the system call instead of raising
1202 an :exc:`InterruptedError` exception (see :pep:`475` for the rationale).
1203
744 1204
745 .. method:: socket.sendall(bytes[, flags]) 1205 .. method:: socket.sendall(bytes[, flags])
746 1206
747 Send data to the socket. The socket must be connected to a remote socket. T he 1207 Send data to the socket. The socket must be connected to a remote socket. T he
748 optional *flags* argument has the same meaning as for :meth:`recv` above. 1208 optional *flags* argument has the same meaning as for :meth:`recv` above.
749 Unlike :meth:`send`, this method continues to send data from *bytes* until 1209 Unlike :meth:`send`, this method continues to send data from *bytes* until
750 either all data has been sent or an error occurs. ``None`` is returned on 1210 either all data has been sent or an error occurs. ``None`` is returned on
751 success. On error, an exception is raised, and there is no way to determine how 1211 success. On error, an exception is raised, and there is no way to determine how
752 much data, if any, was successfully sent. 1212 much data, if any, was successfully sent.
753 1213
1214 .. versionchanged:: 3.5
1215 The socket timeout is no more reset each time data is sent successfuly.
1216 The socket timeout is now the maximum total duration to send all data.
1217
1218 .. versionchanged:: 3.5
1219 If the system call is interrupted and the signal handler does not raise
1220 an exception, the method now retries the system call instead of raising
1221 an :exc:`InterruptedError` exception (see :pep:`475` for the rationale).
1222
754 1223
755 .. method:: socket.sendto(bytes, address) 1224 .. method:: socket.sendto(bytes, address)
756 socket.sendto(bytes, flags, address) 1225 socket.sendto(bytes, flags, address)
757 1226
758 Send data to the socket. The socket should not be connected to a remote sock et, 1227 Send data to the socket. The socket should not be connected to a remote sock et,
759 since the destination socket is specified by *address*. The optional *flags* 1228 since the destination socket is specified by *address*. The optional *flags*
760 argument has the same meaning as for :meth:`recv` above. Return the number o f 1229 argument has the same meaning as for :meth:`recv` above. Return the number o f
761 bytes sent. (The format of *address* depends on the address family --- see 1230 bytes sent. (The format of *address* depends on the address family --- see
762 above.) 1231 above.)
1232
1233 .. versionchanged:: 3.5
1234 If the system call is interrupted and the signal handler does not raise
1235 an exception, the method now retries the system call instead of raising
1236 an :exc:`InterruptedError` exception (see :pep:`475` for the rationale).
1237
1238
1239 .. method:: socket.sendmsg(buffers[, ancdata[, flags[, address]]])
1240
1241 Send normal and ancillary data to the socket, gathering the
1242 non-ancillary data from a series of buffers and concatenating it
1243 into a single message. The *buffers* argument specifies the
1244 non-ancillary data as an iterable of
1245 :term:`bytes-like objects <bytes-like object>`
1246 (e.g. :class:`bytes` objects); the operating system may set a limit
1247 (:func:`~os.sysconf` value ``SC_IOV_MAX``) on the number of buffers
1248 that can be used. The *ancdata* argument specifies the ancillary
1249 data (control messages) as an iterable of zero or more tuples
1250 ``(cmsg_level, cmsg_type, cmsg_data)``, where *cmsg_level* and
1251 *cmsg_type* are integers specifying the protocol level and
1252 protocol-specific type respectively, and *cmsg_data* is a
1253 bytes-like object holding the associated data. Note that
1254 some systems (in particular, systems without :func:`CMSG_SPACE`)
1255 might support sending only one control message per call. The
1256 *flags* argument defaults to 0 and has the same meaning as for
1257 :meth:`send`. If *address* is supplied and not ``None``, it sets a
1258 destination address for the message. The return value is the
1259 number of bytes of non-ancillary data sent.
1260
1261 The following function sends the list of file descriptors *fds*
1262 over an :const:`AF_UNIX` socket, on systems which support the
1263 :const:`SCM_RIGHTS` mechanism. See also :meth:`recvmsg`. ::
1264
1265 import socket, array
1266
1267 def send_fds(sock, msg, fds):
1268 return sock.sendmsg([msg], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, arr ay.array("i", fds))])
1269
1270 Availability: most Unix platforms, possibly others.
1271
1272 .. versionadded:: 3.3
1273
1274 .. versionchanged:: 3.5
1275 If the system call is interrupted and the signal handler does not raise
1276 an exception, the method now retries the system call instead of raising
1277 an :exc:`InterruptedError` exception (see :pep:`475` for the rationale).
1278
1279 .. method:: socket.sendfile(file, offset=0, count=None)
1280
1281 Send a file until EOF is reached by using high-performance
1282 :mod:`os.sendfile` and return the total number of bytes which were sent.
1283 *file* must be a regular file object opened in binary mode. If
1284 :mod:`os.sendfile` is not available (e.g. Windows) or *file* is not a
1285 regular file :meth:`send` will be used instead. *offset* tells from where to
1286 start reading the file. If specified, *count* is the total number of bytes
1287 to transmit as opposed to sending the file until EOF is reached. File
1288 position is updated on return or also in case of error in which case
1289 :meth:`file.tell() <io.IOBase.tell>` can be used to figure out the number of
1290 bytes which were sent. The socket must be of :const:`SOCK_STREAM` type. Non-
1291 blocking sockets are not supported.
1292
1293 .. versionadded:: 3.5
1294
1295 .. method:: socket.set_inheritable(inheritable)
1296
1297 Set the :ref:`inheritable flag <fd_inheritance>` of the socket's file
1298 descriptor or socket's handle.
1299
1300 .. versionadded:: 3.4
763 1301
764 1302
765 .. method:: socket.setblocking(flag) 1303 .. method:: socket.setblocking(flag)
766 1304
767 Set blocking or non-blocking mode of the socket: if *flag* is false, the 1305 Set blocking or non-blocking mode of the socket: if *flag* is false, the
768 socket is set to non-blocking, else to blocking mode. 1306 socket is set to non-blocking, else to blocking mode.
769 1307
770 This method is a shorthand for certain :meth:`~socket.settimeout` calls: 1308 This method is a shorthand for certain :meth:`~socket.settimeout` calls:
771 1309
772 * ``sock.setblocking(True)`` is equivalent to ``sock.settimeout(None)`` 1310 * ``sock.setblocking(True)`` is equivalent to ``sock.settimeout(None)``
(...skipping 12 matching lines...) Expand all
785 1323
786 For further information, please consult the :ref:`notes on socket timeouts <s ocket-timeouts>`. 1324 For further information, please consult the :ref:`notes on socket timeouts <s ocket-timeouts>`.
787 1325
788 1326
789 .. method:: socket.setsockopt(level, optname, value) 1327 .. method:: socket.setsockopt(level, optname, value)
790 1328
791 .. index:: module: struct 1329 .. index:: module: struct
792 1330
793 Set the value of the given socket option (see the Unix manual page 1331 Set the value of the given socket option (see the Unix manual page
794 :manpage:`setsockopt(2)`). The needed symbolic constants are defined in the 1332 :manpage:`setsockopt(2)`). The needed symbolic constants are defined in the
795 :mod:`socket` module (:const:`SO_\*` etc.). The value can be an integer or a 1333 :mod:`socket` module (:const:`SO_\*` etc.). The value can be an integer or
796 bytes object representing a buffer. In the latter case it is up to the calle r to 1334 a :term:`bytes-like object` representing a buffer. In the latter case it is
1335 up to the caller to
797 ensure that the bytestring contains the proper bits (see the optional built-i n 1336 ensure that the bytestring contains the proper bits (see the optional built-i n
798 module :mod:`struct` for a way to encode C structures as bytestrings). 1337 module :mod:`struct` for a way to encode C structures as bytestrings).
1338
1339 .. versionchanged: 3.5
1340 Writable :term:`bytes-like object` is now accepted.
799 1341
800 1342
801 .. method:: socket.shutdown(how) 1343 .. method:: socket.shutdown(how)
802 1344
803 Shut down one or both halves of the connection. If *how* is :const:`SHUT_RD` , 1345 Shut down one or both halves of the connection. If *how* is :const:`SHUT_RD` ,
804 further receives are disallowed. If *how* is :const:`SHUT_WR`, further sends 1346 further receives are disallowed. If *how* is :const:`SHUT_WR`, further sends
805 are disallowed. If *how* is :const:`SHUT_RDWR`, further sends and receives a re 1347 are disallowed. If *how* is :const:`SHUT_RDWR`, further sends and receives a re
806 disallowed. Depending on the platform, shutting down one half of the connect ion 1348 disallowed.
807 can also close the opposite half (e.g. on Mac OS X, ``shutdown(SHUT_WR)`` doe s 1349
808 not allow further reads on the other end of the connection). 1350
1351 .. method:: socket.share(process_id)
1352
1353 Duplicate a socket and prepare it for sharing with a target process. The
1354 target process must be provided with *process_id*. The resulting bytes objec t
1355 can then be passed to the target process using some form of interprocess
1356 communication and the socket can be recreated there using :func:`fromshare`.
1357 Once this method has been called, it is safe to close the socket since
1358 the operating system has already duplicated it for the target process.
1359
1360 Availability: Windows.
1361
1362 .. versionadded:: 3.3
1363
809 1364
810 Note that there are no methods :meth:`read` or :meth:`write`; use 1365 Note that there are no methods :meth:`read` or :meth:`write`; use
811 :meth:`~socket.recv` and :meth:`~socket.send` without *flags* argument instead. 1366 :meth:`~socket.recv` and :meth:`~socket.send` without *flags* argument instead.
812 1367
813 Socket objects also have these (read-only) attributes that correspond to the 1368 Socket objects also have these (read-only) attributes that correspond to the
814 values given to the :class:`socket` constructor. 1369 values given to the :class:`socket` constructor.
815 1370
816 1371
817 .. attribute:: socket.family 1372 .. attribute:: socket.family
818 1373
(...skipping 65 matching lines...) Expand 10 before | Expand all | Expand 10 after
884 behaviour, it is recommended you manually override this setting. 1439 behaviour, it is recommended you manually override this setting.
885 1440
886 1441
887 .. _socket-example: 1442 .. _socket-example:
888 1443
889 Example 1444 Example
890 ------- 1445 -------
891 1446
892 Here are four minimal example programs using the TCP/IP protocol: a server that 1447 Here are four minimal example programs using the TCP/IP protocol: a server that
893 echoes all data that it receives back (servicing only one client), and a client 1448 echoes all data that it receives back (servicing only one client), and a client
894 using it. Note that a server must perform the sequence :func:`socket`, 1449 using it. Note that a server must perform the sequence :func:`.socket`,
895 :meth:`~socket.bind`, :meth:`~socket.listen`, :meth:`~socket.accept` (possibly 1450 :meth:`~socket.bind`, :meth:`~socket.listen`, :meth:`~socket.accept` (possibly
896 repeating the :meth:`~socket.accept` to service more than one client), while a 1451 repeating the :meth:`~socket.accept` to service more than one client), while a
897 client only needs the sequence :func:`socket`, :meth:`~socket.connect`. Also 1452 client only needs the sequence :func:`.socket`, :meth:`~socket.connect`. Also
898 note that the server does not :meth:`~socket.sendall`/:meth:`~socket.recv` on 1453 note that the server does not :meth:`~socket.sendall`/:meth:`~socket.recv` on
899 the socket it is listening on but on the new socket returned by 1454 the socket it is listening on but on the new socket returned by
900 :meth:`~socket.accept`. 1455 :meth:`~socket.accept`.
901 1456
902 The first two examples support IPv4 only. :: 1457 The first two examples support IPv4 only. ::
903 1458
904 # Echo server program 1459 # Echo server program
905 import socket 1460 import socket
906 1461
907 HOST = '' # Symbolic name meaning all available interfaces 1462 HOST = '' # Symbolic name meaning all available interfaces
(...skipping 35 matching lines...) Expand 10 before | Expand all | Expand 10 after
943 import sys 1498 import sys
944 1499
945 HOST = None # Symbolic name meaning all available interfaces 1500 HOST = None # Symbolic name meaning all available interfaces
946 PORT = 50007 # Arbitrary non-privileged port 1501 PORT = 50007 # Arbitrary non-privileged port
947 s = None 1502 s = None
948 for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, 1503 for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC,
949 socket.SOCK_STREAM, 0, socket.AI_PASSIVE): 1504 socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
950 af, socktype, proto, canonname, sa = res 1505 af, socktype, proto, canonname, sa = res
951 try: 1506 try:
952 s = socket.socket(af, socktype, proto) 1507 s = socket.socket(af, socktype, proto)
953 except socket.error as msg: 1508 except OSError as msg:
954 s = None 1509 s = None
955 continue 1510 continue
956 try: 1511 try:
957 s.bind(sa) 1512 s.bind(sa)
958 s.listen(1) 1513 s.listen(1)
959 except socket.error as msg: 1514 except OSError as msg:
960 s.close() 1515 s.close()
961 s = None 1516 s = None
962 continue 1517 continue
963 break 1518 break
964 if s is None: 1519 if s is None:
965 print('could not open socket') 1520 print('could not open socket')
966 sys.exit(1) 1521 sys.exit(1)
967 conn, addr = s.accept() 1522 conn, addr = s.accept()
968 print('Connected by', addr) 1523 print('Connected by', addr)
969 while True: 1524 while True:
970 data = conn.recv(1024) 1525 data = conn.recv(1024)
971 if not data: break 1526 if not data: break
972 conn.send(data) 1527 conn.send(data)
973 conn.close() 1528 conn.close()
974 1529
975 :: 1530 ::
976 1531
977 # Echo client program 1532 # Echo client program
978 import socket 1533 import socket
979 import sys 1534 import sys
980 1535
981 HOST = 'daring.cwi.nl' # The remote host 1536 HOST = 'daring.cwi.nl' # The remote host
982 PORT = 50007 # The same port as used by the server 1537 PORT = 50007 # The same port as used by the server
983 s = None 1538 s = None
984 for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREA M): 1539 for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREA M):
985 af, socktype, proto, canonname, sa = res 1540 af, socktype, proto, canonname, sa = res
986 try: 1541 try:
987 s = socket.socket(af, socktype, proto) 1542 s = socket.socket(af, socktype, proto)
988 except socket.error as msg: 1543 except OSError as msg:
989 s = None 1544 s = None
990 continue 1545 continue
991 try: 1546 try:
992 s.connect(sa) 1547 s.connect(sa)
993 except socket.error as msg: 1548 except OSError as msg:
994 s.close() 1549 s.close()
995 s = None 1550 s = None
996 continue 1551 continue
997 break 1552 break
998 if s is None: 1553 if s is None:
999 print('could not open socket') 1554 print('could not open socket')
1000 sys.exit(1) 1555 sys.exit(1)
1001 s.sendall(b'Hello, world') 1556 s.sendall(b'Hello, world')
1002 data = s.recv(1024) 1557 data = s.recv(1024)
1003 s.close() 1558 s.close()
1004 print('Received', repr(data)) 1559 print('Received', repr(data))
1005 1560
1006 1561
1007 The last example shows how to write a very simple network sniffer with raw 1562 The next example shows how to write a very simple network sniffer with raw
1008 sockets on Windows. The example requires administrator privileges to modify 1563 sockets on Windows. The example requires administrator privileges to modify
1009 the interface:: 1564 the interface::
1010 1565
1011 import socket 1566 import socket
1012 1567
1013 # the public network interface 1568 # the public network interface
1014 HOST = socket.gethostbyname(socket.gethostname()) 1569 HOST = socket.gethostbyname(socket.gethostname())
1015 1570
1016 # create a raw socket and bind it to the public interface 1571 # create a raw socket and bind it to the public interface
1017 s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP) 1572 s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
1018 s.bind((HOST, 0)) 1573 s.bind((HOST, 0))
1019 1574
1020 # Include IP headers 1575 # Include IP headers
1021 s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) 1576 s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
1022 1577
1023 # receive all packages 1578 # receive all packages
1024 s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON) 1579 s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
1025 1580
1026 # receive a package 1581 # receive a package
1027 print(s.recvfrom(65565)) 1582 print(s.recvfrom(65565))
1028 1583
1029 # disabled promiscuous mode 1584 # disabled promiscuous mode
1030 s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF) 1585 s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)
1031 1586
1587 The last example shows how to use the socket interface to communicate to a CAN
1588 network using the raw socket protocol. To use CAN with the broadcast
1589 manager protocol instead, open a socket with::
1590
1591 socket.socket(socket.AF_CAN, socket.SOCK_DGRAM, socket.CAN_BCM)
1592
1593 After binding (:const:`CAN_RAW`) or connecting (:const:`CAN_BCM`) the socket, yo u
1594 can use the :meth:`socket.send`, and the :meth:`socket.recv` operations (and
1595 their counterparts) on the socket object as usual.
1596
1597 This example might require special privileges::
1598
1599 import socket
1600 import struct
1601
1602
1603 # CAN frame packing/unpacking (see 'struct can_frame' in <linux/can.h>)
1604
1605 can_frame_fmt = "=IB3x8s"
1606 can_frame_size = struct.calcsize(can_frame_fmt)
1607
1608 def build_can_frame(can_id, data):
1609 can_dlc = len(data)
1610 data = data.ljust(8, b'\x00')
1611 return struct.pack(can_frame_fmt, can_id, can_dlc, data)
1612
1613 def dissect_can_frame(frame):
1614 can_id, can_dlc, data = struct.unpack(can_frame_fmt, frame)
1615 return (can_id, can_dlc, data[:can_dlc])
1616
1617
1618 # create a raw socket and bind it to the 'vcan0' interface
1619 s = socket.socket(socket.AF_CAN, socket.SOCK_RAW, socket.CAN_RAW)
1620 s.bind(('vcan0',))
1621
1622 while True:
1623 cf, addr = s.recvfrom(can_frame_size)
1624
1625 print('Received: can_id=%x, can_dlc=%x, data=%s' % dissect_can_frame(cf))
1626
1627 try:
1628 s.send(cf)
1629 except OSError:
1630 print('Error sending CAN frame')
1631
1632 try:
1633 s.send(build_can_frame(0x01, b'\x01\x02\x03'))
1634 except OSError:
1635 print('Error sending CAN frame')
1032 1636
1033 Running an example several times with too small delay between executions, could 1637 Running an example several times with too small delay between executions, could
1034 lead to this error:: 1638 lead to this error::
1035 1639
1036 socket.error: [Errno 98] Address already in use 1640 OSError: [Errno 98] Address already in use
1037 1641
1038 This is because the previous execution has left the socket in a ``TIME_WAIT`` 1642 This is because the previous execution has left the socket in a ``TIME_WAIT``
1039 state, and can't be immediately reused. 1643 state, and can't be immediately reused.
1040 1644
1041 There is a :mod:`socket` flag to set, in order to prevent this, 1645 There is a :mod:`socket` flag to set, in order to prevent this,
1042 :data:`socket.SO_REUSEADDR`:: 1646 :data:`socket.SO_REUSEADDR`::
1043 1647
1044 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 1648 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1045 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 1649 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1046 s.bind((HOST, PORT)) 1650 s.bind((HOST, PORT))
(...skipping 10 matching lines...) Expand all
1057 1661
1058 - *An Advanced 4.3BSD Interprocess Communication Tutorial*, by Samuel J. Lef fler et 1662 - *An Advanced 4.3BSD Interprocess Communication Tutorial*, by Samuel J. Lef fler et
1059 al, 1663 al,
1060 1664
1061 both in the UNIX Programmer's Manual, Supplementary Documents 1 (sections 1665 both in the UNIX Programmer's Manual, Supplementary Documents 1 (sections
1062 PS1:7 and PS1:8). The platform-specific reference material for the various 1666 PS1:7 and PS1:8). The platform-specific reference material for the various
1063 socket-related system calls are also a valuable source of information on the 1667 socket-related system calls are also a valuable source of information on the
1064 details of socket semantics. For Unix, refer to the manual pages; for Window s, 1668 details of socket semantics. For Unix, refer to the manual pages; for Window s,
1065 see the WinSock (or Winsock 2) specification. For IPv6-ready APIs, readers m ay 1669 see the WinSock (or Winsock 2) specification. For IPv6-ready APIs, readers m ay
1066 want to refer to :rfc:`3493` titled Basic Socket Interface Extensions for IPv 6. 1670 want to refer to :rfc:`3493` titled Basic Socket Interface Extensions for IPv 6.
1067
LEFTRIGHT
« no previous file | no next file » | Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Toggle Comments ('s')

RSS Feeds Recent Issues | This issue
This is Rietveld 894c83f36cb7+