PageRenderTime 17ms CodeModel.GetById 2ms app.highlight 7ms RepoModel.GetById 1ms app.codeStats 0ms

/library/socket.txt

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