blob: 931dd14d39be65ff58e6efa1fc778de4ff1d3582 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
2:mod:`socket` --- Low-level networking interface
3================================================
4
5.. module:: socket
6 :synopsis: Low-level networking interface.
7
8
9This module provides access to the BSD *socket* interface. It is available on
Skip Montanaroeb33e5a2007-08-17 12:57:41 +000010all modern Unix systems, Windows, MacOS, OS/2, and probably additional
Georg Brandl116aa622007-08-15 14:28:22 +000011platforms.
12
13.. note::
14
15 Some behavior may be platform dependent, since calls are made to the operating
16 system socket APIs.
17
18For an introduction to socket programming (in C), see the following papers: An
19Introductory 4.3BSD Interprocess Communication Tutorial, by Stuart Sechrest and
20An Advanced 4.3BSD Interprocess Communication Tutorial, by Samuel J. Leffler et
21al, both in the UNIX Programmer's Manual, Supplementary Documents 1 (sections
22PS1:7 and PS1:8). The platform-specific reference material for the various
23socket-related system calls are also a valuable source of information on the
24details of socket semantics. For Unix, refer to the manual pages; for Windows,
25see the WinSock (or Winsock 2) specification. For IPv6-ready APIs, readers may
Christian Heimes292d3512008-02-03 16:51:08 +000026want to refer to :rfc:`3493` titled Basic Socket Interface Extensions for IPv6.
Georg Brandl116aa622007-08-15 14:28:22 +000027
28.. index:: object: socket
29
30The Python interface is a straightforward transliteration of the Unix system
31call and library interface for sockets to Python's object-oriented style: the
32:func:`socket` function returns a :dfn:`socket object` whose methods implement
33the various socket system calls. Parameter types are somewhat higher-level than
34in the C interface: as with :meth:`read` and :meth:`write` operations on Python
35files, buffer allocation on receive operations is automatic, and buffer length
36is implicit on send operations.
37
38Socket addresses are represented as follows: A single string is used for the
39:const:`AF_UNIX` address family. A pair ``(host, port)`` is used for the
40:const:`AF_INET` address family, where *host* is a string representing either a
41hostname in Internet domain notation like ``'daring.cwi.nl'`` or an IPv4 address
42like ``'100.50.200.5'``, and *port* is an integral port number. For
43:const:`AF_INET6` address family, a four-tuple ``(host, port, flowinfo,
44scopeid)`` is used, where *flowinfo* and *scopeid* represents ``sin6_flowinfo``
45and ``sin6_scope_id`` member in :const:`struct sockaddr_in6` in C. For
46:mod:`socket` module methods, *flowinfo* and *scopeid* can be omitted just for
47backward compatibility. Note, however, omission of *scopeid* can cause problems
48in manipulating scoped IPv6 addresses. Other address families are currently not
49supported. The address format required by a particular socket object is
50automatically selected based on the address family specified when the socket
51object was created.
52
53For IPv4 addresses, two special forms are accepted instead of a host address:
54the empty string represents :const:`INADDR_ANY`, and the string
55``'<broadcast>'`` represents :const:`INADDR_BROADCAST`. The behavior is not
56available for IPv6 for backward compatibility, therefore, you may want to avoid
57these if you intend to support IPv6 with your Python programs.
58
59If you use a hostname in the *host* portion of IPv4/v6 socket address, the
60program may show a nondeterministic behavior, as Python uses the first address
61returned from the DNS resolution. The socket address will be resolved
62differently into an actual IPv4/v6 address, depending on the results from DNS
63resolution and/or the host configuration. For deterministic behavior use a
64numeric address in *host* portion.
65
Georg Brandl55ac8f02007-09-01 13:51:09 +000066AF_NETLINK sockets are represented as pairs ``pid, groups``.
Georg Brandl116aa622007-08-15 14:28:22 +000067
Christian Heimes043d6f62008-01-07 17:19:16 +000068
69Linux-only support for TIPC is also available using the :const:`AF_TIPC`
70address family. TIPC is an open, non-IP based networked protocol designed
71for use in clustered computer environments. Addresses are represented by a
72tuple, and the fields depend on the address type. The general tuple form is
73``(addr_type, v1, v2, v3 [, scope])``, where:
74
Georg Brandlc62efa82010-07-11 10:41:07 +000075- *addr_type* is one of TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME, or
76 TIPC_ADDR_ID.
77- *scope* is one of TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, and
78 TIPC_NODE_SCOPE.
79- If *addr_type* is TIPC_ADDR_NAME, then *v1* is the server type, *v2* is
80 the port identifier, and *v3* should be 0.
Christian Heimes043d6f62008-01-07 17:19:16 +000081
Georg Brandlc62efa82010-07-11 10:41:07 +000082 If *addr_type* is TIPC_ADDR_NAMESEQ, then *v1* is the server type, *v2*
83 is the lower port number, and *v3* is the upper port number.
Christian Heimes043d6f62008-01-07 17:19:16 +000084
Georg Brandlc62efa82010-07-11 10:41:07 +000085 If *addr_type* is TIPC_ADDR_ID, then *v1* is the node, *v2* is the
86 reference, and *v3* should be set to 0.
87
88 If *addr_type* is TIPC_ADDR_ID, then *v1* is the node, *v2* is the
89 reference, and *v3* should be set to 0.
Christian Heimes043d6f62008-01-07 17:19:16 +000090
91
Georg Brandl116aa622007-08-15 14:28:22 +000092All errors raise exceptions. The normal exceptions for invalid argument types
93and out-of-memory conditions can be raised; errors related to socket or address
94semantics raise the error :exc:`socket.error`.
95
Georg Brandl6c8583f2010-05-19 21:22:58 +000096Non-blocking mode is supported through :meth:`~socket.setblocking`. A
97generalization of this based on timeouts is supported through
98:meth:`~socket.settimeout`.
Georg Brandl116aa622007-08-15 14:28:22 +000099
100The module :mod:`socket` exports the following constants and functions:
101
102
103.. exception:: error
104
105 .. index:: module: errno
106
107 This exception is raised for socket-related errors. The accompanying value is
108 either a string telling what went wrong or a pair ``(errno, string)``
109 representing an error returned by a system call, similar to the value
110 accompanying :exc:`os.error`. See the module :mod:`errno`, which contains names
111 for the error codes defined by the underlying operating system.
112
113
114.. exception:: herror
115
116 This exception is raised for address-related errors, i.e. for functions that use
117 *h_errno* in the C API, including :func:`gethostbyname_ex` and
118 :func:`gethostbyaddr`.
119
120 The accompanying value is a pair ``(h_errno, string)`` representing an error
121 returned by a library call. *string* represents the description of *h_errno*, as
122 returned by the :cfunc:`hstrerror` C function.
123
124
125.. exception:: gaierror
126
127 This exception is raised for address-related errors, for :func:`getaddrinfo` and
128 :func:`getnameinfo`. The accompanying value is a pair ``(error, string)``
129 representing an error returned by a library call. *string* represents the
130 description of *error*, as returned by the :cfunc:`gai_strerror` C function. The
131 *error* value will match one of the :const:`EAI_\*` constants defined in this
132 module.
133
134
135.. exception:: timeout
136
137 This exception is raised when a timeout occurs on a socket which has had
138 timeouts enabled via a prior call to :meth:`settimeout`. The accompanying value
139 is a string whose value is currently always "timed out".
140
Georg Brandl116aa622007-08-15 14:28:22 +0000141
142.. data:: AF_UNIX
143 AF_INET
144 AF_INET6
145
146 These constants represent the address (and protocol) families, used for the
147 first argument to :func:`socket`. If the :const:`AF_UNIX` constant is not
148 defined then this protocol is unsupported.
149
150
151.. data:: SOCK_STREAM
152 SOCK_DGRAM
153 SOCK_RAW
154 SOCK_RDM
155 SOCK_SEQPACKET
156
157 These constants represent the socket types, used for the second argument to
158 :func:`socket`. (Only :const:`SOCK_STREAM` and :const:`SOCK_DGRAM` appear to be
159 generally useful.)
160
161
162.. data:: SO_*
163 SOMAXCONN
164 MSG_*
165 SOL_*
166 IPPROTO_*
167 IPPORT_*
168 INADDR_*
169 IP_*
170 IPV6_*
171 EAI_*
172 AI_*
173 NI_*
174 TCP_*
175
176 Many constants of these forms, documented in the Unix documentation on sockets
177 and/or the IP protocol, are also defined in the socket module. They are
178 generally used in arguments to the :meth:`setsockopt` and :meth:`getsockopt`
179 methods of socket objects. In most cases, only those symbols that are defined
180 in the Unix header files are defined; for a few symbols, default values are
181 provided.
182
Christian Heimesfaf2f632008-01-06 16:59:19 +0000183.. data:: SIO_*
184 RCVALL_*
Georg Brandl48310cd2009-01-03 21:18:54 +0000185
Christian Heimesfaf2f632008-01-06 16:59:19 +0000186 Constants for Windows' WSAIoctl(). The constants are used as arguments to the
187 :meth:`ioctl` method of socket objects.
Georg Brandl48310cd2009-01-03 21:18:54 +0000188
Georg Brandl116aa622007-08-15 14:28:22 +0000189
Christian Heimes043d6f62008-01-07 17:19:16 +0000190.. data:: TIPC_*
191
192 TIPC related constants, matching the ones exported by the C socket API. See
193 the TIPC documentation for more information.
194
195
Georg Brandl116aa622007-08-15 14:28:22 +0000196.. data:: has_ipv6
197
198 This constant contains a boolean value which indicates if IPv6 is supported on
199 this platform.
200
Georg Brandl116aa622007-08-15 14:28:22 +0000201
202.. function:: create_connection(address[, timeout])
203
Georg Brandlf78e02b2008-06-10 17:40:04 +0000204 Convenience function. Connect to *address* (a 2-tuple ``(host, port)``),
205 and return the socket object. Passing the optional *timeout* parameter will
206 set the timeout on the socket instance before attempting to connect. If no
207 *timeout* is supplied, the global default timeout setting returned by
208 :func:`getdefaulttimeout` is used.
Georg Brandl116aa622007-08-15 14:28:22 +0000209
Georg Brandl116aa622007-08-15 14:28:22 +0000210
Antoine Pitrou3f6b2d02010-05-31 17:06:44 +0000211.. function:: getaddrinfo(host, port, family=0, socktype=0, proto=0, flags=0)
Georg Brandl116aa622007-08-15 14:28:22 +0000212
Antoine Pitrou3f6b2d02010-05-31 17:06:44 +0000213 Translate the *host*/*port* argument into a sequence of 5-tuples that contain
214 all the necessary arguments for creating a socket connected to that service.
215 *host* is a domain name, a string representation of an IPv4/v6 address
216 or ``None``. *port* is a string service name such as ``'http'``, a numeric
217 port number or ``None``. By passing ``None`` as the value of *host*
218 and *port*, you can pass ``NULL`` to the underlying C API.
Georg Brandl116aa622007-08-15 14:28:22 +0000219
Antoine Pitrou3f6b2d02010-05-31 17:06:44 +0000220 The *family*, *socktype* and *proto* arguments can be optionally specified
221 in order to narrow the list of addresses returned. Passing zero as a
222 value for each of these arguments selects the full range of results.
223 The *flags* argument can be one or several of the ``AI_*`` constants,
224 and will influence how results are computed and returned.
225 For example, :const:`AI_NUMERICHOST` will disable domain name resolution
226 and will raise an error if *host* is a domain name.
227
228 The function returns a list of 5-tuples with the following structure:
Georg Brandl116aa622007-08-15 14:28:22 +0000229
230 ``(family, socktype, proto, canonname, sockaddr)``
231
Antoine Pitrou3f6b2d02010-05-31 17:06:44 +0000232 In these tuples, *family*, *socktype*, *proto* are all integers and are
233 meant to be passed to the :func:`socket` function. *canonname* will be
234 a string representing the canonical name of the *host* if
235 :const:`AI_CANONNAME` is part of the *flags* argument; else *canonname*
236 will be empty. *sockaddr* is a tuple describing a socket address, whose
237 format depends on the returned *family* (a ``(address, port)`` 2-tuple for
238 :const:`AF_INET`, a ``(address, port, flow info, scope id)`` 4-tuple for
239 :const:`AF_INET6`), and is meant to be passed to the :meth:`socket.connect`
240 method.
Georg Brandl116aa622007-08-15 14:28:22 +0000241
Antoine Pitrou3f6b2d02010-05-31 17:06:44 +0000242 The following example fetches address information for a hypothetical TCP
243 connection to ``www.python.org`` on port 80 (results may differ on your
244 system if IPv6 isn't enabled)::
245
246 >>> socket.getaddrinfo("www.python.org", 80, 0, 0, socket.SOL_TCP)
247 [(2, 1, 6, '', ('82.94.164.162', 80)),
248 (10, 1, 6, '', ('2001:888:2000:d::a2', 80, 0, 0))]
Georg Brandl116aa622007-08-15 14:28:22 +0000249
250.. function:: getfqdn([name])
251
252 Return a fully qualified domain name for *name*. If *name* is omitted or empty,
253 it is interpreted as the local host. To find the fully qualified name, the
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +0000254 hostname returned by :func:`gethostbyaddr` is checked, followed by aliases for the
Georg Brandl116aa622007-08-15 14:28:22 +0000255 host, if available. The first name which includes a period is selected. In
256 case no fully qualified domain name is available, the hostname as returned by
257 :func:`gethostname` is returned.
258
Georg Brandl116aa622007-08-15 14:28:22 +0000259
260.. function:: gethostbyname(hostname)
261
262 Translate a host name to IPv4 address format. The IPv4 address is returned as a
263 string, such as ``'100.50.200.5'``. If the host name is an IPv4 address itself
264 it is returned unchanged. See :func:`gethostbyname_ex` for a more complete
265 interface. :func:`gethostbyname` does not support IPv6 name resolution, and
266 :func:`getaddrinfo` should be used instead for IPv4/v6 dual stack support.
267
268
269.. function:: gethostbyname_ex(hostname)
270
271 Translate a host name to IPv4 address format, extended interface. Return a
272 triple ``(hostname, aliaslist, ipaddrlist)`` where *hostname* is the primary
273 host name responding to the given *ip_address*, *aliaslist* is a (possibly
274 empty) list of alternative host names for the same address, and *ipaddrlist* is
275 a list of IPv4 addresses for the same interface on the same host (often but not
276 always a single address). :func:`gethostbyname_ex` does not support IPv6 name
277 resolution, and :func:`getaddrinfo` should be used instead for IPv4/v6 dual
278 stack support.
279
280
281.. function:: gethostname()
282
283 Return a string containing the hostname of the machine where the Python
Benjamin Peterson65676e42008-11-05 21:42:45 +0000284 interpreter is currently executing.
285
286 If you want to know the current machine's IP address, you may want to use
287 ``gethostbyname(gethostname())``. This operation assumes that there is a
288 valid address-to-host mapping for the host, and the assumption does not
289 always hold.
290
291 Note: :func:`gethostname` doesn't always return the fully qualified domain
292 name; use ``getfqdn()`` (see above).
Georg Brandl116aa622007-08-15 14:28:22 +0000293
294
295.. function:: gethostbyaddr(ip_address)
296
297 Return a triple ``(hostname, aliaslist, ipaddrlist)`` where *hostname* is the
298 primary host name responding to the given *ip_address*, *aliaslist* is a
299 (possibly empty) list of alternative host names for the same address, and
300 *ipaddrlist* is a list of IPv4/v6 addresses for the same interface on the same
301 host (most likely containing only a single address). To find the fully qualified
302 domain name, use the function :func:`getfqdn`. :func:`gethostbyaddr` supports
303 both IPv4 and IPv6.
304
305
306.. function:: getnameinfo(sockaddr, flags)
307
308 Translate a socket address *sockaddr* into a 2-tuple ``(host, port)``. Depending
309 on the settings of *flags*, the result can contain a fully-qualified domain name
310 or numeric address representation in *host*. Similarly, *port* can contain a
311 string port name or a numeric port number.
312
Georg Brandl116aa622007-08-15 14:28:22 +0000313
314.. function:: getprotobyname(protocolname)
315
316 Translate an Internet protocol name (for example, ``'icmp'``) to a constant
317 suitable for passing as the (optional) third argument to the :func:`socket`
318 function. This is usually only needed for sockets opened in "raw" mode
319 (:const:`SOCK_RAW`); for the normal socket modes, the correct protocol is chosen
320 automatically if the protocol is omitted or zero.
321
322
323.. function:: getservbyname(servicename[, protocolname])
324
325 Translate an Internet service name and protocol name to a port number for that
326 service. The optional protocol name, if given, should be ``'tcp'`` or
327 ``'udp'``, otherwise any protocol will match.
328
329
330.. function:: getservbyport(port[, protocolname])
331
332 Translate an Internet port number and protocol name to a service name for that
333 service. The optional protocol name, if given, should be ``'tcp'`` or
334 ``'udp'``, otherwise any protocol will match.
335
336
337.. function:: socket([family[, type[, proto]]])
338
339 Create a new socket using the given address family, socket type and protocol
340 number. The address family should be :const:`AF_INET` (the default),
341 :const:`AF_INET6` or :const:`AF_UNIX`. The socket type should be
342 :const:`SOCK_STREAM` (the default), :const:`SOCK_DGRAM` or perhaps one of the
343 other ``SOCK_`` constants. The protocol number is usually zero and may be
344 omitted in that case.
345
346
Georg Brandl116aa622007-08-15 14:28:22 +0000347.. function:: socketpair([family[, type[, proto]]])
348
349 Build a pair of connected socket objects using the given address family, socket
350 type, and protocol number. Address family, socket type, and protocol number are
351 as for the :func:`socket` function above. The default family is :const:`AF_UNIX`
352 if defined on the platform; otherwise, the default is :const:`AF_INET`.
353 Availability: Unix.
354
Georg Brandl116aa622007-08-15 14:28:22 +0000355
356.. function:: fromfd(fd, family, type[, proto])
357
358 Duplicate the file descriptor *fd* (an integer as returned by a file object's
359 :meth:`fileno` method) and build a socket object from the result. Address
360 family, socket type and protocol number are as for the :func:`socket` function
361 above. The file descriptor should refer to a socket, but this is not checked ---
362 subsequent operations on the object may fail if the file descriptor is invalid.
363 This function is rarely needed, but can be used to get or set socket options on
364 a socket passed to a program as standard input or output (such as a server
365 started by the Unix inet daemon). The socket is assumed to be in blocking mode.
366 Availability: Unix.
367
368
369.. function:: ntohl(x)
370
371 Convert 32-bit positive integers from network to host byte order. On machines
372 where the host byte order is the same as network byte order, this is a no-op;
373 otherwise, it performs a 4-byte swap operation.
374
375
376.. function:: ntohs(x)
377
378 Convert 16-bit positive integers from network to host byte order. On machines
379 where the host byte order is the same as network byte order, this is a no-op;
380 otherwise, it performs a 2-byte swap operation.
381
382
383.. function:: htonl(x)
384
385 Convert 32-bit positive integers from host to network byte order. On machines
386 where the host byte order is the same as network byte order, this is a no-op;
387 otherwise, it performs a 4-byte swap operation.
388
389
390.. function:: htons(x)
391
392 Convert 16-bit positive integers from host to network byte order. On machines
393 where the host byte order is the same as network byte order, this is a no-op;
394 otherwise, it performs a 2-byte swap operation.
395
396
397.. function:: inet_aton(ip_string)
398
399 Convert an IPv4 address from dotted-quad string format (for example,
Georg Brandl42b2f2e2008-08-14 11:50:32 +0000400 '123.45.67.89') to 32-bit packed binary format, as a bytes object four characters in
Georg Brandl116aa622007-08-15 14:28:22 +0000401 length. This is useful when conversing with a program that uses the standard C
402 library and needs objects of type :ctype:`struct in_addr`, which is the C type
403 for the 32-bit packed binary this function returns.
404
Georg Brandlf5123ef2009-06-04 10:28:36 +0000405 :func:`inet_aton` also accepts strings with less than three dots; see the
406 Unix manual page :manpage:`inet(3)` for details.
407
Georg Brandl116aa622007-08-15 14:28:22 +0000408 If the IPv4 address string passed to this function is invalid,
409 :exc:`socket.error` will be raised. Note that exactly what is valid depends on
410 the underlying C implementation of :cfunc:`inet_aton`.
411
Georg Brandl5f259722009-05-04 20:50:30 +0000412 :func:`inet_aton` does not support IPv6, and :func:`inet_pton` should be used
Georg Brandl116aa622007-08-15 14:28:22 +0000413 instead for IPv4/v6 dual stack support.
414
415
416.. function:: inet_ntoa(packed_ip)
417
Georg Brandl42b2f2e2008-08-14 11:50:32 +0000418 Convert a 32-bit packed IPv4 address (a bytes object four characters in
419 length) to its standard dotted-quad string representation (for example,
420 '123.45.67.89'). This is useful when conversing with a program that uses the
421 standard C library and needs objects of type :ctype:`struct in_addr`, which
422 is the C type for the 32-bit packed binary data this function takes as an
423 argument.
Georg Brandl116aa622007-08-15 14:28:22 +0000424
Georg Brandl42b2f2e2008-08-14 11:50:32 +0000425 If the byte sequence passed to this function is not exactly 4 bytes in
426 length, :exc:`socket.error` will be raised. :func:`inet_ntoa` does not
Georg Brandl5f259722009-05-04 20:50:30 +0000427 support IPv6, and :func:`inet_ntop` should be used instead for IPv4/v6 dual
Georg Brandl42b2f2e2008-08-14 11:50:32 +0000428 stack support.
Georg Brandl116aa622007-08-15 14:28:22 +0000429
430
431.. function:: inet_pton(address_family, ip_string)
432
Georg Brandl42b2f2e2008-08-14 11:50:32 +0000433 Convert an IP address from its family-specific string format to a packed,
434 binary format. :func:`inet_pton` is useful when a library or network protocol
435 calls for an object of type :ctype:`struct in_addr` (similar to
436 :func:`inet_aton`) or :ctype:`struct in6_addr`.
Georg Brandl116aa622007-08-15 14:28:22 +0000437
438 Supported values for *address_family* are currently :const:`AF_INET` and
439 :const:`AF_INET6`. If the IP address string *ip_string* is invalid,
440 :exc:`socket.error` will be raised. Note that exactly what is valid depends on
441 both the value of *address_family* and the underlying implementation of
442 :cfunc:`inet_pton`.
443
444 Availability: Unix (maybe not all platforms).
445
Georg Brandl116aa622007-08-15 14:28:22 +0000446
447.. function:: inet_ntop(address_family, packed_ip)
448
Georg Brandl42b2f2e2008-08-14 11:50:32 +0000449 Convert a packed IP address (a bytes object of some number of characters) to its
Georg Brandl116aa622007-08-15 14:28:22 +0000450 standard, family-specific string representation (for example, ``'7.10.0.5'`` or
Georg Brandl42b2f2e2008-08-14 11:50:32 +0000451 ``'5aef:2b::8'``). :func:`inet_ntop` is useful when a library or network protocol
Georg Brandl116aa622007-08-15 14:28:22 +0000452 returns an object of type :ctype:`struct in_addr` (similar to :func:`inet_ntoa`)
453 or :ctype:`struct in6_addr`.
454
455 Supported values for *address_family* are currently :const:`AF_INET` and
456 :const:`AF_INET6`. If the string *packed_ip* is not the correct length for the
457 specified address family, :exc:`ValueError` will be raised. A
458 :exc:`socket.error` is raised for errors from the call to :func:`inet_ntop`.
459
460 Availability: Unix (maybe not all platforms).
461
Georg Brandl116aa622007-08-15 14:28:22 +0000462
463.. function:: getdefaulttimeout()
464
465 Return the default timeout in floating seconds for new socket objects. A value
466 of ``None`` indicates that new socket objects have no timeout. When the socket
467 module is first imported, the default is ``None``.
468
Georg Brandl116aa622007-08-15 14:28:22 +0000469
470.. function:: setdefaulttimeout(timeout)
471
472 Set the default timeout in floating seconds for new socket objects. A value of
473 ``None`` indicates that new socket objects have no timeout. When the socket
474 module is first imported, the default is ``None``.
475
Georg Brandl116aa622007-08-15 14:28:22 +0000476
477.. data:: SocketType
478
479 This is a Python type object that represents the socket object type. It is the
480 same as ``type(socket(...))``.
481
482
483.. seealso::
484
Alexandre Vassalottice261952008-05-12 02:31:37 +0000485 Module :mod:`socketserver`
Georg Brandl116aa622007-08-15 14:28:22 +0000486 Classes that simplify writing network servers.
487
488
489.. _socket-objects:
490
491Socket Objects
492--------------
493
494Socket objects have the following methods. Except for :meth:`makefile` these
495correspond to Unix system calls applicable to sockets.
496
497
498.. method:: socket.accept()
499
500 Accept a connection. The socket must be bound to an address and listening for
501 connections. The return value is a pair ``(conn, address)`` where *conn* is a
502 *new* socket object usable to send and receive data on the connection, and
503 *address* is the address bound to the socket on the other end of the connection.
504
505
506.. method:: socket.bind(address)
507
508 Bind the socket to *address*. The socket must not already be bound. (The format
509 of *address* depends on the address family --- see above.)
510
Georg Brandl116aa622007-08-15 14:28:22 +0000511
512.. method:: socket.close()
513
514 Close the socket. All future operations on the socket object will fail. The
515 remote end will receive no more data (after queued data is flushed). Sockets are
516 automatically closed when they are garbage-collected.
517
518
519.. method:: socket.connect(address)
520
521 Connect to a remote socket at *address*. (The format of *address* depends on the
522 address family --- see above.)
523
Georg Brandl116aa622007-08-15 14:28:22 +0000524
525.. method:: socket.connect_ex(address)
526
527 Like ``connect(address)``, but return an error indicator instead of raising an
528 exception for errors returned by the C-level :cfunc:`connect` call (other
529 problems, such as "host not found," can still raise exceptions). The error
530 indicator is ``0`` if the operation succeeded, otherwise the value of the
531 :cdata:`errno` variable. This is useful to support, for example, asynchronous
532 connects.
533
Georg Brandl116aa622007-08-15 14:28:22 +0000534
535.. method:: socket.fileno()
536
537 Return the socket's file descriptor (a small integer). This is useful with
538 :func:`select.select`.
539
540 Under Windows the small integer returned by this method cannot be used where a
541 file descriptor can be used (such as :func:`os.fdopen`). Unix does not have
542 this limitation.
543
544
545.. method:: socket.getpeername()
546
547 Return the remote address to which the socket is connected. This is useful to
548 find out the port number of a remote IPv4/v6 socket, for instance. (The format
549 of the address returned depends on the address family --- see above.) On some
550 systems this function is not supported.
551
552
553.. method:: socket.getsockname()
554
555 Return the socket's own address. This is useful to find out the port number of
556 an IPv4/v6 socket, for instance. (The format of the address returned depends on
557 the address family --- see above.)
558
559
560.. method:: socket.getsockopt(level, optname[, buflen])
561
562 Return the value of the given socket option (see the Unix man page
563 :manpage:`getsockopt(2)`). The needed symbolic constants (:const:`SO_\*` etc.)
564 are defined in this module. If *buflen* is absent, an integer option is assumed
565 and its integer value is returned by the function. If *buflen* is present, it
566 specifies the maximum length of the buffer used to receive the option in, and
Georg Brandl42b2f2e2008-08-14 11:50:32 +0000567 this buffer is returned as a bytes object. It is up to the caller to decode the
Georg Brandl116aa622007-08-15 14:28:22 +0000568 contents of the buffer (see the optional built-in module :mod:`struct` for a way
Georg Brandl42b2f2e2008-08-14 11:50:32 +0000569 to decode C structures encoded as byte strings).
Georg Brandl116aa622007-08-15 14:28:22 +0000570
Georg Brandl48310cd2009-01-03 21:18:54 +0000571
Christian Heimesfaf2f632008-01-06 16:59:19 +0000572.. method:: socket.ioctl(control, option)
573
Georg Brandl48310cd2009-01-03 21:18:54 +0000574 :platform: Windows
575
Christian Heimes679db4a2008-01-18 09:56:22 +0000576 The :meth:`ioctl` method is a limited interface to the WSAIoctl system
Georg Brandl6c8583f2010-05-19 21:22:58 +0000577 interface. Please refer to the `Win32 documentation
578 <http://msdn.microsoft.com/en-us/library/ms741621%28VS.85%29.aspx>`_ for more
579 information.
Georg Brandl48310cd2009-01-03 21:18:54 +0000580
Georg Brandlc5605df2009-08-13 08:26:44 +0000581 On other platforms, the generic :func:`fcntl.fcntl` and :func:`fcntl.ioctl`
582 functions may be used; they accept a socket object as their first argument.
Georg Brandl116aa622007-08-15 14:28:22 +0000583
584.. method:: socket.listen(backlog)
585
586 Listen for connections made to the socket. The *backlog* argument specifies the
587 maximum number of queued connections and should be at least 1; the maximum value
588 is system-dependent (usually 5).
589
590
Georg Brandl1e8cbe32009-10-27 20:23:20 +0000591.. method:: socket.makefile(mode='r', buffering=None, *, encoding=None, newline=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000592
593 .. index:: single: I/O control; buffering
594
Antoine Pitrou25d535e2010-09-15 11:25:11 +0000595 Return a :term:`file object` associated with the socket. The exact
Antoine Pitroufa833952010-01-04 19:55:11 +0000596 returned type depends on the arguments given to :meth:`makefile`. These
Georg Brandl1e8cbe32009-10-27 20:23:20 +0000597 arguments are interpreted the same way as by the built-in :func:`open`
598 function.
Georg Brandl116aa622007-08-15 14:28:22 +0000599
Antoine Pitrouecbf2de2010-09-15 11:16:39 +0000600 Closing the file object won't close the socket unless there are no
601 remaining references to the socket. The socket must be in blocking mode
602 (it can not have a timeout).
Antoine Pitroufa833952010-01-04 19:55:11 +0000603
Georg Brandl116aa622007-08-15 14:28:22 +0000604
605.. method:: socket.recv(bufsize[, flags])
606
Georg Brandl42b2f2e2008-08-14 11:50:32 +0000607 Receive data from the socket. The return value is a bytes object representing the
Georg Brandl116aa622007-08-15 14:28:22 +0000608 data received. The maximum amount of data to be received at once is specified
609 by *bufsize*. See the Unix manual page :manpage:`recv(2)` for the meaning of
610 the optional argument *flags*; it defaults to zero.
611
612 .. note::
613
614 For best match with hardware and network realities, the value of *bufsize*
615 should be a relatively small power of 2, for example, 4096.
616
617
618.. method:: socket.recvfrom(bufsize[, flags])
619
Georg Brandl42b2f2e2008-08-14 11:50:32 +0000620 Receive data from the socket. The return value is a pair ``(bytes, address)``
621 where *bytes* is a bytes object representing the data received and *address* is the
Georg Brandl116aa622007-08-15 14:28:22 +0000622 address of the socket sending the data. See the Unix manual page
623 :manpage:`recv(2)` for the meaning of the optional argument *flags*; it defaults
624 to zero. (The format of *address* depends on the address family --- see above.)
625
626
627.. method:: socket.recvfrom_into(buffer[, nbytes[, flags]])
628
Georg Brandl42b2f2e2008-08-14 11:50:32 +0000629 Receive data from the socket, writing it into *buffer* instead of creating a
630 new bytestring. The return value is a pair ``(nbytes, address)`` where *nbytes* is
Georg Brandl116aa622007-08-15 14:28:22 +0000631 the number of bytes received and *address* is the address of the socket sending
632 the data. See the Unix manual page :manpage:`recv(2)` for the meaning of the
633 optional argument *flags*; it defaults to zero. (The format of *address*
634 depends on the address family --- see above.)
635
Georg Brandl116aa622007-08-15 14:28:22 +0000636
637.. method:: socket.recv_into(buffer[, nbytes[, flags]])
638
639 Receive up to *nbytes* bytes from the socket, storing the data into a buffer
Georg Brandl42b2f2e2008-08-14 11:50:32 +0000640 rather than creating a new bytestring. If *nbytes* is not specified (or 0),
Georg Brandl116aa622007-08-15 14:28:22 +0000641 receive up to the size available in the given buffer. See the Unix manual page
642 :manpage:`recv(2)` for the meaning of the optional argument *flags*; it defaults
643 to zero.
644
Georg Brandl116aa622007-08-15 14:28:22 +0000645
Georg Brandl42b2f2e2008-08-14 11:50:32 +0000646.. method:: socket.send(bytes[, flags])
Georg Brandl116aa622007-08-15 14:28:22 +0000647
648 Send data to the socket. The socket must be connected to a remote socket. The
649 optional *flags* argument has the same meaning as for :meth:`recv` above.
650 Returns the number of bytes sent. Applications are responsible for checking that
651 all data has been sent; if only some of the data was transmitted, the
652 application needs to attempt delivery of the remaining data.
653
654
Georg Brandl42b2f2e2008-08-14 11:50:32 +0000655.. method:: socket.sendall(bytes[, flags])
Georg Brandl116aa622007-08-15 14:28:22 +0000656
657 Send data to the socket. The socket must be connected to a remote socket. The
658 optional *flags* argument has the same meaning as for :meth:`recv` above.
Georg Brandl42b2f2e2008-08-14 11:50:32 +0000659 Unlike :meth:`send`, this method continues to send data from *bytes* until
Georg Brandl116aa622007-08-15 14:28:22 +0000660 either all data has been sent or an error occurs. ``None`` is returned on
661 success. On error, an exception is raised, and there is no way to determine how
662 much data, if any, was successfully sent.
663
664
Georg Brandl42b2f2e2008-08-14 11:50:32 +0000665.. method:: socket.sendto(bytes[, flags], address)
Georg Brandl116aa622007-08-15 14:28:22 +0000666
667 Send data to the socket. The socket should not be connected to a remote socket,
668 since the destination socket is specified by *address*. The optional *flags*
669 argument has the same meaning as for :meth:`recv` above. Return the number of
670 bytes sent. (The format of *address* depends on the address family --- see
671 above.)
672
673
674.. method:: socket.setblocking(flag)
675
676 Set blocking or non-blocking mode of the socket: if *flag* is 0, the socket is
677 set to non-blocking, else to blocking mode. Initially all sockets are in
678 blocking mode. In non-blocking mode, if a :meth:`recv` call doesn't find any
679 data, or if a :meth:`send` call can't immediately dispose of the data, a
680 :exc:`error` exception is raised; in blocking mode, the calls block until they
Georg Brandl6c8583f2010-05-19 21:22:58 +0000681 can proceed. ``s.setblocking(0)`` is equivalent to ``s.settimeout(0.0)``;
Georg Brandl116aa622007-08-15 14:28:22 +0000682 ``s.setblocking(1)`` is equivalent to ``s.settimeout(None)``.
683
684
685.. method:: socket.settimeout(value)
686
687 Set a timeout on blocking socket operations. The *value* argument can be a
688 nonnegative float expressing seconds, or ``None``. If a float is given,
Georg Brandlc62efa82010-07-11 10:41:07 +0000689 subsequent socket operations will raise a :exc:`timeout` exception if the
Georg Brandl116aa622007-08-15 14:28:22 +0000690 timeout period *value* has elapsed before the operation has completed. Setting
691 a timeout of ``None`` disables timeouts on socket operations.
692 ``s.settimeout(0.0)`` is equivalent to ``s.setblocking(0)``;
693 ``s.settimeout(None)`` is equivalent to ``s.setblocking(1)``.
694
Georg Brandl116aa622007-08-15 14:28:22 +0000695
696.. method:: socket.gettimeout()
697
698 Return the timeout in floating seconds associated with socket operations, or
699 ``None`` if no timeout is set. This reflects the last call to
700 :meth:`setblocking` or :meth:`settimeout`.
701
Georg Brandl116aa622007-08-15 14:28:22 +0000702
703Some notes on socket blocking and timeouts: A socket object can be in one of
704three modes: blocking, non-blocking, or timeout. Sockets are always created in
Gregory P. Smith349c5952009-02-19 01:25:51 +0000705blocking mode. In blocking mode, operations block until complete or
706the system returns an error (such as connection timed out). In
Georg Brandl116aa622007-08-15 14:28:22 +0000707non-blocking mode, operations fail (with an error that is unfortunately
708system-dependent) if they cannot be completed immediately. In timeout mode,
709operations fail if they cannot be completed within the timeout specified for the
Georg Brandl6c8583f2010-05-19 21:22:58 +0000710socket or if the system returns an error. The :meth:`~socket.setblocking`
711method is simply a shorthand for certain :meth:`~socket.settimeout` calls.
Georg Brandl116aa622007-08-15 14:28:22 +0000712
713Timeout mode internally sets the socket in non-blocking mode. The blocking and
714timeout modes are shared between file descriptors and socket objects that refer
715to the same network endpoint. A consequence of this is that file objects
Georg Brandl6c8583f2010-05-19 21:22:58 +0000716returned by the :meth:`~socket.makefile` method must only be used when the
717socket is in blocking mode; in timeout or non-blocking mode file operations
718that cannot be completed immediately will fail.
Georg Brandl116aa622007-08-15 14:28:22 +0000719
Georg Brandl6c8583f2010-05-19 21:22:58 +0000720Note that the :meth:`~socket.connect` operation is subject to the timeout
721setting, and in general it is recommended to call :meth:`~socket.settimeout`
722before calling :meth:`~socket.connect` or pass a timeout parameter to
723:meth:`create_connection`. The system network stack may return a connection
724timeout error of its own regardless of any Python socket timeout setting.
Georg Brandl116aa622007-08-15 14:28:22 +0000725
726
727.. method:: socket.setsockopt(level, optname, value)
728
729 .. index:: module: struct
730
731 Set the value of the given socket option (see the Unix manual page
732 :manpage:`setsockopt(2)`). The needed symbolic constants are defined in the
733 :mod:`socket` module (:const:`SO_\*` etc.). The value can be an integer or a
Georg Brandl42b2f2e2008-08-14 11:50:32 +0000734 bytes object representing a buffer. In the latter case it is up to the caller to
735 ensure that the bytestring contains the proper bits (see the optional built-in
736 module :mod:`struct` for a way to encode C structures as bytestrings).
Georg Brandl116aa622007-08-15 14:28:22 +0000737
738
739.. method:: socket.shutdown(how)
740
741 Shut down one or both halves of the connection. If *how* is :const:`SHUT_RD`,
742 further receives are disallowed. If *how* is :const:`SHUT_WR`, further sends
743 are disallowed. If *how* is :const:`SHUT_RDWR`, further sends and receives are
Georg Brandl914a2182010-10-06 08:13:26 +0000744 disallowed. Depending on the platform, shutting down one half of the connection
745 can also close the opposite half (e.g. on Mac OS X, ``shutdown(SHUT_WR)`` does
746 not allow further reads on the other end of the connection).
Georg Brandl116aa622007-08-15 14:28:22 +0000747
Georg Brandl6c8583f2010-05-19 21:22:58 +0000748Note that there are no methods :meth:`read` or :meth:`write`; use
749:meth:`~socket.recv` and :meth:`~socket.send` without *flags* argument instead.
Georg Brandl116aa622007-08-15 14:28:22 +0000750
751Socket objects also have these (read-only) attributes that correspond to the
752values given to the :class:`socket` constructor.
753
754
755.. attribute:: socket.family
756
757 The socket family.
758
Georg Brandl116aa622007-08-15 14:28:22 +0000759
760.. attribute:: socket.type
761
762 The socket type.
763
Georg Brandl116aa622007-08-15 14:28:22 +0000764
765.. attribute:: socket.proto
766
767 The socket protocol.
768
Georg Brandl116aa622007-08-15 14:28:22 +0000769
Georg Brandl116aa622007-08-15 14:28:22 +0000770.. _socket-example:
771
772Example
773-------
774
775Here are four minimal example programs using the TCP/IP protocol: a server that
776echoes all data that it receives back (servicing only one client), and a client
777using it. Note that a server must perform the sequence :func:`socket`,
Georg Brandl6c8583f2010-05-19 21:22:58 +0000778:meth:`~socket.bind`, :meth:`~socket.listen`, :meth:`~socket.accept` (possibly
779repeating the :meth:`~socket.accept` to service more than one client), while a
780client only needs the sequence :func:`socket`, :meth:`~socket.connect`. Also
781note that the server does not :meth:`~socket.send`/:meth:`~socket.recv` on the
782socket it is listening on but on the new socket returned by
783:meth:`~socket.accept`.
Georg Brandl116aa622007-08-15 14:28:22 +0000784
785The first two examples support IPv4 only. ::
786
787 # Echo server program
788 import socket
789
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000790 HOST = '' # Symbolic name meaning all available interfaces
Georg Brandl116aa622007-08-15 14:28:22 +0000791 PORT = 50007 # Arbitrary non-privileged port
792 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
793 s.bind((HOST, PORT))
794 s.listen(1)
795 conn, addr = s.accept()
Georg Brandl6911e3c2007-09-04 07:15:32 +0000796 print('Connected by', addr)
Collin Winter46334482007-09-10 00:49:57 +0000797 while True:
Georg Brandl116aa622007-08-15 14:28:22 +0000798 data = conn.recv(1024)
799 if not data: break
800 conn.send(data)
801 conn.close()
802
803::
804
805 # Echo client program
806 import socket
807
808 HOST = 'daring.cwi.nl' # The remote host
809 PORT = 50007 # The same port as used by the server
810 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
811 s.connect((HOST, PORT))
Georg Brandl42b2f2e2008-08-14 11:50:32 +0000812 s.send(b'Hello, world')
Georg Brandl116aa622007-08-15 14:28:22 +0000813 data = s.recv(1024)
814 s.close()
Georg Brandl6911e3c2007-09-04 07:15:32 +0000815 print('Received', repr(data))
Georg Brandl116aa622007-08-15 14:28:22 +0000816
817The next two examples are identical to the above two, but support both IPv4 and
818IPv6. The server side will listen to the first address family available (it
819should listen to both instead). On most of IPv6-ready systems, IPv6 will take
820precedence and the server may not accept IPv4 traffic. The client side will try
821to connect to the all addresses returned as a result of the name resolution, and
822sends traffic to the first one connected successfully. ::
823
824 # Echo server program
825 import socket
826 import sys
827
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000828 HOST = None # Symbolic name meaning all available interfaces
Georg Brandl116aa622007-08-15 14:28:22 +0000829 PORT = 50007 # Arbitrary non-privileged port
830 s = None
Georg Brandl42b2f2e2008-08-14 11:50:32 +0000831 for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC,
832 socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
Georg Brandl116aa622007-08-15 14:28:22 +0000833 af, socktype, proto, canonname, sa = res
834 try:
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000835 s = socket.socket(af, socktype, proto)
Georg Brandl116aa622007-08-15 14:28:22 +0000836 except socket.error as msg:
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000837 s = None
838 continue
Georg Brandl116aa622007-08-15 14:28:22 +0000839 try:
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000840 s.bind(sa)
841 s.listen(1)
Georg Brandl116aa622007-08-15 14:28:22 +0000842 except socket.error as msg:
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000843 s.close()
844 s = None
845 continue
Georg Brandl116aa622007-08-15 14:28:22 +0000846 break
847 if s is None:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000848 print('could not open socket')
Georg Brandl116aa622007-08-15 14:28:22 +0000849 sys.exit(1)
850 conn, addr = s.accept()
Georg Brandl6911e3c2007-09-04 07:15:32 +0000851 print('Connected by', addr)
Collin Winter46334482007-09-10 00:49:57 +0000852 while True:
Georg Brandl116aa622007-08-15 14:28:22 +0000853 data = conn.recv(1024)
854 if not data: break
855 conn.send(data)
856 conn.close()
857
858::
859
860 # Echo client program
861 import socket
862 import sys
863
864 HOST = 'daring.cwi.nl' # The remote host
865 PORT = 50007 # The same port as used by the server
866 s = None
867 for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM):
868 af, socktype, proto, canonname, sa = res
869 try:
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000870 s = socket.socket(af, socktype, proto)
Georg Brandl116aa622007-08-15 14:28:22 +0000871 except socket.error as msg:
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000872 s = None
873 continue
Georg Brandl116aa622007-08-15 14:28:22 +0000874 try:
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000875 s.connect(sa)
Georg Brandl116aa622007-08-15 14:28:22 +0000876 except socket.error as msg:
Georg Brandla1c6a1c2009-01-03 21:26:05 +0000877 s.close()
878 s = None
879 continue
Georg Brandl116aa622007-08-15 14:28:22 +0000880 break
881 if s is None:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000882 print('could not open socket')
Georg Brandl116aa622007-08-15 14:28:22 +0000883 sys.exit(1)
Georg Brandl42b2f2e2008-08-14 11:50:32 +0000884 s.send(b'Hello, world')
Georg Brandl116aa622007-08-15 14:28:22 +0000885 data = s.recv(1024)
886 s.close()
Georg Brandl6911e3c2007-09-04 07:15:32 +0000887 print('Received', repr(data))
Georg Brandl116aa622007-08-15 14:28:22 +0000888
Georg Brandl48310cd2009-01-03 21:18:54 +0000889
Christian Heimesfaf2f632008-01-06 16:59:19 +0000890The last example shows how to write a very simple network sniffer with raw
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000891sockets on Windows. The example requires administrator privileges to modify
Christian Heimesfaf2f632008-01-06 16:59:19 +0000892the interface::
893
894 import socket
895
896 # the public network interface
897 HOST = socket.gethostbyname(socket.gethostname())
Georg Brandl48310cd2009-01-03 21:18:54 +0000898
Christian Heimesfaf2f632008-01-06 16:59:19 +0000899 # create a raw socket and bind it to the public interface
900 s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
901 s.bind((HOST, 0))
Georg Brandl48310cd2009-01-03 21:18:54 +0000902
Christian Heimesfaf2f632008-01-06 16:59:19 +0000903 # Include IP headers
904 s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
Georg Brandl48310cd2009-01-03 21:18:54 +0000905
Christian Heimesfaf2f632008-01-06 16:59:19 +0000906 # receive all packages
907 s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
Georg Brandl48310cd2009-01-03 21:18:54 +0000908
Christian Heimesfaf2f632008-01-06 16:59:19 +0000909 # receive a package
Neal Norwitz752abd02008-05-13 04:55:24 +0000910 print(s.recvfrom(65565))
Georg Brandl48310cd2009-01-03 21:18:54 +0000911
Christian Heimesc3f30c42008-02-22 16:37:40 +0000912 # disabled promiscuous mode
Christian Heimesfaf2f632008-01-06 16:59:19 +0000913 s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)