PageRenderTime 34ms CodeModel.GetById 2ms app.highlight 24ms RepoModel.GetById 1ms app.codeStats 1ms

/Doc/library/socket.rst

https://bitbucket.org/schmichael/cpython-v2.6.8-nosslv2
ReStructuredText | 967 lines | 674 code | 293 blank | 0 comment | 0 complexity | 9dfdba9fde828bcaf90f5e4dc89b63b9 MD5 | raw file
  1:mod:`socket` --- Low-level networking interface
  2================================================
  3
  4.. module:: socket
  5   :synopsis: Low-level networking interface.
  6
  7
  8This module provides access to the BSD *socket* interface. It is available on
  9all modern Unix systems, Windows, Mac OS X, BeOS, OS/2, and probably additional
 10platforms.
 11
 12.. note::
 13
 14   Some behavior may be platform dependent, since calls are made to the operating
 15   system socket APIs.
 16
 17For an introduction to socket programming (in C), see the following papers: An
 18Introductory 4.3BSD Interprocess Communication Tutorial, by Stuart Sechrest and
 19An Advanced 4.3BSD Interprocess Communication Tutorial, by Samuel J.  Leffler et
 20al, both in the UNIX Programmer's Manual, Supplementary Documents 1 (sections
 21PS1:7 and PS1:8).  The platform-specific reference material for the various
 22socket-related system calls are also a valuable source of information on the
 23details of socket semantics.  For Unix, refer to the manual pages; for Windows,
 24see the WinSock (or Winsock 2) specification. For IPv6-ready APIs, readers may
 25want to refer to :rfc:`3493` titled Basic Socket Interface Extensions for IPv6.
 26
 27.. index:: object: socket
 28
 29The Python interface is a straightforward transliteration of the Unix system
 30call and library interface for sockets to Python's object-oriented style: the
 31:func:`socket` function returns a :dfn:`socket object` whose methods implement
 32the various socket system calls.  Parameter types are somewhat higher-level than
 33in the C interface: as with :meth:`read` and :meth:`write` operations on Python
 34files, buffer allocation on receive operations is automatic, and buffer length
 35is implicit on send operations.
 36
 37Socket addresses are represented as follows: A single string is used for the
 38:const:`AF_UNIX` address family. A pair ``(host, port)`` is used for the
 39:const:`AF_INET` address family, where *host* is a string representing either a
 40hostname in Internet domain notation like ``'daring.cwi.nl'`` or an IPv4 address
 41like ``'100.50.200.5'``, and *port* is an integral port number. For
 42:const:`AF_INET6` address family, a four-tuple ``(host, port, flowinfo,
 43scopeid)`` is used, where *flowinfo* and *scopeid* represents ``sin6_flowinfo``
 44and ``sin6_scope_id`` member in :const:`struct sockaddr_in6` in C. For
 45:mod:`socket` module methods, *flowinfo* and *scopeid* can be omitted just for
 46backward compatibility. Note, however, omission of *scopeid* can cause problems
 47in manipulating scoped IPv6 addresses. Other address families are currently not
 48supported. The address format required by a particular socket object is
 49automatically selected based on the address family specified when the socket
 50object was created.
 51
 52For IPv4 addresses, two special forms are accepted instead of a host address:
 53the empty string represents :const:`INADDR_ANY`, and the string
 54``'<broadcast>'`` represents :const:`INADDR_BROADCAST`. The behavior is not
 55available for IPv6 for backward compatibility, therefore, you may want to avoid
 56these if you intend to support IPv6 with your Python programs.
 57
 58If you use a hostname in the *host* portion of IPv4/v6 socket address, the
 59program may show a nondeterministic behavior, as Python uses the first address
 60returned from the DNS resolution.  The socket address will be resolved
 61differently into an actual IPv4/v6 address, depending on the results from DNS
 62resolution and/or the host configuration.  For deterministic behavior use a
 63numeric address in *host* portion.
 64
 65.. versionadded:: 2.5
 66   AF_NETLINK sockets are represented as  pairs ``pid, groups``.
 67
 68.. versionadded:: 2.6
 69   Linux-only support for TIPC is also available using the :const:`AF_TIPC`
 70   address family. TIPC is an open, non-IP based networked protocol designed
 71   for use in clustered computer environments.  Addresses are represented by a
 72   tuple, and the fields depend on the address type. The general tuple form is
 73   ``(addr_type, v1, v2, v3 [, scope])``, where:
 74
 75   - *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.
 81
 82     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.
 84
 85     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
 89All errors raise exceptions.  The normal exceptions for invalid argument types
 90and out-of-memory conditions can be raised; errors related to socket or address
 91semantics raise the error :exc:`socket.error`.
 92
 93Non-blocking mode is supported through :meth:`~socket.setblocking`.  A
 94generalization of this based on timeouts is supported through
 95:meth:`~socket.settimeout`.
 96
 97The module :mod:`socket` exports the following constants and functions:
 98
 99
