blob: 73c0ff311f0c7c0e8ed281c9fcdcb1cd5c4b4d76 [file] [log] [blame]
Fred Drake295da241998-08-10 19:42:37 +00001\section{\module{socket} ---
Fred Drake318c0b11999-04-21 17:29:14 +00002 Low-level networking interface}
Fred Drakeb91e9341998-07-23 17:59:49 +00003
Fred Drake318c0b11999-04-21 17:29:14 +00004\declaremodule{builtin}{socket}
Fred Drakeb91e9341998-07-23 17:59:49 +00005\modulesynopsis{Low-level networking interface.}
6
Fred Draked883ca11998-03-10 05:20:33 +00007
Fred Drakeaf8a0151998-01-14 14:51:31 +00008This module provides access to the BSD \emph{socket} interface.
Fred Drake38e5d272000-04-03 20:13:55 +00009It is available on all modern \UNIX{} systems, Windows, MacOS, BeOS,
10OS/2, and probably additional platforms.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000011
12For an introduction to socket programming (in C), see the following
Fred Drake37f15741999-11-10 16:21:37 +000013papers: \citetitle{An Introductory 4.3BSD Interprocess Communication
14Tutorial}, by Stuart Sechrest and \citetitle{An Advanced 4.3BSD
15Interprocess Communication Tutorial}, by Samuel J. Leffler et al,
16both in the \citetitle{\UNIX{} Programmer's Manual, Supplementary Documents 1}
Fred Drake38e5d272000-04-03 20:13:55 +000017(sections PS1:7 and PS1:8). The platform-specific reference material
18for the various socket-related system calls are also a valuable source
19of information on the details of socket semantics. For \UNIX, refer
20to the manual pages; for Windows, see the WinSock (or Winsock 2)
21specification.
Fred Drake3fc291a2001-09-27 04:17:20 +000022For IPv6-ready APIs, readers may want to refer to \rfc{2553} titled
23\citetitle{Basic Socket Interface Extensions for IPv6}.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000024
25The Python interface is a straightforward transliteration of the
26\UNIX{} system call and library interface for sockets to Python's
Fred Draked883ca11998-03-10 05:20:33 +000027object-oriented style: the \function{socket()} function returns a
Fred Drake318c0b11999-04-21 17:29:14 +000028\dfn{socket object}\obindex{socket} whose methods implement the
29various socket system calls. Parameter types are somewhat
30higher-level than in the C interface: as with \method{read()} and
31\method{write()} operations on Python files, buffer allocation on
32receive operations is automatic, and buffer length is implicit on send
33operations.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000034
Martin v. Löwisc9908c42001-08-04 22:22:45 +000035Socket addresses are represented as follows:
36A single string is used for the \constant{AF_UNIX} address family.
37A pair \code{(\var{host}, \var{port})} is used for the
38\constant{AF_INET} address family, where \var{host} is a string
39representing either a hostname in Internet domain notation like
40\code{'daring.cwi.nl'} or an IPv4 address like \code{'100.50.200.5'},
41and \var{port} is an integral port number.
42For \constant{AF_INET6} address family, a four-tuple
43\code{(\var{host}, \var{port}, \var{flowinfo}, \var{scopeid})} is
44used, where \var{flowinfo} and \var{scopeid} represents
45\code{sin6_flowinfo} and \code{sin6_scope_id} member in
46\constant{struct sockaddr_in6} in C.
47For \module{socket} module methods, \var{flowinfo} and \var{scopeid}
48can be omitted just for backward compatibility. Note, however,
49omission of \var{scopeid} can cause problems in manipulating scoped
50IPv6 addresses. Other address families are currently not supported.
51The address format required by a particular socket object is
52automatically selected based on the address family specified when the
53socket object was created.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000054
Martin v. Löwisc9908c42001-08-04 22:22:45 +000055For IPv4 addresses, two special forms are accepted instead of a host
Fred Draked883ca11998-03-10 05:20:33 +000056address: the empty string represents \constant{INADDR_ANY}, and the string
Fred Drake318c0b11999-04-21 17:29:14 +000057\code{'<broadcast>'} represents \constant{INADDR_BROADCAST}.
Martin v. Löwisc9908c42001-08-04 22:22:45 +000058The behavior is not available for IPv6 for backward compatibility,
59therefore, you may want to avoid these if you intend to support IPv6 with
60your Python programs.
61
62If you use a hostname in the \var{host} portion of IPv4/v6 socket
63address, the program may show a nondeterministic behavior, as Python
64uses the first address returned from the DNS resolution. The socket
65address will be resolved differently into an actual IPv4/v6 address,
66depending on the results from DNS resolution and/or the host
67configuration. For deterministic behavior use a numeric address in
68\var{host} portion.
Guido van Rossume4f347e1997-05-09 02:21:51 +000069
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000070All errors raise exceptions. The normal exceptions for invalid
71argument types and out-of-memory conditions can be raised; errors
Fred Drake318c0b11999-04-21 17:29:14 +000072related to socket or address semantics raise the error
73\exception{socket.error}.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000074
Guido van Rossum11ba0942002-06-13 15:07:44 +000075Non-blocking mode is supported through
76\method{setblocking()}. A generalization of this based on timeouts
77is supported through \method{settimeout()}.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000078
Fred Draked883ca11998-03-10 05:20:33 +000079The module \module{socket} exports the following constants and functions:
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000080
Fred Draked883ca11998-03-10 05:20:33 +000081
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000082\begin{excdesc}{error}
Martin v. Löwisc9908c42001-08-04 22:22:45 +000083This exception is raised for socket-related errors.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000084The accompanying value is either a string telling what went wrong or a
85pair \code{(\var{errno}, \var{string})}
86representing an error returned by a system
Fred Drake318c0b11999-04-21 17:29:14 +000087call, similar to the value accompanying \exception{os.error}.
88See the module \refmodule{errno}\refbimodindex{errno}, which contains
Guido van Rossum8e1e68d1998-02-06 15:18:25 +000089names for the error codes defined by the underlying operating system.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000090\end{excdesc}
91
Martin v. Löwisc9908c42001-08-04 22:22:45 +000092\begin{excdesc}{herror}
93This exception is raised for address-related errors, i.e. for
Fred Drake87fa3aa2001-12-21 17:45:03 +000094functions that use \var{h_errno} in the C API, including
95\function{gethostbyname_ex()} and \function{gethostbyaddr()}.
Martin v. Löwisc9908c42001-08-04 22:22:45 +000096
97The accompanying value is a pair \code{(\var{h_errno}, \var{string})}
98representing an error returned by a library call. \var{string}
99represents the description of \var{h_errno}, as returned by
Fred Drake87fa3aa2001-12-21 17:45:03 +0000100the \cfunction{hstrerror()} C function.
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000101\end{excdesc}
102
103\begin{excdesc}{gaierror}
104This exception is raised for address-related errors, for
Fred Drake87fa3aa2001-12-21 17:45:03 +0000105\function{getaddrinfo()} and \function{getnameinfo()}.
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000106The accompanying value is a pair \code{(\var{error}, \var{string})}
107representing an error returned by a library call.
108\var{string} represents the description of \var{error}, as returned
Fred Drake87fa3aa2001-12-21 17:45:03 +0000109by the \cfunction{gai_strerror()} C function.
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000110\end{excdesc}
111
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000112\begin{datadesc}{AF_UNIX}
113\dataline{AF_INET}
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000114\dataline{AF_INET6}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000115These constants represent the address (and protocol) families,
Fred Draked883ca11998-03-10 05:20:33 +0000116used for the first argument to \function{socket()}. If the
117\constant{AF_UNIX} constant is not defined then this protocol is
118unsupported.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000119\end{datadesc}
120
121\begin{datadesc}{SOCK_STREAM}
122\dataline{SOCK_DGRAM}
Guido van Rossum781db5d1994-08-05 13:37:36 +0000123\dataline{SOCK_RAW}
124\dataline{SOCK_RDM}
125\dataline{SOCK_SEQPACKET}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000126These constants represent the socket types,
Fred Draked883ca11998-03-10 05:20:33 +0000127used for the second argument to \function{socket()}.
128(Only \constant{SOCK_STREAM} and
129\constant{SOCK_DGRAM} appear to be generally useful.)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000130\end{datadesc}
131
Guido van Rossumed2bad81995-02-16 16:29:18 +0000132\begin{datadesc}{SO_*}
133\dataline{SOMAXCONN}
134\dataline{MSG_*}
135\dataline{SOL_*}
136\dataline{IPPROTO_*}
137\dataline{IPPORT_*}
138\dataline{INADDR_*}
139\dataline{IP_*}
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000140\dataline{IPV6_*}
141\dataline{EAI_*}
142\dataline{AI_*}
143\dataline{NI_*}
Fred Drake39960f62001-12-22 19:07:58 +0000144\dataline{TCP_*}
Guido van Rossum6bb1adc1995-03-13 10:03:32 +0000145Many constants of these forms, documented in the \UNIX{} documentation on
Guido van Rossumed2bad81995-02-16 16:29:18 +0000146sockets and/or the IP protocol, are also defined in the socket module.
Fred Draked883ca11998-03-10 05:20:33 +0000147They are generally used in arguments to the \method{setsockopt()} and
148\method{getsockopt()} methods of socket objects. In most cases, only
Guido van Rossum6bb1adc1995-03-13 10:03:32 +0000149those symbols that are defined in the \UNIX{} header files are defined;
Guido van Rossumed2bad81995-02-16 16:29:18 +0000150for a few symbols, default values are provided.
151\end{datadesc}
152
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000153\begin{datadesc}{has_ipv6}
154This constant contains a boolean value which indicates if IPv6 is
155supported on this platform.
156\end{datadesc}
157
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000158\begin{funcdesc}{getaddrinfo}{host, port\optional{, family, socktype, proto, flags}}
159
160Resolves the \var{host}/\var{port} argument, into a sequence of
1615-tuples that contain all the necessary argument for the sockets
162manipulation. \var{host} is a domain name, a string representation of
163IPv4/v6 address or \code{None}.
164\var{port} is a string service name (like \code{``http''}), a numeric
165port number or \code{None}.
166
167The rest of the arguments are optional and must be numeric if
168specified. For \var{host} and \var{port}, by passing either an empty
169string or \code{None}, you can pass \code{NULL} to the C API. The
170\function{getaddrinfo()} function returns a list of 5-tuples with
171the following structure:
172
173\code{(\var{family}, \var{socktype}, \var{proto}, \var{canonname}, \var{sockaddr})}.
174
175\var{family}, \var{socktype}, \var{proto} are all integer and are meant to
176be passed to the \function{socket()} function.
177\var{canonname} is a string representing the canonical name of the \var{host}.
178It can be a numeric IPv4/v6 address when \code{AI_CANONNAME} is specified
179for a numeric \var{host}.
180\var{sockaddr} is a tuple describing a socket address, as described above.
181See \code{Lib/httplib.py} and other library files
182for a typical usage of the function.
183\versionadded{2.2}
184\end{funcdesc}
185
Fred Drake5772c862000-08-16 14:21:42 +0000186\begin{funcdesc}{getfqdn}{\optional{name}}
187Return a fully qualified domain name for \var{name}.
188If \var{name} is omitted or empty, it is interpreted as the local
189host. To find the fully qualified name, the hostname returned by
190\function{gethostbyaddr()} is checked, then aliases for the host, if
191available. The first name which includes a period is selected. In
192case no fully qualified domain name is available, the hostname is
193returned.
Fred Drake8b2e8f82000-09-06 02:22:16 +0000194\versionadded{2.0}
Fred Drake5772c862000-08-16 14:21:42 +0000195\end{funcdesc}
196
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000197\begin{funcdesc}{gethostbyname}{hostname}
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000198Translate a host name to IPv4 address format. The IPv4 address is
Fred Drake87fa3aa2001-12-21 17:45:03 +0000199returned as a string, such as \code{'100.50.200.5'}. If the host name
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000200is an IPv4 address itself it is returned unchanged. See
Fred Drake318c0b11999-04-21 17:29:14 +0000201\function{gethostbyname_ex()} for a more complete interface.
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000202\function{gethostbyname()} does not support IPv6 name resolution, and
203\function{getaddrinfo()} should be used instead for IPv4/v6 dual stack support.
Guido van Rossumcdf6af11998-08-07 18:07:36 +0000204\end{funcdesc}
205
206\begin{funcdesc}{gethostbyname_ex}{hostname}
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000207Translate a host name to IPv4 address format, extended interface.
Guido van Rossumcdf6af11998-08-07 18:07:36 +0000208Return a triple \code{(hostname, aliaslist, ipaddrlist)} where
209\code{hostname} is the primary host name responding to the given
210\var{ip_address}, \code{aliaslist} is a (possibly empty) list of
211alternative host names for the same address, and \code{ipaddrlist} is
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000212a list of IPv4 addresses for the same interface on the same
Guido van Rossumcdf6af11998-08-07 18:07:36 +0000213host (often but not always a single address).
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000214\function{gethostbyname_ex()} does not support IPv6 name resolution, and
215\function{getaddrinfo()} should be used instead for IPv4/v6 dual stack support.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000216\end{funcdesc}
217
Guido van Rossum781db5d1994-08-05 13:37:36 +0000218\begin{funcdesc}{gethostname}{}
Guido van Rossum16d6e711994-08-08 12:30:22 +0000219Return a string containing the hostname of the machine where
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000220the Python interpreter is currently executing.
221If you want to know the current machine's IP address, you may want to use
222\code{gethostbyname(gethostname())}.
223This operation assumes that there is a valid address-to-host mapping for
224the host, and the assumption does not always hold.
Fred Draked883ca11998-03-10 05:20:33 +0000225Note: \function{gethostname()} doesn't always return the fully qualified
226domain name; use \code{gethostbyaddr(gethostname())}
Guido van Rossumfe27a501997-01-11 17:04:56 +0000227(see below).
Guido van Rossum31cce971995-01-04 19:17:34 +0000228\end{funcdesc}
229
230\begin{funcdesc}{gethostbyaddr}{ip_address}
Fred Draked883ca11998-03-10 05:20:33 +0000231Return a triple \code{(\var{hostname}, \var{aliaslist},
232\var{ipaddrlist})} where \var{hostname} is the primary host name
233responding to the given \var{ip_address}, \var{aliaslist} is a
234(possibly empty) list of alternative host names for the same address,
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000235and \var{ipaddrlist} is a list of IPv4/v6 addresses for the same interface
Fred Draked883ca11998-03-10 05:20:33 +0000236on the same host (most likely containing only a single address).
Fred Drake5772c862000-08-16 14:21:42 +0000237To find the fully qualified domain name, use the function
238\function{getfqdn()}.
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000239\function{gethostbyaddr} supports both IPv4 and IPv6.
240\end{funcdesc}
241
242\begin{funcdesc}{getnameinfo}{sockaddr, flags}
243Translate a socket address \var{sockaddr} into a 2-tuple
244\code{(\var{host}, \var{port})}.
245Depending on the settings of \var{flags}, the result can contain a
246fully-qualified domain name or numeric address representation in
247\var{host}. Similarly, \var{port} can contain a string port name or a
248numeric port number.
249\versionadded{2.2}
Guido van Rossum781db5d1994-08-05 13:37:36 +0000250\end{funcdesc}
251
Guido van Rossum62ac99e1996-12-19 16:43:25 +0000252\begin{funcdesc}{getprotobyname}{protocolname}
Fred Drake87fa3aa2001-12-21 17:45:03 +0000253Translate an Internet protocol name (for example, \code{'icmp'}) to a constant
Guido van Rossum62ac99e1996-12-19 16:43:25 +0000254suitable for passing as the (optional) third argument to the
Fred Draked883ca11998-03-10 05:20:33 +0000255\function{socket()} function. This is usually only needed for sockets
256opened in ``raw'' mode (\constant{SOCK_RAW}); for the normal socket
257modes, the correct protocol is chosen automatically if the protocol is
Guido van Rossum62ac99e1996-12-19 16:43:25 +0000258omitted or zero.
259\end{funcdesc}
260
Fred Draked883ca11998-03-10 05:20:33 +0000261\begin{funcdesc}{getservbyname}{servicename, protocolname}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000262Translate an Internet service name and protocol name to a port number
263for that service. The protocol name should be \code{'tcp'} or
264\code{'udp'}.
265\end{funcdesc}
266
Fred Draked883ca11998-03-10 05:20:33 +0000267\begin{funcdesc}{socket}{family, type\optional{, proto}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000268Create a new socket using the given address family, socket type and
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000269protocol number. The address family should be \constant{AF_INET}, \constant{AF_INET6} or
Fred Draked883ca11998-03-10 05:20:33 +0000270\constant{AF_UNIX}. The socket type should be \constant{SOCK_STREAM},
271\constant{SOCK_DGRAM} or perhaps one of the other \samp{SOCK_} constants.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000272The protocol number is usually zero and may be omitted in that case.
273\end{funcdesc}
274
Jeremy Hyltoncb43c082001-10-11 16:17:22 +0000275\begin{funcdesc}{ssl}{sock\optional{, keyfile, certfile}}
Fred Drake9081bb12001-09-25 15:48:11 +0000276Initiate a SSL connection over the socket \var{sock}. \var{keyfile} is
277the name of a PEM formatted file that contains your private
278key. \var{certfile} is a PEM formatted certificate chain file. On
279success, a new \class{SSLObject} is returned.
280
Fred Drake0aa811c2001-10-20 04:24:09 +0000281\warning{This does not do any certificate verification!}
Fred Drake9081bb12001-09-25 15:48:11 +0000282\end{funcdesc}
283
Fred Draked883ca11998-03-10 05:20:33 +0000284\begin{funcdesc}{fromfd}{fd, family, type\optional{, proto}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000285Build a socket object from an existing file descriptor (an integer as
Fred Draked883ca11998-03-10 05:20:33 +0000286returned by a file object's \method{fileno()} method). Address family,
Fred Drake318c0b11999-04-21 17:29:14 +0000287socket type and protocol number are as for the \function{socket()} function
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000288above. The file descriptor should refer to a socket, but this is not
289checked --- subsequent operations on the object may fail if the file
290descriptor is invalid. This function is rarely needed, but can be
291used to get or set socket options on a socket passed to a program as
Fred Drake87fa3aa2001-12-21 17:45:03 +0000292standard input or output (such as a server started by the \UNIX{} inet
Guido van Rossum11ba0942002-06-13 15:07:44 +0000293daemon). The socket is assumed to be in blocking mode.
Fred Drake87fa3aa2001-12-21 17:45:03 +0000294Availability: \UNIX.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000295\end{funcdesc}
296
Guido van Rossumbda7ca71996-12-02 17:24:10 +0000297\begin{funcdesc}{ntohl}{x}
Fred Drakec5aec051997-12-08 21:25:41 +0000298Convert 32-bit integers from network to host byte order. On machines
299where the host byte order is the same as network byte order, this is a
300no-op; otherwise, it performs a 4-byte swap operation.
301\end{funcdesc}
302
303\begin{funcdesc}{ntohs}{x}
304Convert 16-bit integers from network to host byte order. On machines
305where the host byte order is the same as network byte order, this is a
306no-op; otherwise, it performs a 2-byte swap operation.
307\end{funcdesc}
308
309\begin{funcdesc}{htonl}{x}
310Convert 32-bit integers from host to network byte order. On machines
311where the host byte order is the same as network byte order, this is a
312no-op; otherwise, it performs a 4-byte swap operation.
313\end{funcdesc}
314
315\begin{funcdesc}{htons}{x}
316Convert 16-bit integers from host to network byte order. On machines
317where the host byte order is the same as network byte order, this is a
318no-op; otherwise, it performs a 2-byte swap operation.
Guido van Rossumbda7ca71996-12-02 17:24:10 +0000319\end{funcdesc}
320
Fred Drakee6fb1c41999-09-16 15:50:00 +0000321\begin{funcdesc}{inet_aton}{ip_string}
Fred Drake87fa3aa2001-12-21 17:45:03 +0000322Convert an IPv4 address from dotted-quad string format (for example,
323'123.45.67.89') to 32-bit packed binary format, as a string four
Fred Drakee6fb1c41999-09-16 15:50:00 +0000324characters in length.
325
326Useful when conversing with a program that uses the standard C library
327and needs objects of type \ctype{struct in_addr}, which is the C type
328for the 32-bit packed binary this function returns.
329
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000330If the IPv4 address string passed to this function is invalid,
Fred Drakee6fb1c41999-09-16 15:50:00 +0000331\exception{socket.error} will be raised. Note that exactly what is
332valid depends on the underlying C implementation of
333\cfunction{inet_aton()}.
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000334
Fred Drake39960f62001-12-22 19:07:58 +0000335\function{inet_aton()} does not support IPv6, and
336\function{getnameinfo()} should be used instead for IPv4/v6 dual stack
337support.
Fred Drakee6fb1c41999-09-16 15:50:00 +0000338\end{funcdesc}
339
340\begin{funcdesc}{inet_ntoa}{packed_ip}
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000341Convert a 32-bit packed IPv4 address (a string four characters in
Fred Drakee6fb1c41999-09-16 15:50:00 +0000342length) to its standard dotted-quad string representation
Fred Drake87fa3aa2001-12-21 17:45:03 +0000343(for example, '123.45.67.89').
Fred Drakee6fb1c41999-09-16 15:50:00 +0000344
345Useful when conversing with a program that uses the standard C library
346and needs objects of type \ctype{struct in_addr}, which is the C type
347for the 32-bit packed binary this function takes as an argument.
348
349If the string passed to this function is not exactly 4 bytes in
350length, \exception{socket.error} will be raised.
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000351
Fred Drake39960f62001-12-22 19:07:58 +0000352\function{inet_ntoa()} does not support IPv6, and
353\function{getnameinfo()} should be used instead for IPv4/v6 dual stack
354support.
Fred Drakee6fb1c41999-09-16 15:50:00 +0000355\end{funcdesc}
356
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000357\begin{funcdesc}{inet_pton}{address_family, ip_string}
358Convert an IP address from its family-specific string format to a packed,
359binary format.
360
361Supported values for address_family are currently \constant{AF_INET}
362and \constant{AF_INET6}.
363
364\function{inet_pton()} is useful when a library or network protocol calls for
365an object of type \ctype{struct in_addr} (similar to \function{inet_aton()})
366or \ctype{struct in6_addr}.
367
368If the IP address string passed to this function is invalid,
369\exception{socket.error} will be raised. Note that exactly what is valid
370depends on both the value of \var{address_family} and the underlying
371implementation of \cfunction{inet_pton()}.
372\versionadded{2.3}
373\end{funcdesc}
374
375\begin{funcdesc}{inet_ntop}{address_family, packed_ip}
376Convert a packed IP address (a string of some number of characters) to its
377standard, family-specific string representation (for example, '7.10.0.5' or
378'5aef:2b::8')
379
380Supported values for address_family are currently \constant{AF_INET}
381and \constant{AF_INET6}.
382
383\function{inet_pton()} is useful when a library or network protocol calls for
384an object of type \ctype{struct in_addr} (similar to \function{inet_aton()})
385or \ctype{struct in6_addr}.
386
387If the string passed to this function is not the correct length for the
388specified address family, \exception{ValueError} will be raised.
389A \exception{socket.error} is raised for errors from the call to
390\function{inet_ntop()}.
391\versionadded{2.3}
392\end{funcdesc}
393
Skip Montanaro2a403e82003-03-20 17:58:12 +0000394\begin{funcdesc}{getdefaulttimeout}{}
395Return the default timeout in floating seconds for new socket objects.
396A value of \code{None} indicates that new socket objects have no timeout.
397When the socket module is first imported, the default is \code{None}.
398\versionadded{2.3}
399\end{funcdesc}
400
401\begin{funcdesc}{setdefaulttimeout}{timeout}
402Set the default timeout in floating seconds for new socket objects.
403A value of \code{None} indicates that new socket objects have no timeout.
404When the socket module is first imported, the default is \code{None}.
405\versionadded{2.3}
406\end{funcdesc}
407
Fred Drake5451d671997-10-13 21:31:02 +0000408\begin{datadesc}{SocketType}
Guido van Rossum2335c5e1997-05-21 14:41:42 +0000409This is a Python type object that represents the socket object type.
Fred Draked883ca11998-03-10 05:20:33 +0000410It is the same as \code{type(socket(...))}.
Guido van Rossum2335c5e1997-05-21 14:41:42 +0000411\end{datadesc}
412
Fred Drakeaa7524c2000-07-06 18:37:08 +0000413
414\begin{seealso}
415 \seemodule{SocketServer}{Classes that simplify writing network servers.}
416\end{seealso}
417
418
Fred Drakea94f6761999-08-05 13:41:04 +0000419\subsection{Socket Objects \label{socket-objects}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000420
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000421Socket objects have the following methods. Except for
Fred Draked883ca11998-03-10 05:20:33 +0000422\method{makefile()} these correspond to \UNIX{} system calls
423applicable to sockets.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000424
Fred Drake3f1c4721998-04-03 07:04:45 +0000425\begin{methoddesc}[socket]{accept}{}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000426Accept a connection.
427The socket must be bound to an address and listening for connections.
428The return value is a pair \code{(\var{conn}, \var{address})}
429where \var{conn} is a \emph{new} socket object usable to send and
430receive data on the connection, and \var{address} is the address bound
431to the socket on the other end of the connection.
Fred Drake3f1c4721998-04-03 07:04:45 +0000432\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000433
Fred Drake3f1c4721998-04-03 07:04:45 +0000434\begin{methoddesc}[socket]{bind}{address}
Guido van Rossuma84ec511994-06-23 12:13:52 +0000435Bind the socket to \var{address}. The socket must not already be bound.
Fred Drake7d686902000-04-04 17:48:30 +0000436(The format of \var{address} depends on the address family --- see
Fred Drake0aa811c2001-10-20 04:24:09 +0000437above.) \note{This method has historically accepted a pair
Fred Drake7d686902000-04-04 17:48:30 +0000438of parameters for \constant{AF_INET} addresses instead of only a
Eric S. Raymond83210262001-01-10 19:34:52 +0000439tuple. This was never intentional and is no longer be available in
Fred Drake0aa811c2001-10-20 04:24:09 +0000440Python 2.0.}
Fred Drake3f1c4721998-04-03 07:04:45 +0000441\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000442
Fred Drake3f1c4721998-04-03 07:04:45 +0000443\begin{methoddesc}[socket]{close}{}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000444Close the socket. All future operations on the socket object will fail.
445The remote end will receive no more data (after queued data is flushed).
446Sockets are automatically closed when they are garbage-collected.
Fred Drake3f1c4721998-04-03 07:04:45 +0000447\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000448
Fred Drake3f1c4721998-04-03 07:04:45 +0000449\begin{methoddesc}[socket]{connect}{address}
Guido van Rossuma84ec511994-06-23 12:13:52 +0000450Connect to a remote socket at \var{address}.
Fred Draked883ca11998-03-10 05:20:33 +0000451(The format of \var{address} depends on the address family --- see
Fred Drake0aa811c2001-10-20 04:24:09 +0000452above.) \note{This method has historically accepted a pair
Fred Drake7d686902000-04-04 17:48:30 +0000453of parameters for \constant{AF_INET} addresses instead of only a
Eric S. Raymond83210262001-01-10 19:34:52 +0000454tuple. This was never intentional and is no longer available in
Fred Drake0aa811c2001-10-20 04:24:09 +0000455Python 2.0 and later.}
Fred Drake3f1c4721998-04-03 07:04:45 +0000456\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000457
Fred Drake3f1c4721998-04-03 07:04:45 +0000458\begin{methoddesc}[socket]{connect_ex}{address}
Guido van Rossumeefcba61997-12-09 19:47:24 +0000459Like \code{connect(\var{address})}, but return an error indicator
Fred Drakeb0bc7f21999-05-06 22:03:50 +0000460instead of raising an exception for errors returned by the C-level
461\cfunction{connect()} call (other problems, such as ``host not found,''
462can still raise exceptions). The error indicator is \code{0} if the
Fred Draked883ca11998-03-10 05:20:33 +0000463operation succeeded, otherwise the value of the \cdata{errno}
Fred Drake87fa3aa2001-12-21 17:45:03 +0000464variable. This is useful to support, for example, asynchronous connects.
Fred Drake0aa811c2001-10-20 04:24:09 +0000465\note{This method has historically accepted a pair of
Fred Drake7d686902000-04-04 17:48:30 +0000466parameters for \constant{AF_INET} addresses instead of only a tuple.
Eric S. Raymond83210262001-01-10 19:34:52 +0000467This was never intentional and is no longer be available in Python
Fred Drake0aa811c2001-10-20 04:24:09 +00004682.0 and later.}
Fred Drake3f1c4721998-04-03 07:04:45 +0000469\end{methoddesc}
Guido van Rossumf7790c61997-11-18 15:29:20 +0000470
Fred Drake3f1c4721998-04-03 07:04:45 +0000471\begin{methoddesc}[socket]{fileno}{}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000472Return the socket's file descriptor (a small integer). This is useful
Fred Draked883ca11998-03-10 05:20:33 +0000473with \function{select.select()}.
Fred Drake3f1c4721998-04-03 07:04:45 +0000474\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000475
Fred Drake3f1c4721998-04-03 07:04:45 +0000476\begin{methoddesc}[socket]{getpeername}{}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000477Return the remote address to which the socket is connected. This is
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000478useful to find out the port number of a remote IPv4/v6 socket, for instance.
Guido van Rossum86751151995-02-28 17:14:32 +0000479(The format of the address returned depends on the address family ---
Guido van Rossum781db5d1994-08-05 13:37:36 +0000480see above.) On some systems this function is not supported.
Fred Drake3f1c4721998-04-03 07:04:45 +0000481\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000482
Fred Drake3f1c4721998-04-03 07:04:45 +0000483\begin{methoddesc}[socket]{getsockname}{}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000484Return the socket's own address. This is useful to find out the port
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000485number of an IPv4/v6 socket, for instance.
Guido van Rossum86751151995-02-28 17:14:32 +0000486(The format of the address returned depends on the address family ---
Guido van Rossuma84ec511994-06-23 12:13:52 +0000487see above.)
Fred Drake3f1c4721998-04-03 07:04:45 +0000488\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000489
Fred Drake3f1c4721998-04-03 07:04:45 +0000490\begin{methoddesc}[socket]{getsockopt}{level, optname\optional{, buflen}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000491Return the value of the given socket option (see the \UNIX{} man page
Fred Draked883ca11998-03-10 05:20:33 +0000492\manpage{getsockopt}{2}). The needed symbolic constants
493(\constant{SO_*} etc.) are defined in this module. If \var{buflen}
Guido van Rossum470be141995-03-17 16:07:09 +0000494is absent, an integer option is assumed and its integer value
Guido van Rossum8df36371995-02-27 17:52:15 +0000495is returned by the function. If \var{buflen} is present, it specifies
496the maximum length of the buffer used to receive the option in, and
Guido van Rossum470be141995-03-17 16:07:09 +0000497this buffer is returned as a string. It is up to the caller to decode
Guido van Rossum8df36371995-02-27 17:52:15 +0000498the contents of the buffer (see the optional built-in module
Fred Drake318c0b11999-04-21 17:29:14 +0000499\refmodule{struct} for a way to decode C structures encoded as strings).
Fred Drake3f1c4721998-04-03 07:04:45 +0000500\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000501
Fred Drake3f1c4721998-04-03 07:04:45 +0000502\begin{methoddesc}[socket]{listen}{backlog}
Guido van Rossum470be141995-03-17 16:07:09 +0000503Listen for connections made to the socket. The \var{backlog} argument
504specifies the maximum number of queued connections and should be at
505least 1; the maximum value is system-dependent (usually 5).
Fred Drake3f1c4721998-04-03 07:04:45 +0000506\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000507
Fred Drake3f1c4721998-04-03 07:04:45 +0000508\begin{methoddesc}[socket]{makefile}{\optional{mode\optional{, bufsize}}}
Guido van Rossum470be141995-03-17 16:07:09 +0000509Return a \dfn{file object} associated with the socket. (File objects
Fred Drakea94f6761999-08-05 13:41:04 +0000510are described in \ref{bltin-file-objects}, ``File Objects.'')
Fred Draked883ca11998-03-10 05:20:33 +0000511The file object references a \cfunction{dup()}ped version of the
512socket file descriptor, so the file object and socket object may be
Fred Drakea94f6761999-08-05 13:41:04 +0000513closed or garbage-collected independently.
Guido van Rossum715b8612002-06-07 12:38:23 +0000514The socket should be in blocking mode.
Fred Drakea94f6761999-08-05 13:41:04 +0000515\index{I/O control!buffering}The optional \var{mode}
Fred Draked883ca11998-03-10 05:20:33 +0000516and \var{bufsize} arguments are interpreted the same way as by the
Fred Drakeaad8bb52001-10-19 17:22:29 +0000517built-in \function{file()} function; see ``Built-in Functions''
518(section \ref{built-in-funcs}) for more information.
Fred Drake3f1c4721998-04-03 07:04:45 +0000519\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000520
Fred Drake3f1c4721998-04-03 07:04:45 +0000521\begin{methoddesc}[socket]{recv}{bufsize\optional{, flags}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000522Receive data from the socket. The return value is a string representing
523the data received. The maximum amount of data to be received
524at once is specified by \var{bufsize}. See the \UNIX{} manual page
Fred Draked883ca11998-03-10 05:20:33 +0000525\manpage{recv}{2} for the meaning of the optional argument
526\var{flags}; it defaults to zero.
Fred Drake3f1c4721998-04-03 07:04:45 +0000527\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000528
Fred Drake3f1c4721998-04-03 07:04:45 +0000529\begin{methoddesc}[socket]{recvfrom}{bufsize\optional{, flags}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000530Receive data from the socket. The return value is a pair
531\code{(\var{string}, \var{address})} where \var{string} is a string
532representing the data received and \var{address} is the address of the
Guido van Rossum470be141995-03-17 16:07:09 +0000533socket sending the data. The optional \var{flags} argument has the
Fred Draked883ca11998-03-10 05:20:33 +0000534same meaning as for \method{recv()} above.
Guido van Rossum86751151995-02-28 17:14:32 +0000535(The format of \var{address} depends on the address family --- see above.)
Fred Drake3f1c4721998-04-03 07:04:45 +0000536\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000537
Fred Drake3f1c4721998-04-03 07:04:45 +0000538\begin{methoddesc}[socket]{send}{string\optional{, flags}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000539Send data to the socket. The socket must be connected to a remote
Guido van Rossum470be141995-03-17 16:07:09 +0000540socket. The optional \var{flags} argument has the same meaning as for
Fred Draked883ca11998-03-10 05:20:33 +0000541\method{recv()} above. Returns the number of bytes sent.
Fred Drake39368c12001-12-05 05:25:59 +0000542Applications are responsible for checking that all data has been sent;
543if only some of the data was transmitted, the application needs to
544attempt delivery of the remaining data.
545\end{methoddesc}
546
547\begin{methoddesc}[socket]{sendall}{string\optional{, flags}}
548Send data to the socket. The socket must be connected to a remote
549socket. The optional \var{flags} argument has the same meaning as for
550\method{recv()} above. Unlike \method{send()}, this method continues
551to send data from \var{string} until either all data has been sent or
552an error occurs. \code{None} is returned on success. On error, an
553exception is raised, and there is no way to determine how much data,
554if any, was successfully sent.
Fred Drake3f1c4721998-04-03 07:04:45 +0000555\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000556
Fred Drake3f1c4721998-04-03 07:04:45 +0000557\begin{methoddesc}[socket]{sendto}{string\optional{, flags}, address}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000558Send data to the socket. The socket should not be connected to a
559remote socket, since the destination socket is specified by
Fred Draked883ca11998-03-10 05:20:33 +0000560\var{address}. The optional \var{flags} argument has the same
561meaning as for \method{recv()} above. Return the number of bytes sent.
Guido van Rossum86751151995-02-28 17:14:32 +0000562(The format of \var{address} depends on the address family --- see above.)
Fred Drake3f1c4721998-04-03 07:04:45 +0000563\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000564
Fred Drake3f1c4721998-04-03 07:04:45 +0000565\begin{methoddesc}[socket]{setblocking}{flag}
Guido van Rossum91951481994-09-07 14:39:14 +0000566Set blocking or non-blocking mode of the socket: if \var{flag} is 0,
567the socket is set to non-blocking, else to blocking mode. Initially
568all sockets are in blocking mode. In non-blocking mode, if a
Fred Drake318c0b11999-04-21 17:29:14 +0000569\method{recv()} call doesn't find any data, or if a
570\method{send()} call can't immediately dispose of the data, a
571\exception{error} exception is raised; in blocking mode, the calls
572block until they can proceed.
Guido van Rossum11ba0942002-06-13 15:07:44 +0000573\code{s.setblocking(0)} is equivalent to \code{s.settimeout(0)};
574\code{s.setblocking(1)} is equivalent to \code{s.settimeout(None)}.
Fred Drake3f1c4721998-04-03 07:04:45 +0000575\end{methoddesc}
Guido van Rossum91951481994-09-07 14:39:14 +0000576
Guido van Rossumbe946bf2002-06-06 21:51:01 +0000577\begin{methoddesc}[socket]{settimeout}{value}
Guido van Rossum11ba0942002-06-13 15:07:44 +0000578Set a timeout on blocking socket operations. The \var{value} argument
579can be a nonnegative float expressing seconds, or \code{None}.
580If a float is
Neal Norwitz62a7f632002-06-07 12:36:44 +0000581given, subsequent socket operations will raise an \exception{error}
Guido van Rossumfc9823b2002-06-07 03:39:21 +0000582exception if the timeout period \var{value} has elapsed before the
583operation has completed. Setting a timeout of \code{None} disables
584timeouts on socket operations.
Guido van Rossum11ba0942002-06-13 15:07:44 +0000585\code{s.settimeout(0.0)} is equivalent to \code{s.blocking(0)};
586\code{s.settimeout(None)} is equivalent to \code{s.setblocking(1)}.
Neal Norwitzbdbd84f2002-06-06 22:24:10 +0000587\versionadded{2.3}
Guido van Rossumbe946bf2002-06-06 21:51:01 +0000588\end{methoddesc}
589
590\begin{methoddesc}[socket]{gettimeout}{}
Fred Drake6c6d6622002-06-06 21:57:48 +0000591Returns the timeout in floating seconds associated with socket
Guido van Rossum11ba0942002-06-13 15:07:44 +0000592operations, or \code{None} if no timeout is set. This reflects
593the last call to \method{setblocking()} or \method{settimeout()}.
Neal Norwitzbdbd84f2002-06-06 22:24:10 +0000594\versionadded{2.3}
Guido van Rossumbe946bf2002-06-06 21:51:01 +0000595\end{methoddesc}
596
Guido van Rossum11ba0942002-06-13 15:07:44 +0000597Some notes on socket blocking and timeouts: A socket object can be in
598one of three modes: blocking, non-blocking, or timout. Sockets are
599always created in blocking mode. In blocking mode, operations block
600until complete. In non-blocking mode, operations fail (with an error
601that is unfortunately system-dependent) if they cannot be completed
602immediately. In timeout mode, operations fail if they cannot be
603completed within the timeout specified for the socket. The
604\method{setblocking()} method is simply a shorthand for certain
605\method{settimeout()} calls.
Guido van Rossumbe946bf2002-06-06 21:51:01 +0000606
Guido van Rossum715b8612002-06-07 12:38:23 +0000607Timeout mode internally sets the socket in non-blocking mode. The
608blocking and timeout modes are shared between file descriptors and
609socket objects that refer to the same network endpoint. A consequence
610of this is that file objects returned by the \method{makefile()}
611method should only be used when the socket is in blocking mode; in
612timeout or non-blocking mode file operations that cannot be completed
613immediately will fail.
614
Fred Drake3f1c4721998-04-03 07:04:45 +0000615\begin{methoddesc}[socket]{setsockopt}{level, optname, value}
Fred Drake9a748aa2000-06-30 04:21:41 +0000616Set the value of the given socket option (see the \UNIX{} manual page
Fred Draked883ca11998-03-10 05:20:33 +0000617\manpage{setsockopt}{2}). The needed symbolic constants are defined in
618the \module{socket} module (\code{SO_*} etc.). The value can be an
Guido van Rossum8df36371995-02-27 17:52:15 +0000619integer or a string representing a buffer. In the latter case it is
620up to the caller to ensure that the string contains the proper bits
621(see the optional built-in module
Fred Drake318c0b11999-04-21 17:29:14 +0000622\refmodule{struct}\refbimodindex{struct} for a way to encode C
623structures as strings).
Fred Drake3f1c4721998-04-03 07:04:45 +0000624\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000625
Fred Drake3f1c4721998-04-03 07:04:45 +0000626\begin{methoddesc}[socket]{shutdown}{how}
Fred Draked883ca11998-03-10 05:20:33 +0000627Shut down one or both halves of the connection. If \var{how} is
628\code{0}, further receives are disallowed. If \var{how} is \code{1},
629further sends are disallowed. If \var{how} is \code{2}, further sends
630and receives are disallowed.
Fred Drake3f1c4721998-04-03 07:04:45 +0000631\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000632
Fred Draked883ca11998-03-10 05:20:33 +0000633Note that there are no methods \method{read()} or \method{write()};
634use \method{recv()} and \method{send()} without \var{flags} argument
635instead.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000636
Fred Drakeaa7524c2000-07-06 18:37:08 +0000637
Fred Drake9081bb12001-09-25 15:48:11 +0000638\subsection{SSL Objects \label{ssl-objects}}
639
640SSL objects have the following methods.
641
642\begin{methoddesc}{write}{s}
643Writes the string \var{s} to the on the object's SSL connection.
644The return value is the number of bytes written.
645\end{methoddesc}
646
647\begin{methoddesc}{read}{\optional{n}}
648If \var{n} is provided, read \var{n} bytes from the SSL connection, otherwise
649read until EOF. The return value is a string of the bytes read.
650\end{methoddesc}
651
Fred Drakeaa7524c2000-07-06 18:37:08 +0000652\subsection{Example \label{socket-example}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000653
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000654Here are four minimal example programs using the TCP/IP protocol:\ a
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000655server that echoes all data that it receives back (servicing only one
656client), and a client using it. Note that a server must perform the
Fred Draked883ca11998-03-10 05:20:33 +0000657sequence \function{socket()}, \method{bind()}, \method{listen()},
658\method{accept()} (possibly repeating the \method{accept()} to service
659more than one client), while a client only needs the sequence
660\function{socket()}, \method{connect()}. Also note that the server
661does not \method{send()}/\method{recv()} on the
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000662socket it is listening on but on the new socket returned by
Fred Draked883ca11998-03-10 05:20:33 +0000663\method{accept()}.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000664
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000665The first two examples support IPv4 only.
666
Fred Drake19479911998-02-13 06:58:54 +0000667\begin{verbatim}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000668# Echo server program
Fred Drakeef52f602000-10-10 20:36:29 +0000669import socket
670
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000671HOST = '' # Symbolic name meaning the local host
Fred Drakeef52f602000-10-10 20:36:29 +0000672PORT = 50007 # Arbitrary non-privileged port
673s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Fred Drake3d69c0e2000-05-03 19:40:32 +0000674s.bind((HOST, PORT))
Guido van Rossum5da57551994-03-02 10:52:16 +0000675s.listen(1)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000676conn, addr = s.accept()
677print 'Connected by', addr
678while 1:
679 data = conn.recv(1024)
680 if not data: break
681 conn.send(data)
682conn.close()
Fred Drake19479911998-02-13 06:58:54 +0000683\end{verbatim}
Fred Draked883ca11998-03-10 05:20:33 +0000684
Fred Drake19479911998-02-13 06:58:54 +0000685\begin{verbatim}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000686# Echo client program
Fred Drakeef52f602000-10-10 20:36:29 +0000687import socket
688
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000689HOST = 'daring.cwi.nl' # The remote host
690PORT = 50007 # The same port as used by the server
Fred Drakeef52f602000-10-10 20:36:29 +0000691s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Fred Drake3d69c0e2000-05-03 19:40:32 +0000692s.connect((HOST, PORT))
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000693s.send('Hello, world')
694data = s.recv(1024)
695s.close()
696print 'Received', `data`
Fred Drake19479911998-02-13 06:58:54 +0000697\end{verbatim}
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000698
699The next two examples are identical to the above two, but support both
700IPv4 and IPv6.
701The server side will listen to the first address family available
702(it should listen to both instead).
703On most of IPv6-ready systems, IPv6 will take precedence
704and the server may not accept IPv4 traffic.
705The client side will try to connect to the all addresses returned as a result
706of the name resolution, and sends traffic to the first one connected
707successfully.
708
709\begin{verbatim}
710# Echo server program
711import socket
712import sys
713
714HOST = '' # Symbolic name meaning the local host
715PORT = 50007 # Arbitrary non-privileged port
716s = None
717for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
718 af, socktype, proto, canonname, sa = res
719 try:
720 s = socket.socket(af, socktype, proto)
721 except socket.error, msg:
722 s = None
723 continue
724 try:
725 s.bind(sa)
726 s.listen(1)
727 except socket.error, msg:
728 s.close()
729 s = None
730 continue
731 break
732if s is None:
733 print 'could not open socket'
734 sys.exit(1)
735conn, addr = s.accept()
736print 'Connected by', addr
737while 1:
738 data = conn.recv(1024)
739 if not data: break
740 conn.send(data)
741conn.close()
742\end{verbatim}
743
744\begin{verbatim}
745# Echo client program
746import socket
747import sys
748
749HOST = 'daring.cwi.nl' # The remote host
750PORT = 50007 # The same port as used by the server
751s = None
752for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM):
753 af, socktype, proto, canonname, sa = res
754 try:
755 s = socket.socket(af, socktype, proto)
756 except socket.error, msg:
757 s = None
758 continue
759 try:
760 s.connect(sa)
761 except socket.error, msg:
762 s.close()
763 s = None
764 continue
765 break
766if s is None:
767 print 'could not open socket'
768 sys.exit(1)
769s.send('Hello, world')
770data = s.recv(1024)
771s.close()
772print 'Received', `data`
773\end{verbatim}