100.. exception:: error
101
102   .. index:: module: errno
103
104   This exception is raised for socket-related errors. The accompanying value is
105   either a string telling what went wrong or a pair ``(errno, string)``
106   representing an error returned by a system call, similar to the value
107   accompanying :exc:`os.error`. See the module :mod:`errno`, which contains names
108   for the error codes defined by the underlying operating system.
109
110   .. versionchanged:: 2.6
111      :exc:`socket.error` is now a child class of :exc:`IOError`.
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
141   .. versionadded:: 2.3
142
143
144.. data:: AF_UNIX
145          AF_INET
146          AF_INET6
147
148   These constants represent the address (and protocol) families, used for the
149   first argument to :func:`socket`.  If the :const:`AF_UNIX` constant is not
150   defined then this protocol is unsupported.
151
152
153.. data:: SOCK_STREAM
154          SOCK_DGRAM
155          SOCK_RAW
156          SOCK_RDM
157          SOCK_SEQPACKET
158
159   These constants represent the socket types, used for the second argument to
160   :func:`socket`. (Only :const:`SOCK_STREAM` and :const:`SOCK_DGRAM` appear to be
161   generally useful.)
162
163
164.. data:: SO_*
165          SOMAXCONN
166          MSG_*
167          SOL_*
168          IPPROTO_*
169          IPPORT_*
170          INADDR_*
171          IP_*
172          IPV6_*
173          EAI_*
174          AI_*
175          NI_*
176          TCP_*
177
178   Many constants of these forms, documented in the Unix documentation on sockets
179   and/or the IP protocol, are also defined in the socket module. They are
180   generally used in arguments to the :meth:`setsockopt` and :meth:`getsockopt`
181   methods of socket objects.  In most cases, only those symbols that are defined
182   in the Unix header files are defined; for a few symbols, default values are
183   provided.
184
185.. data:: SIO_*
186          RCVALL_*
187
188   Constants for Windows' WSAIoctl(). The constants are used as arguments to the
189   :meth:`ioctl` method of socket objects.
190
191   .. versionadded:: 2.6
192
193.. data:: TIPC_*
194
195   TIPC related constants, matching the ones exported by the C socket API. See
196   the TIPC documentation for more information.
197
198   .. versionadded:: 2.6
199
200.. data:: has_ipv6
201
202   This constant contains a boolean value which indicates if IPv6 is supported on
203   this platform.
204
205   .. versionadded:: 2.3
206
207
208.. function:: create_connection(address[, timeout])
209
210   Convenience function.  Connect to *address* (a 2-tuple ``(host, port)``),
211   and return the socket object.  Passing the optional *timeout* parameter will
212   set the timeout on the socket instance before attempting to connect.  If no
213   *timeout* is supplied, the global default timeout setting returned by
214   :func:`getdefaulttimeout` is used.
215
216   .. versionadded:: 2.6
217
218
219.. function:: getaddrinfo(host, port, family=0, socktype=0, proto=0, flags=0)
220
221   Translate the *host*/*port* argument into a sequence of 5-tuples that contain
222   all the necessary arguments for creating a socket connected to that service.
223   *host* is a domain name, a string representation of an IPv4/v6 address
224   or ``None``. *port* is a string service name such as ``'http'``, a numeric
225   port number or ``None``.  By passing ``None`` as the value of *host*
226   and *port*, you can pass ``NULL`` to the underlying C API.
227
228   The *family*, *socktype* and *proto* arguments can be optionally specified
229   in order to narrow the list of addresses returned.  Passing zero as a
230   value for each of these arguments selects the full range of results.
231   The *flags* argument can be one or several of the ``AI_*`` constants,
232   and will influence how results are computed and returned.
233   For example, :const:`AI_NUMERICHOST` will disable domain name resolution
234   and will raise an error if *host* is a domain name.
235
236   The function returns a list of 5-tuples with the following structure:
237
238   ``(family, socktype, proto, canonname, sockaddr)``
239
240   In these tuples, *family*, *socktype*, *proto* are all integers and are
241   meant to be passed to the :func:`socket` function.  *canonname* will be
242   a string representing the canonical name of the *host* if
243   :const:`AI_CANONNAME` is part of the *flags* argument; else *canonname*
244   will be empty.  *sockaddr* is a tuple describing a socket address, whose
245   format depends on the returned *family* (a ``(address, port)`` 2-tuple for
246   :const:`AF_INET`, a ``(address, port, flow info, scope id)`` 4-tuple for
247   :const:`AF_INET6`), and is meant to be passed to the :meth:`socket.connect`
248   method.
249
250   The following example fetches address information for a hypothetical TCP
251   connection to ``www.python.org`` on port 80 (results may differ on your
252   system if IPv6 isn't enabled)::
253
254      >>> socket.getaddrinfo("www.python.org", 80, 0, 0, socket.SOL_TCP)
255      [(2, 1, 6, '', ('82.94.164.162', 80)),
256       (10, 1, 6, '', ('2001:888:2000:d::a2', 80, 0, 0))]
257
258   .. versionadded:: 2.2
259
260
261.. function:: getfqdn([name])
262
263   Return a fully qualified domain name for *name*. If *name* is omitted or empty,
264   it is interpreted as the local host.  To find the fully qualified name, the
265   hostname returned by :func:`gethostbyaddr` is checked, followed by aliases for the
266   host, if available.  The first name which includes a period is selected.  In
267   case no fully qualified domain name is available, the hostname as returned by
268   :func:`gethostname` is returned.
269
270   .. versionadded:: 2.0
271
272
273.. function:: gethostbyname(hostname)
274
275   Translate a host name to IPv4 address format.  The IPv4 address is returned as a
276   string, such as  ``'100.50.200.5'``.  If the host name is an IPv4 address itself
277   it is returned unchanged.  See :func:`gethostbyname_ex` for a more complete
278   interface. :func:`gethostbyname` does not support IPv6 name resolution, and
279   :func:`getaddrinfo` should be used instead for IPv4/v6 dual stack support.
280
281
282.. function:: gethostbyname_ex(hostname)
283
284   Translate a host name to IPv4 address format, extended interface. Return a
285   triple ``(hostname, aliaslist, ipaddrlist)`` where *hostname* is the primary
286   host name responding to the given *ip_address*, *aliaslist* is a (possibly
287   empty) list of alternative host names for the same address, and *ipaddrlist* is
288   a list of IPv4 addresses for the same interface on the same host (often but not
289   always a single address). :func:`gethostbyname_ex` does not support IPv6 name
290   resolution, and :func:`getaddrinfo` should be used instead for IPv4/v6 dual
291   stack support.
292
293
294.. function:: gethostname()
295
296   Return a string containing the hostname of the machine where  the Python
297   interpreter is currently executing.
298
299   If you want to know the current machine's IP address, you may want to use
300   ``gethostbyname(gethostname())``. This operation assumes that there is a
301   valid address-to-host mapping for the host, and the assumption does not
302   always hold.
303
304   Note: :func:`gethostname` doesn't always return the fully qualified domain
305   name; use ``getfqdn()`` (see above).
306
307
308.. function:: gethostbyaddr(ip_address)
309
310   Return a triple ``(hostname, aliaslist, ipaddrlist)`` where *hostname* is the
311   primary host name responding to the given *ip_address*, *aliaslist* is a
312   (possibly empty) list of alternative host names for the same address, and
313   *ipaddrlist* is a list of IPv4/v6 addresses for the same interface on the same
314   host (most likely containing only a single address). To find the fully qualified
315   domain name, use the function :func:`getfqdn`. :func:`gethostbyaddr` supports
316   both IPv4 and IPv6.
317
318
319.. function:: getnameinfo(sockaddr, flags)
320
321   Translate a socket address *sockaddr* into a 2-tuple ``(host, port)``. Depending
322   on the settings of *flags*, the result can contain a fully-qualified domain name
323   or numeric address representation in *host*.  Similarly, *port* can contain a
324   string port name or a numeric port number.
325
326   .. versionadded:: 2.2
327
328
329.. function:: getprotobyname(protocolname)
330
331   Translate an Internet protocol name (for example, ``'icmp'``) to a constant
332   suitable for passing as the (optional) third argument to the :func:`socket`
333   function.  This is usually only needed for sockets opened in "raw" mode
334   (:const:`SOCK_RAW`); for the normal socket modes, the correct protocol is chosen
335   automatically if the protocol is omitted or zero.
336
337
338.. function:: getservbyname(servicename[, protocolname])
339
340   Translate an Internet service name and protocol name to a port number for that
341   service.  The optional protocol name, if given, should be ``'tcp'`` or
342   ``'udp'``, otherwise any protocol will match.
343
344
345.. function:: getservbyport(port[, protocolname])
346
347   Translate an Internet port number and protocol name to a service name for that
348   service.  The optional protocol name, if given, should be ``'tcp'`` or
349   ``'udp'``, otherwise any protocol will match.
350
351
352.. function:: socket([family[, type[, proto]]])
353
354   Create a new socket using the given address family, socket type and protocol
355   number.  The address family should be :const:`AF_INET` (the default),
356   :const:`AF_INET6` or :const:`AF_UNIX`.  The socket type should be
357   :const:`SOCK_STREAM` (the default), :const:`SOCK_DGRAM` or perhaps one of the
358   other ``SOCK_`` constants.  The protocol number is usually zero and may be
359   omitted in that case.
360
361
362.. function:: socketpair([family[, type[, proto]]])
363
364   Build a pair of connected socket objects using the given address family, socket
365   type, and protocol number.  Address family, socket type, and protocol number are
366   as for the :func:`socket` function above. The default family is :const:`AF_UNIX`
367   if defined on the platform; otherwise, the default is :const:`AF_INET`.
368   Availability: Unix.
369
370   .. versionadded:: 2.4
371
372
373.. function:: fromfd(fd, family, type[, proto])
374
375   Duplicate the file descriptor *fd* (an integer as returned by a file object's
376   :meth:`fileno` method) and build a socket object from the result.  Address
377   family, socket type and protocol number are as for the :func:`socket` function
378   above. The file descriptor should refer to a socket, but this is not checked ---
379   subsequent operations on the object may fail if the file descriptor is invalid.
380   This function is rarely needed, but can be used to get or set socket options on
381   a socket passed to a program as standard input or output (such as a server
382   started by the Unix inet daemon).  The socket is assumed to be in blocking mode.
383   Availability: Unix.
384
385
386.. function:: ntohl(x)
387
388   Convert 32-bit positive integers from network to host byte order.  On machines
389   where the host byte order is the same as network byte order, this is a no-op;
390   otherwise, it performs a 4-byte swap operation.
391
392
393.. function:: ntohs(x)
394
395   Convert 16-bit positive integers from network to host byte order.  On machines
396   where the host byte order is the same as network byte order, this is a no-op;
397   otherwise, it performs a 2-byte swap operation.
398
399
400.. function:: htonl(x)
401
402   Convert 32-bit positive integers from host to network byte order.  On machines
403   where the host byte order is the same as network byte order, this is a no-op;
404   otherwise, it performs a 4-byte swap operation.
405
406
407.. function:: htons(x)
408
409   Convert 16-bit positive integers from host to network byte order.  On machines
410   where the host byte order is the same as network byte order, this is a no-op;
411   otherwise, it performs a 2-byte swap operation.
412
413
414.. function:: inet_aton(ip_string)
415
416   Convert an IPv4 address from dotted-quad string format (for example,
417   '123.45.67.89') to 32-bit packed binary format, as a string four characters in
418   length.  This is useful when conversing with a program that uses the standard C
419   library and needs objects of type :ctype:`struct in_addr`, which is the C type
420   for the 32-bit packed binary this function returns.
421
422   :func:`inet_aton` also accepts strings with less than three dots; see the
423   Unix manual page :manpage:`inet(3)` for details.
424
425   If the IPv4 address string passed to this function is invalid,
426   :exc:`socket.error` will be raised. Note that exactly what is valid depends on
427   the underlying C implementation of :cfunc:`inet_aton`.
428
429   :func:`inet_aton` does not support IPv6, and :func:`inet_pton` should be used
430   instead for IPv4/v6 dual stack support.
431
432
433.. function:: inet_ntoa(packed_ip)
434
435   Convert a 32-bit packed IPv4 address (a string four characters in length) to its
436   standard dotted-quad string representation (for example, '123.45.67.89').  This
437   is useful when conversing with a program that uses the standard C library and
438   needs objects of type :ctype:`struct in_addr`, which is the C type for the
439   32-bit packed binary data this function takes as an argument.
440
441   If the string passed to this function is not exactly 4 bytes in length,
442   :exc:`socket.error` will be raised. :func:`inet_ntoa` does not support IPv6, and
443   :func:`inet_ntop` should be used instead for IPv4/v6 dual stack support.
444
445
446.. function:: inet_pton(address_family, ip_string)
447
448   Convert an IP address from its family-specific string format to a packed, binary
449   format. :func:`inet_pton` is useful when a library or network protocol calls for
450   an object of type :ctype:`struct in_addr` (similar to :func:`inet_aton`) or
451   :ctype:`struct in6_addr`.
452
453   Supported values for *address_family* are currently :const:`AF_INET` and
454   :const:`AF_INET6`. If the IP address string *ip_string* is invalid,
455   :exc:`socket.error` will be raised. Note that exactly what is valid depends on
456   both the value of *address_family* and the underlying implementation of
457   :cfunc:`inet_pton`.
458
459   Availability: Unix (maybe not all platforms).
460
461   .. versionadded:: 2.3
462
463
464.. function:: inet_ntop(address_family, packed_ip)
465
466   Convert a packed IP address (a string of some number of characters) to its
467   standard, family-specific string representation (for example, ``'7.10.0.5'`` or
468   ``'5aef:2b::8'``) :func:`inet_ntop` is useful when a library or network protocol
469   returns an object of type :ctype:`struct in_addr` (similar to :func:`inet_ntoa`)
470   or :ctype:`struct in6_addr`.
471
472   Supported values for *address_family* are currently :const:`AF_INET` and
473   :const:`AF_INET6`. If the string *packed_ip* is not the correct length for the
474   specified address family, :exc:`ValueError` will be raised.  A
475   :exc:`socket.error` is raised for errors from the call to :func:`inet_ntop`.
476
477   Availability: Unix (maybe not all platforms).
478
479   .. versionadded:: 2.3
480
481
482.. function:: getdefaulttimeout()
483
484   Return the default timeout in floating seconds for new socket objects. A value
485   of ``None`` indicates that new socket objects have no timeout. When the socket
486   module is first imported, the default is ``None``.
487
488   .. versionadded:: 2.3
489
490
491.. function:: setdefaulttimeout(timeout)
492
493   Set the default timeout in floating seconds for new socket objects. A value of
494   ``None`` indicates that new socket objects have no timeout. When the socket
495   module is first imported, the default is ``None``.
496
497   .. versionadded:: 2.3
498
499
500.. data:: SocketType
501
502   This is a Python type object that represents the socket object type. It is the
503   same as ``type(socket(...))``.
504
505
506.. seealso::
507
508   Module :mod:`SocketServer`
509      Classes that simplify writing network servers.
510
511
512.. _socket-objects:
513
514Socket Objects
515--------------
516
517Socket objects have the following methods.  Except for :meth:`makefile` these
518correspond to Unix system calls applicable to sockets.
519
520
521.. method:: socket.accept()
522
523   Accept a connection. The socket must be bound to an address and listening for
524   connections. The return value is a pair ``(conn, address)`` where *conn* is a
525   *new* socket object usable to send and receive data on the connection, and
526   *address* is the address bound to the socket on the other end of the connection.
527
528
529.. method:: socket.bind(address)
530
531   Bind the socket to *address*.  The socket must not already be bound. (The format
532   of *address* depends on the address family --- see above.)
533
534   .. note::
535
536      This method has historically accepted a pair of parameters for :const:`AF_INET`
537      addresses instead of only a tuple.  This was never intentional and is no longer
538      available in Python 2.0 and later.
539
540
541.. method:: socket.close()
542
543   Close the socket.  All future operations on the socket object will fail. The
544   remote end will receive no more data (after queued data is flushed). Sockets are
545   automatically closed when they are garbage-collected.
546
547
548.. method:: socket.connect(address)
549
550   Connect to a remote socket at *address*. (The format of *address* depends on the
551   address family --- see above.)
552
553   .. note::
554
555      This method has historically accepted a pair of parameters for :const:`AF_INET`
556      addresses instead of only a tuple.  This was never intentional and is no longer
557      available in Python 2.0 and later.
558
559
560.. method:: socket.connect_ex(address)
561
562   Like ``connect(address)``, but return an error indicator instead of raising an
563   exception for errors returned by the C-level :cfunc:`connect` call (other
564   problems, such as "host not found," can still raise exceptions).  The error
565   indicator is ``0`` if the operation succeeded, otherwise the value of the
566   :cdata:`errno` variable.  This is useful to support, for example, asynchronous
567   connects.
568
569   .. note::
570
571      This method has historically accepted a pair of parameters for :const:`AF_INET`
572      addresses instead of only a tuple. This was never intentional and is no longer
573      available in Python 2.0 and later.
574
575
576.. method:: socket.fileno()
577
578   Return the socket's file descriptor (a small integer).  This is useful with
579   :func:`select.select`.
580
581   Under Windows the small integer returned by this method cannot be used where a
582   file descriptor can be used (such as :func:`os.fdopen`).  Unix does not have
583   this limitation.
584
585
586.. method:: socket.getpeername()
587
588   Return the remote address to which the socket is connected.  This is useful to
589   find out the port number of a remote IPv4/v6 socket, for instance. (The format
590   of the address returned depends on the address family --- see above.)  On some
591   systems this function is not supported.
592
593
594.. method:: socket.getsockname()
595
596   Return the socket's own address.  This is useful to find out the port number of
597   an IPv4/v6 socket, for instance. (The format of the address returned depends on
598   the address family --- see above.)
599
600
601.. method:: socket.getsockopt(level, optname[, buflen])
602
603   Return the value of the given socket option (see the Unix man page
604   :manpage:`getsockopt(2)`).  The needed symbolic constants (:const:`SO_\*` etc.)
605   are defined in this module.  If *buflen* is absent, an integer option is assumed
606   and its integer value is returned by the function.  If *buflen* is present, it
607   specifies the maximum length of the buffer used to receive the option in, and
608   this buffer is returned as a string.  It is up to the caller to decode the
609   contents of the buffer (see the optional built-in module :mod:`struct` for a way
610   to decode C structures encoded as strings).
611
612
613.. method:: socket.ioctl(control, option)
614
615   :platform: Windows
616
617   The :meth:`ioctl` method is a limited interface to the WSAIoctl system
618   interface.  Please refer to the `Win32 documentation
619   <http://msdn.microsoft.com/en-us/library/ms741621%28VS.85%29.aspx>`_ for more
620   information.
621
622   On other platforms, the generic :func:`fcntl.fcntl` and :func:`fcntl.ioctl`
623   functions may be used; they accept a socket object as their first argument.
624
625   .. versionadded:: 2.6
626
627
628.. method:: socket.listen(backlog)
629
630   Listen for connections made to the socket.  The *backlog* argument specifies the
631   maximum number of queued connections and should be at least 1; the maximum value
632   is system-dependent (usually 5).
633
634
635.. method:: socket.makefile([mode[, bufsize]])
636
637   .. index:: single: I/O control; buffering
638
639   Return a :dfn:`file object` associated with the socket.  (File objects are
640   described in :ref:`bltin-file-objects`.) The file object
641   references a :cfunc:`dup`\ ped version of the socket file descriptor, so the
642   file object and socket object may be closed or garbage-collected independently.
643   The socket must be in blocking mode (it can not have a timeout). The optional
644   *mode* and *bufsize* arguments are interpreted the same way as by the built-in
645   :func:`file` function.
646
647
648.. method:: socket.recv(bufsize[, flags])
649
650   Receive data from the socket.  The return value is a string representing the
651   data received.  The maximum amount of data to be received at once is specified
652   by *bufsize*.  See the Unix manual page :manpage:`recv(2)` for the meaning of
653   the optional argument *flags*; it defaults to zero.
654
655   .. note::
656
657      For best match with hardware and network realities, the value of  *bufsize*
658      should be a relatively small power of 2, for example, 4096.
659
660
661.. method:: socket.recvfrom(bufsize[, flags])
662
663   Receive data from the socket.  The return value is a pair ``(string, address)``
664   where *string* is a string representing the data received and *address* is the
665   address of the socket sending the data.  See the Unix manual page
666   :manpage:`recv(2)` for the meaning of the optional argument *flags*; it defaults
667   to zero. (The format of *address* depends on the address family --- see above.)
668
669
670.. method:: socket.recvfrom_into(buffer[, nbytes[, flags]])
671
672   Receive data from the socket, writing it into *buffer* instead of  creating a
673   new string.  The return value is a pair ``(nbytes, address)`` where *nbytes* is
674   the number of bytes received and *address* is the address of the socket sending
675   the data.  See the Unix manual page :manpage:`recv(2)` for the meaning of the
676   optional argument *flags*; it defaults to zero.  (The format of *address*
677   depends on the address family --- see above.)
678
679   .. versionadded:: 2.5
680
681
682.. method:: socket.recv_into(buffer[, nbytes[, flags]])
683
684   Receive up to *nbytes* bytes from the socket, storing the data into a buffer
685   rather than creating a new string.  If *nbytes* is not specified (or 0),
686   receive up to the size available in the given buffer.  Returns the number of
687   bytes received.  See the Unix manual page :manpage:`recv(2)` for the meaning
688   of the optional argument *flags*; it defaults to zero.
689
690   .. versionadded:: 2.5
691
692
693.. method:: socket.send(string[, flags])
694
695   Send data to the socket.  The socket must be connected to a remote socket.  The
696   optional *flags* argument has the same meaning as for :meth:`recv` above.
697   Returns the number of bytes sent. Applications are responsible for checking that
698   all data has been sent; if only some of the data was transmitted, the
699   application needs to attempt delivery of the remaining data.
700
701
702.. method:: socket.sendall(string[, flags])
703
704   Send data to the socket.  The socket must be connected to a remote socket.  The
705   optional *flags* argument has the same meaning as for :meth:`recv` above.
706   Unlike :meth:`send`, this method continues to send data from *string* until
707   either all data has been sent or an error occurs.  ``None`` is returned on
708   success.  On error, an exception is raised, and there is no way to determine how
709   much data, if any, was successfully sent.
710
711
712.. method:: socket.sendto(string[, flags], address)
713
714   Send data to the socket.  The socket should not be connected to a remote socket,
715   since the destination socket is specified by *address*.  The optional *flags*
716   argument has the same meaning as for :meth:`recv` above.  Return the number of
717   bytes sent. (The format of *address* depends on the address family --- see
718   above.)
719
720
721.. method:: socket.setblocking(flag)
722
723   Set blocking or non-blocking mode of the socket: if *flag* is 0, the socket is
724   set to non-blocking, else to blocking mode.  Initially all sockets are in
725   blocking mode.  In non-blocking mode, if a :meth:`recv` call doesn't find any
726   data, or if a :meth:`send` call can't immediately dispose of the data, a
727   :exc:`error` exception is raised; in blocking mode, the calls block until they
728   can proceed. ``s.setblocking(0)`` is equivalent to ``s.settimeout(0.0)``;
729   ``s.setblocking(1)`` is equivalent to ``s.settimeout(None)``.
730
731
732.. method:: socket.settimeout(value)
733
734   Set a timeout on blocking socket operations.  The *value* argument can be a
735   nonnegative float expressing seconds, or ``None``. If a float is given,
736   subsequent socket operations will raise an :exc:`timeout` exception if the
737   timeout period *value* has elapsed before the operation has completed.  Setting
738   a timeout of ``None`` disables timeouts on socket operations.
739   ``s.settimeout(0.0)`` is equivalent to ``s.setblocking(0)``;
740   ``s.settimeout(None)`` is equivalent to ``s.setblocking(1)``.
741
742   .. versionadded:: 2.3
743
744
745.. method:: socket.gettimeout()
746
747   Return the timeout in floating seconds associated with socket operations, or
748   ``None`` if no timeout is set.  This reflects the last call to
749   :meth:`setblocking` or :meth:`settimeout`.
750
751   .. versionadded:: 2.3
752
753Some notes on socket blocking and timeouts: A socket object can be in one of
754three modes: blocking, non-blocking, or timeout.  Sockets are always created in
755blocking mode.  In blocking mode, operations block until complete or
756the system returns an error (such as connection timed out).  In
757non-blocking mode, operations fail (with an error that is unfortunately
758system-dependent) if they cannot be completed immediately.  In timeout mode,
759operations fail if they cannot be completed within the timeout specified for the
760socket or if the system returns an error.  The :meth:`~socket.setblocking`
761method is simply a shorthand for certain :meth:`~socket.settimeout` calls.
762
763Timeout mode internally sets the socket in non-blocking mode.  The blocking and
764timeout modes are shared between file descriptors and socket objects that refer
765to the same network endpoint.  A consequence of this is that file objects
766returned by the :meth:`~socket.makefile` method must only be used when the
767socket is in blocking mode; in timeout or non-blocking mode file operations
768that cannot be completed immediately will fail.
769
770Note that the :meth:`~socket.connect` operation is subject to the timeout
771setting, and in general it is recommended to call :meth:`~socket.settimeout`
772before calling :meth:`~socket.connect` or pass a timeout parameter to
773:meth:`create_connection`.  The system network stack may return a connection
774timeout error of its own regardless of any Python socket timeout setting.
775
776
777.. method:: socket.setsockopt(level, optname, value)
778
779   .. index:: module: struct
780
781   Set the value of the given socket option (see the Unix manual page
782   :manpage:`setsockopt(2)`).  The needed symbolic constants are defined in the
783   :mod:`socket` module (:const:`SO_\*` etc.).  The value can be an integer or a
784   string representing a buffer.  In the latter case it is up to the caller to
785   ensure that the string contains the proper bits (see the optional built-in
786   module :mod:`struct` for a way to encode C structures as strings).
787
788
789.. method:: socket.shutdown(how)
790
791   Shut down one or both halves of the connection.  If *how* is :const:`SHUT_RD`,
792   further receives are disallowed.  If *how* is :const:`SHUT_WR`, further sends
793   are disallowed.  If *how* is :const:`SHUT_RDWR`, further sends and receives are
794   disallowed.
795
796Note that there are no methods :meth:`read` or :meth:`write`; use
797:meth:`~socket.recv` and :meth:`~socket.send` without *flags* argument instead.
798
799Socket objects also have these (read-only) attributes that correspond to the
800values given to the :class:`socket` constructor.
801
802
803.. attribute:: socket.family
804
805   The socket family.
806
807   .. versionadded:: 2.5
808
809
810.. attribute:: socket.type
811
812   The socket type.
813
814   .. versionadded:: 2.5
815
816
817.. attribute:: socket.proto
818
819   The socket protocol.
820
821   .. versionadded:: 2.5
822
823
824.. _socket-example:
825
826Example
827-------
828
829Here are four minimal example programs using the TCP/IP protocol: a server that
830echoes all data that it receives back (servicing only one client), and a client
831using it.  Note that a server must perform the sequence :func:`socket`,
832:meth:`~socket.bind`, :meth:`~socket.listen`, :meth:`~socket.accept` (possibly
833repeating the :meth:`~socket.accept` to service more than one client), while a
834client only needs the sequence :func:`socket`, :meth:`~socket.connect`.  Also
835note that the server does not :meth:`~socket.send`/:meth:`~socket.recv` on the
836socket it is listening on but on the new socket returned by
837:meth:`~socket.accept`.
838
839The first two examples support IPv4 only. ::
840
841   # Echo server program
842   import socket
843
844   HOST = ''                 # Symbolic name meaning all available interfaces
845   PORT = 50007              # Arbitrary non-privileged port
846   s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
847   s.bind((HOST, PORT))
848   s.listen(1)
849   conn, addr = s.accept()
850   print 'Connected by', addr
851   while 1:
852       data = conn.recv(1024)
853       if not data: break
854       conn.send(data)
855   conn.close()
856
857::
858
859   # Echo client program
860   import socket
861
862   HOST = 'daring.cwi.nl'    # The remote host
863   PORT = 50007              # The same port as used by the server
864   s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
865   s.connect((HOST, PORT))
866   s.send('Hello, world')
867   data = s.recv(1024)
868   s.close()
869   print 'Received', repr(data)
870
871The next two examples are identical to the above two, but support both IPv4 and
872IPv6. The server side will listen to the first address family available (it
873should listen to both instead). On most of IPv6-ready systems, IPv6 will take
874precedence and the server may not accept IPv4 traffic. The client side will try
875to connect to the all addresses returned as a result of the name resolution, and
876sends traffic to the first one connected successfully. ::
877
878   # Echo server program
879   import socket
880   import sys
881
882   HOST = None               # Symbolic name meaning all available interfaces
883   PORT = 50007              # Arbitrary non-privileged port
884   s = None
885   for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC,
886                                 socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
887       af, socktype, proto, canonname, sa = res
888       try:
889           s = socket.socket(af, socktype, proto)
890       except socket.error, msg:
891           s = None
892           continue
893       try:
894           s.bind(sa)
895           s.listen(1)
896       except socket.error, msg:
897           s.close()
898           s = None
899           continue
900       break
901   if s is None:
902       print 'could not open socket'
903       sys.exit(1)
904   conn, addr = s.accept()
905   print 'Connected by', addr
906   while 1:
907       data = conn.recv(1024)
908       if not data: break
909       conn.send(data)
910   conn.close()
911
912::
913
914   # Echo client program
915   import socket
916   import sys
917
918   HOST = 'daring.cwi.nl'    # The remote host
919   PORT = 50007              # The same port as used by the server
920   s = None
921   for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM):
922       af, socktype, proto, canonname, sa = res
923       try:
924           s = socket.socket(af, socktype, proto)
925       except socket.error, msg:
926           s = None
927           continue
928       try:
929           s.connect(sa)
930       except socket.error, msg:
931           s.close()
932           s = None
933           continue
934       break
935   if s is None:
936       print 'could not open socket'
937       sys.exit(1)
938   s.send('Hello, world')
939   data = s.recv(1024)
940   s.close()
941   print 'Received', repr(data)
942
943
944The last example shows how to write a very simple network sniffer with raw
945sockets on Windows. The example requires administrator privileges to modify
946the interface::
947
948   import socket
949
950   # the public network interface
951   HOST = socket.gethostbyname(socket.gethostname())
952
953   # create a raw socket and bind it to the public interface
954   s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
955   s.bind((HOST, 0))
956
957   # Include IP headers
958   s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
959
960   # receive all packages
961   s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
962
963   # receive a package
964   print s.recvfrom(65565)
965
966   # disabled promiscuous mode
967   s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)