blob: e3fce23c7c0cf889be5db70dc36f3a9066f0b7ce [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,
Neal Norwitzd157b1d2005-10-03 00:44:06 +000010OS/2, and probably additional platforms. \note{Some behavior may be
11platform dependent, since calls are made to the operating system socket APIs.}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000012
13For an introduction to socket programming (in C), see the following
Fred Drake37f15741999-11-10 16:21:37 +000014papers: \citetitle{An Introductory 4.3BSD Interprocess Communication
15Tutorial}, by Stuart Sechrest and \citetitle{An Advanced 4.3BSD
16Interprocess Communication Tutorial}, by Samuel J. Leffler et al,
Guido van Rossumd8faa362007-04-27 19:54:29 +000017both in the \citetitle{UNIX Programmer's Manual, Supplementary Documents 1}
Fred Drake38e5d272000-04-03 20:13:55 +000018(sections PS1:7 and PS1:8). The platform-specific reference material
19for the various socket-related system calls are also a valuable source
20of information on the details of socket semantics. For \UNIX, refer
21to the manual pages; for Windows, see the WinSock (or Winsock 2)
22specification.
Fred Drake3fc291a2001-09-27 04:17:20 +000023For IPv6-ready APIs, readers may want to refer to \rfc{2553} titled
24\citetitle{Basic Socket Interface Extensions for IPv6}.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000025
26The Python interface is a straightforward transliteration of the
27\UNIX{} system call and library interface for sockets to Python's
Fred Draked883ca11998-03-10 05:20:33 +000028object-oriented style: the \function{socket()} function returns a
Fred Drake318c0b11999-04-21 17:29:14 +000029\dfn{socket object}\obindex{socket} whose methods implement the
30various socket system calls. Parameter types are somewhat
31higher-level than in the C interface: as with \method{read()} and
32\method{write()} operations on Python files, buffer allocation on
33receive operations is automatic, and buffer length is implicit on send
34operations.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000035
Martin v. Löwisc9908c42001-08-04 22:22:45 +000036Socket addresses are represented as follows:
37A single string is used for the \constant{AF_UNIX} address family.
38A pair \code{(\var{host}, \var{port})} is used for the
39\constant{AF_INET} address family, where \var{host} is a string
40representing either a hostname in Internet domain notation like
41\code{'daring.cwi.nl'} or an IPv4 address like \code{'100.50.200.5'},
42and \var{port} is an integral port number.
43For \constant{AF_INET6} address family, a four-tuple
44\code{(\var{host}, \var{port}, \var{flowinfo}, \var{scopeid})} is
45used, where \var{flowinfo} and \var{scopeid} represents
46\code{sin6_flowinfo} and \code{sin6_scope_id} member in
47\constant{struct sockaddr_in6} in C.
48For \module{socket} module methods, \var{flowinfo} and \var{scopeid}
49can be omitted just for backward compatibility. Note, however,
50omission of \var{scopeid} can cause problems in manipulating scoped
51IPv6 addresses. Other address families are currently not supported.
52The address format required by a particular socket object is
53automatically selected based on the address family specified when the
54socket object was created.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000055
Martin v. Löwisc9908c42001-08-04 22:22:45 +000056For IPv4 addresses, two special forms are accepted instead of a host
Fred Draked883ca11998-03-10 05:20:33 +000057address: the empty string represents \constant{INADDR_ANY}, and the string
Fred Drake318c0b11999-04-21 17:29:14 +000058\code{'<broadcast>'} represents \constant{INADDR_BROADCAST}.
Martin v. Löwisc9908c42001-08-04 22:22:45 +000059The behavior is not available for IPv6 for backward compatibility,
60therefore, you may want to avoid these if you intend to support IPv6 with
61your Python programs.
62
63If you use a hostname in the \var{host} portion of IPv4/v6 socket
64address, the program may show a nondeterministic behavior, as Python
65uses the first address returned from the DNS resolution. The socket
66address will be resolved differently into an actual IPv4/v6 address,
67depending on the results from DNS resolution and/or the host
68configuration. For deterministic behavior use a numeric address in
69\var{host} portion.
Guido van Rossume4f347e1997-05-09 02:21:51 +000070
Georg Brandla635fbb2006-01-15 07:55:35 +000071\versionadded[AF_NETLINK sockets are represented as
72pairs \code{\var{pid}, \var{groups}}]{2.5}
Martin v. Löwis11017b12006-01-14 18:12:57 +000073
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000074All errors raise exceptions. The normal exceptions for invalid
75argument types and out-of-memory conditions can be raised; errors
Fred Drake318c0b11999-04-21 17:29:14 +000076related to socket or address semantics raise the error
77\exception{socket.error}.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000078
Guido van Rossum11ba0942002-06-13 15:07:44 +000079Non-blocking mode is supported through
80\method{setblocking()}. A generalization of this based on timeouts
81is supported through \method{settimeout()}.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000082
Fred Draked883ca11998-03-10 05:20:33 +000083The module \module{socket} exports the following constants and functions:
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000084
Fred Draked883ca11998-03-10 05:20:33 +000085
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000086\begin{excdesc}{error}
Martin v. Löwisc9908c42001-08-04 22:22:45 +000087This exception is raised for socket-related errors.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000088The accompanying value is either a string telling what went wrong or a
89pair \code{(\var{errno}, \var{string})}
90representing an error returned by a system
Fred Drake318c0b11999-04-21 17:29:14 +000091call, similar to the value accompanying \exception{os.error}.
92See the module \refmodule{errno}\refbimodindex{errno}, which contains
Guido van Rossum8e1e68d1998-02-06 15:18:25 +000093names for the error codes defined by the underlying operating system.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000094\end{excdesc}
95
Martin v. Löwisc9908c42001-08-04 22:22:45 +000096\begin{excdesc}{herror}
97This exception is raised for address-related errors, i.e. for
Fred Drake87fa3aa2001-12-21 17:45:03 +000098functions that use \var{h_errno} in the C API, including
99\function{gethostbyname_ex()} and \function{gethostbyaddr()}.
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000100
101The accompanying value is a pair \code{(\var{h_errno}, \var{string})}
102representing an error returned by a library call. \var{string}
103represents the description of \var{h_errno}, as returned by
Fred Drake87fa3aa2001-12-21 17:45:03 +0000104the \cfunction{hstrerror()} C function.
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000105\end{excdesc}
106
107\begin{excdesc}{gaierror}
108This exception is raised for address-related errors, for
Fred Drake87fa3aa2001-12-21 17:45:03 +0000109\function{getaddrinfo()} and \function{getnameinfo()}.
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000110The accompanying value is a pair \code{(\var{error}, \var{string})}
111representing an error returned by a library call.
112\var{string} represents the description of \var{error}, as returned
Fred Drake87fa3aa2001-12-21 17:45:03 +0000113by the \cfunction{gai_strerror()} C function.
Fred Drakecee88792004-05-05 04:18:11 +0000114The \var{error} value will match one of the \constant{EAI_*} constants
115defined in this module.
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000116\end{excdesc}
117
Raymond Hettingerbe2528d2003-06-29 04:55:59 +0000118\begin{excdesc}{timeout}
119This exception is raised when a timeout occurs on a socket which has
120had timeouts enabled via a prior call to \method{settimeout()}. The
121accompanying value is a string whose value is currently always ``timed
122out''.
123\versionadded{2.3}
124\end{excdesc}
125
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000126\begin{datadesc}{AF_UNIX}
127\dataline{AF_INET}
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000128\dataline{AF_INET6}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000129These constants represent the address (and protocol) families,
Fred Draked883ca11998-03-10 05:20:33 +0000130used for the first argument to \function{socket()}. If the
131\constant{AF_UNIX} constant is not defined then this protocol is
132unsupported.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000133\end{datadesc}
134
135\begin{datadesc}{SOCK_STREAM}
136\dataline{SOCK_DGRAM}
Guido van Rossum781db5d1994-08-05 13:37:36 +0000137\dataline{SOCK_RAW}
138\dataline{SOCK_RDM}
139\dataline{SOCK_SEQPACKET}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000140These constants represent the socket types,
Fred Draked883ca11998-03-10 05:20:33 +0000141used for the second argument to \function{socket()}.
142(Only \constant{SOCK_STREAM} and
143\constant{SOCK_DGRAM} appear to be generally useful.)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000144\end{datadesc}
145
Guido van Rossumed2bad81995-02-16 16:29:18 +0000146\begin{datadesc}{SO_*}
147\dataline{SOMAXCONN}
148\dataline{MSG_*}
149\dataline{SOL_*}
150\dataline{IPPROTO_*}
151\dataline{IPPORT_*}
152\dataline{INADDR_*}
153\dataline{IP_*}
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000154\dataline{IPV6_*}
155\dataline{EAI_*}
156\dataline{AI_*}
157\dataline{NI_*}
Fred Drake39960f62001-12-22 19:07:58 +0000158\dataline{TCP_*}
Guido van Rossum6bb1adc1995-03-13 10:03:32 +0000159Many constants of these forms, documented in the \UNIX{} documentation on
Guido van Rossumed2bad81995-02-16 16:29:18 +0000160sockets and/or the IP protocol, are also defined in the socket module.
Fred Draked883ca11998-03-10 05:20:33 +0000161They are generally used in arguments to the \method{setsockopt()} and
162\method{getsockopt()} methods of socket objects. In most cases, only
Guido van Rossum6bb1adc1995-03-13 10:03:32 +0000163those symbols that are defined in the \UNIX{} header files are defined;
Guido van Rossumed2bad81995-02-16 16:29:18 +0000164for a few symbols, default values are provided.
165\end{datadesc}
166
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000167\begin{datadesc}{has_ipv6}
168This constant contains a boolean value which indicates if IPv6 is
169supported on this platform.
Neal Norwitz6eb502f2003-04-25 14:53:48 +0000170\versionadded{2.3}
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000171\end{datadesc}
172
Guido van Rossumd8faa362007-04-27 19:54:29 +0000173\begin{funcdesc}{create_connection}{address\optional{, timeout}}
174Connects to the \var{address} received (as usual, a \code{(host, port)}
175pair), with an optional timeout for the connection. Specially useful for
176higher-level protocols, it is not normally used directly from
177application-level code. Passing the optional \var{timeout} parameter
178will set the timeout on the socket instance (if it is not given or
179\code{None}, the global default timeout setting is used).
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000180\versionadded{2.6}
Guido van Rossumd8faa362007-04-27 19:54:29 +0000181\end{funcdesc}
182
Fred Draked198f382003-04-25 16:16:02 +0000183\begin{funcdesc}{getaddrinfo}{host, port\optional{, family\optional{,
184 socktype\optional{, proto\optional{,
185 flags}}}}}
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000186Resolves the \var{host}/\var{port} argument, into a sequence of
1875-tuples that contain all the necessary argument for the sockets
188manipulation. \var{host} is a domain name, a string representation of
189IPv4/v6 address or \code{None}.
Fred Draked198f382003-04-25 16:16:02 +0000190\var{port} is a string service name (like \code{'http'}), a numeric
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000191port number or \code{None}.
192
193The rest of the arguments are optional and must be numeric if
194specified. For \var{host} and \var{port}, by passing either an empty
195string or \code{None}, you can pass \code{NULL} to the C API. The
196\function{getaddrinfo()} function returns a list of 5-tuples with
197the following structure:
198
Fred Draked198f382003-04-25 16:16:02 +0000199\code{(\var{family}, \var{socktype}, \var{proto}, \var{canonname},
200 \var{sockaddr})}
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000201
202\var{family}, \var{socktype}, \var{proto} are all integer and are meant to
203be passed to the \function{socket()} function.
204\var{canonname} is a string representing the canonical name of the \var{host}.
Fred Draked198f382003-04-25 16:16:02 +0000205It can be a numeric IPv4/v6 address when \constant{AI_CANONNAME} is specified
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000206for a numeric \var{host}.
207\var{sockaddr} is a tuple describing a socket address, as described above.
Fred Draked198f382003-04-25 16:16:02 +0000208See the source for the \refmodule{httplib} and other library modules
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000209for a typical usage of the function.
210\versionadded{2.2}
211\end{funcdesc}
212
Fred Drake5772c862000-08-16 14:21:42 +0000213\begin{funcdesc}{getfqdn}{\optional{name}}
214Return a fully qualified domain name for \var{name}.
215If \var{name} is omitted or empty, it is interpreted as the local
216host. To find the fully qualified name, the hostname returned by
217\function{gethostbyaddr()} is checked, then aliases for the host, if
218available. The first name which includes a period is selected. In
Brett Cannon01668a12005-03-11 00:04:17 +0000219case no fully qualified domain name is available, the hostname as
220returned by \function{gethostname()} is returned.
Fred Drake8b2e8f82000-09-06 02:22:16 +0000221\versionadded{2.0}
Fred Drake5772c862000-08-16 14:21:42 +0000222\end{funcdesc}
223
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000224\begin{funcdesc}{gethostbyname}{hostname}
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000225Translate a host name to IPv4 address format. The IPv4 address is
Fred Drake87fa3aa2001-12-21 17:45:03 +0000226returned as a string, such as \code{'100.50.200.5'}. If the host name
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000227is an IPv4 address itself it is returned unchanged. See
Fred Drake318c0b11999-04-21 17:29:14 +0000228\function{gethostbyname_ex()} for a more complete interface.
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000229\function{gethostbyname()} does not support IPv6 name resolution, and
230\function{getaddrinfo()} should be used instead for IPv4/v6 dual stack support.
Guido van Rossumcdf6af11998-08-07 18:07:36 +0000231\end{funcdesc}
232
233\begin{funcdesc}{gethostbyname_ex}{hostname}
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000234Translate a host name to IPv4 address format, extended interface.
Fred Draked198f382003-04-25 16:16:02 +0000235Return a triple \code{(\var{hostname}, \var{aliaslist},
236\var{ipaddrlist})} where
237\var{hostname} is the primary host name responding to the given
238\var{ip_address}, \var{aliaslist} is a (possibly empty) list of
239alternative host names for the same address, and \var{ipaddrlist} is
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000240a list of IPv4 addresses for the same interface on the same
Guido van Rossumcdf6af11998-08-07 18:07:36 +0000241host (often but not always a single address).
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000242\function{gethostbyname_ex()} does not support IPv6 name resolution, and
243\function{getaddrinfo()} should be used instead for IPv4/v6 dual stack support.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000244\end{funcdesc}
245
Guido van Rossum781db5d1994-08-05 13:37:36 +0000246\begin{funcdesc}{gethostname}{}
Guido van Rossum16d6e711994-08-08 12:30:22 +0000247Return a string containing the hostname of the machine where
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000248the Python interpreter is currently executing.
249If you want to know the current machine's IP address, you may want to use
250\code{gethostbyname(gethostname())}.
251This operation assumes that there is a valid address-to-host mapping for
252the host, and the assumption does not always hold.
Fred Draked883ca11998-03-10 05:20:33 +0000253Note: \function{gethostname()} doesn't always return the fully qualified
Thomas Wouters89f507f2006-12-13 04:49:30 +0000254domain name; use \code{getfqdn()}
255(see above).
Guido van Rossum31cce971995-01-04 19:17:34 +0000256\end{funcdesc}
257
258\begin{funcdesc}{gethostbyaddr}{ip_address}
Fred Draked883ca11998-03-10 05:20:33 +0000259Return a triple \code{(\var{hostname}, \var{aliaslist},
260\var{ipaddrlist})} where \var{hostname} is the primary host name
261responding to the given \var{ip_address}, \var{aliaslist} is a
262(possibly empty) list of alternative host names for the same address,
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000263and \var{ipaddrlist} is a list of IPv4/v6 addresses for the same interface
Fred Draked883ca11998-03-10 05:20:33 +0000264on the same host (most likely containing only a single address).
Fred Drake5772c862000-08-16 14:21:42 +0000265To find the fully qualified domain name, use the function
266\function{getfqdn()}.
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000267\function{gethostbyaddr} supports both IPv4 and IPv6.
268\end{funcdesc}
269
270\begin{funcdesc}{getnameinfo}{sockaddr, flags}
271Translate a socket address \var{sockaddr} into a 2-tuple
272\code{(\var{host}, \var{port})}.
273Depending on the settings of \var{flags}, the result can contain a
274fully-qualified domain name or numeric address representation in
275\var{host}. Similarly, \var{port} can contain a string port name or a
276numeric port number.
277\versionadded{2.2}
Guido van Rossum781db5d1994-08-05 13:37:36 +0000278\end{funcdesc}
279
Guido van Rossum62ac99e1996-12-19 16:43:25 +0000280\begin{funcdesc}{getprotobyname}{protocolname}
Fred Drake87fa3aa2001-12-21 17:45:03 +0000281Translate an Internet protocol name (for example, \code{'icmp'}) to a constant
Guido van Rossum62ac99e1996-12-19 16:43:25 +0000282suitable for passing as the (optional) third argument to the
Fred Draked883ca11998-03-10 05:20:33 +0000283\function{socket()} function. This is usually only needed for sockets
284opened in ``raw'' mode (\constant{SOCK_RAW}); for the normal socket
285modes, the correct protocol is chosen automatically if the protocol is
Guido van Rossum62ac99e1996-12-19 16:43:25 +0000286omitted or zero.
287\end{funcdesc}
288
Barry Warsaw11b91a02004-06-28 00:50:43 +0000289\begin{funcdesc}{getservbyname}{servicename\optional{, protocolname}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000290Translate an Internet service name and protocol name to a port number
Barry Warsaw11b91a02004-06-28 00:50:43 +0000291for that service. The optional protocol name, if given, should be
292\code{'tcp'} or \code{'udp'}, otherwise any protocol will match.
293\end{funcdesc}
294
295\begin{funcdesc}{getservbyport}{port\optional{, protocolname}}
296Translate an Internet port number and protocol name to a service name
297for that service. The optional protocol name, if given, should be
298\code{'tcp'} or \code{'udp'}, otherwise any protocol will match.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000299\end{funcdesc}
300
Fred Drakefcc51762004-01-27 18:21:26 +0000301\begin{funcdesc}{socket}{\optional{family\optional{,
302 type\optional{, proto}}}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000303Create a new socket using the given address family, socket type and
Fred Drakefcc51762004-01-27 18:21:26 +0000304protocol number. The address family should be \constant{AF_INET} (the
305default), \constant{AF_INET6} or \constant{AF_UNIX}. The socket type
306should be \constant{SOCK_STREAM} (the default), \constant{SOCK_DGRAM}
307or perhaps one of the other \samp{SOCK_} constants. The protocol
308number is usually zero and may be omitted in that case.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000309\end{funcdesc}
310
Jeremy Hyltoncb43c082001-10-11 16:17:22 +0000311\begin{funcdesc}{ssl}{sock\optional{, keyfile, certfile}}
Fred Drake9081bb12001-09-25 15:48:11 +0000312Initiate a SSL connection over the socket \var{sock}. \var{keyfile} is
313the name of a PEM formatted file that contains your private
314key. \var{certfile} is a PEM formatted certificate chain file. On
315success, a new \class{SSLObject} is returned.
316
Fred Drake0aa811c2001-10-20 04:24:09 +0000317\warning{This does not do any certificate verification!}
Fred Drake9081bb12001-09-25 15:48:11 +0000318\end{funcdesc}
319
Dave Cole331708b2004-08-09 04:51:41 +0000320\begin{funcdesc}{socketpair}{\optional{family\optional{, type\optional{, proto}}}}
321Build a pair of connected socket objects using the given address
Dave Colee8bbfe42004-08-26 00:51:16 +0000322family, socket type, and protocol number. Address family, socket type,
Dave Cole331708b2004-08-09 04:51:41 +0000323and protocol number are as for the \function{socket()} function above.
Dave Colee8bbfe42004-08-26 00:51:16 +0000324The default family is \constant{AF_UNIX} if defined on the platform;
325otherwise, the default is \constant{AF_INET}.
Dave Cole07fda7e2004-08-23 05:16:23 +0000326Availability: \UNIX. \versionadded{2.4}
Dave Cole331708b2004-08-09 04:51:41 +0000327\end{funcdesc}
328
Fred Draked883ca11998-03-10 05:20:33 +0000329\begin{funcdesc}{fromfd}{fd, family, type\optional{, proto}}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000330Duplicate the file descriptor \var{fd} (an integer as returned by a file
331object's \method{fileno()} method) and build a socket object from the
332result. Address family, socket type and protocol number are as for the
333\function{socket()} function above.
334The file descriptor should refer to a socket, but this is not
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000335checked --- subsequent operations on the object may fail if the file
336descriptor is invalid. This function is rarely needed, but can be
337used to get or set socket options on a socket passed to a program as
Fred Drake87fa3aa2001-12-21 17:45:03 +0000338standard input or output (such as a server started by the \UNIX{} inet
Guido van Rossum11ba0942002-06-13 15:07:44 +0000339daemon). The socket is assumed to be in blocking mode.
Fred Drake87fa3aa2001-12-21 17:45:03 +0000340Availability: \UNIX.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000341\end{funcdesc}
342
Guido van Rossumbda7ca71996-12-02 17:24:10 +0000343\begin{funcdesc}{ntohl}{x}
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000344Convert 32-bit positive integers from network to host byte order. On machines
Fred Drakec5aec051997-12-08 21:25:41 +0000345where the host byte order is the same as network byte order, this is a
346no-op; otherwise, it performs a 4-byte swap operation.
347\end{funcdesc}
348
349\begin{funcdesc}{ntohs}{x}
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000350Convert 16-bit positive integers from network to host byte order. On machines
Fred Drakec5aec051997-12-08 21:25:41 +0000351where the host byte order is the same as network byte order, this is a
352no-op; otherwise, it performs a 2-byte swap operation.
353\end{funcdesc}
354
355\begin{funcdesc}{htonl}{x}
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000356Convert 32-bit positive integers from host to network byte order. On machines
Fred Drakec5aec051997-12-08 21:25:41 +0000357where the host byte order is the same as network byte order, this is a
358no-op; otherwise, it performs a 4-byte swap operation.
359\end{funcdesc}
360
361\begin{funcdesc}{htons}{x}
Thomas Woutersfc7bb8c2007-01-15 15:49:28 +0000362Convert 16-bit positive integers from host to network byte order. On machines
Fred Drakec5aec051997-12-08 21:25:41 +0000363where the host byte order is the same as network byte order, this is a
364no-op; otherwise, it performs a 2-byte swap operation.
Guido van Rossumbda7ca71996-12-02 17:24:10 +0000365\end{funcdesc}
366
Fred Drakee6fb1c41999-09-16 15:50:00 +0000367\begin{funcdesc}{inet_aton}{ip_string}
Fred Drake87fa3aa2001-12-21 17:45:03 +0000368Convert an IPv4 address from dotted-quad string format (for example,
369'123.45.67.89') to 32-bit packed binary format, as a string four
Fred Draked198f382003-04-25 16:16:02 +0000370characters in length. This is useful when conversing with a program
371that uses the standard C library and needs objects of type
372\ctype{struct in_addr}, which is the C type for the 32-bit packed
373binary this function returns.
Fred Drakee6fb1c41999-09-16 15:50:00 +0000374
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000375If the IPv4 address string passed to this function is invalid,
Fred Drakee6fb1c41999-09-16 15:50:00 +0000376\exception{socket.error} will be raised. Note that exactly what is
377valid depends on the underlying C implementation of
378\cfunction{inet_aton()}.
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000379
Fred Drake39960f62001-12-22 19:07:58 +0000380\function{inet_aton()} does not support IPv6, and
381\function{getnameinfo()} should be used instead for IPv4/v6 dual stack
382support.
Fred Drakee6fb1c41999-09-16 15:50:00 +0000383\end{funcdesc}
384
385\begin{funcdesc}{inet_ntoa}{packed_ip}
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000386Convert a 32-bit packed IPv4 address (a string four characters in
Fred Draked198f382003-04-25 16:16:02 +0000387length) to its standard dotted-quad string representation (for
388example, '123.45.67.89'). This is useful when conversing with a
389program that uses the standard C library and needs objects of type
390\ctype{struct in_addr}, which is the C type for the 32-bit packed
391binary data this function takes as an argument.
Fred Drakee6fb1c41999-09-16 15:50:00 +0000392
393If the string passed to this function is not exactly 4 bytes in
394length, \exception{socket.error} will be raised.
Fred Drake39960f62001-12-22 19:07:58 +0000395\function{inet_ntoa()} does not support IPv6, and
396\function{getnameinfo()} should be used instead for IPv4/v6 dual stack
397support.
Fred Drakee6fb1c41999-09-16 15:50:00 +0000398\end{funcdesc}
399
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000400\begin{funcdesc}{inet_pton}{address_family, ip_string}
401Convert an IP address from its family-specific string format to a packed,
402binary format.
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000403\function{inet_pton()} is useful when a library or network protocol calls for
404an object of type \ctype{struct in_addr} (similar to \function{inet_aton()})
405or \ctype{struct in6_addr}.
406
Fred Draked198f382003-04-25 16:16:02 +0000407Supported values for \var{address_family} are currently
408\constant{AF_INET} and \constant{AF_INET6}.
409If the IP address string \var{ip_string} is invalid,
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000410\exception{socket.error} will be raised. Note that exactly what is valid
411depends on both the value of \var{address_family} and the underlying
412implementation of \cfunction{inet_pton()}.
Fred Draked198f382003-04-25 16:16:02 +0000413
414Availability: \UNIX{} (maybe not all platforms).
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000415\versionadded{2.3}
416\end{funcdesc}
417
418\begin{funcdesc}{inet_ntop}{address_family, packed_ip}
Fred Draked198f382003-04-25 16:16:02 +0000419Convert a packed IP address (a string of some number of characters) to
420its standard, family-specific string representation (for example,
421\code{'7.10.0.5'} or \code{'5aef:2b::8'})
Guido van Rossumb0167522003-04-25 15:26:58 +0000422\function{inet_ntop()} is useful when a library or network protocol returns
423an object of type \ctype{struct in_addr} (similar to \function{inet_ntoa()})
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000424or \ctype{struct in6_addr}.
425
Fred Draked198f382003-04-25 16:16:02 +0000426Supported values for \var{address_family} are currently
427\constant{AF_INET} and \constant{AF_INET6}.
428If the string \var{packed_ip} is not the correct length for the
429specified address family, \exception{ValueError} will be raised. A
430\exception{socket.error} is raised for errors from the call to
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000431\function{inet_ntop()}.
Fred Draked198f382003-04-25 16:16:02 +0000432
433Availability: \UNIX{} (maybe not all platforms).
Guido van Rossum47dfa4a2003-04-25 05:48:32 +0000434\versionadded{2.3}
435\end{funcdesc}
436
Skip Montanaro2a403e82003-03-20 17:58:12 +0000437\begin{funcdesc}{getdefaulttimeout}{}
438Return the default timeout in floating seconds for new socket objects.
439A value of \code{None} indicates that new socket objects have no timeout.
440When the socket module is first imported, the default is \code{None}.
441\versionadded{2.3}
442\end{funcdesc}
443
444\begin{funcdesc}{setdefaulttimeout}{timeout}
445Set the default timeout in floating seconds for new socket objects.
446A value of \code{None} indicates that new socket objects have no timeout.
447When the socket module is first imported, the default is \code{None}.
448\versionadded{2.3}
449\end{funcdesc}
450
Fred Drake5451d671997-10-13 21:31:02 +0000451\begin{datadesc}{SocketType}
Guido van Rossum2335c5e1997-05-21 14:41:42 +0000452This is a Python type object that represents the socket object type.
Fred Draked883ca11998-03-10 05:20:33 +0000453It is the same as \code{type(socket(...))}.
Guido van Rossum2335c5e1997-05-21 14:41:42 +0000454\end{datadesc}
455
Fred Drakeaa7524c2000-07-06 18:37:08 +0000456
457\begin{seealso}
458 \seemodule{SocketServer}{Classes that simplify writing network servers.}
459\end{seealso}
460
461
Fred Drakea94f6761999-08-05 13:41:04 +0000462\subsection{Socket Objects \label{socket-objects}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000463
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000464Socket objects have the following methods. Except for
Fred Draked883ca11998-03-10 05:20:33 +0000465\method{makefile()} these correspond to \UNIX{} system calls
466applicable to sockets.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000467
Fred Drake3f1c4721998-04-03 07:04:45 +0000468\begin{methoddesc}[socket]{accept}{}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000469Accept a connection.
470The socket must be bound to an address and listening for connections.
471The return value is a pair \code{(\var{conn}, \var{address})}
472where \var{conn} is a \emph{new} socket object usable to send and
473receive data on the connection, and \var{address} is the address bound
474to the socket on the other end of the connection.
Fred Drake3f1c4721998-04-03 07:04:45 +0000475\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000476
Fred Drake3f1c4721998-04-03 07:04:45 +0000477\begin{methoddesc}[socket]{bind}{address}
Guido van Rossuma84ec511994-06-23 12:13:52 +0000478Bind the socket to \var{address}. The socket must not already be bound.
Fred Drake7d686902000-04-04 17:48:30 +0000479(The format of \var{address} depends on the address family --- see
Fred Drake0aa811c2001-10-20 04:24:09 +0000480above.) \note{This method has historically accepted a pair
Fred Drake7d686902000-04-04 17:48:30 +0000481of parameters for \constant{AF_INET} addresses instead of only a
Neal Norwitzba813e22004-04-03 18:02:37 +0000482tuple. This was never intentional and is no longer available in
483Python 2.0 and later.}
Fred Drake3f1c4721998-04-03 07:04:45 +0000484\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000485
Fred Drake3f1c4721998-04-03 07:04:45 +0000486\begin{methoddesc}[socket]{close}{}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000487Close the socket. All future operations on the socket object will fail.
488The remote end will receive no more data (after queued data is flushed).
489Sockets are automatically closed when they are garbage-collected.
Fred Drake3f1c4721998-04-03 07:04:45 +0000490\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000491
Fred Drake3f1c4721998-04-03 07:04:45 +0000492\begin{methoddesc}[socket]{connect}{address}
Guido van Rossuma84ec511994-06-23 12:13:52 +0000493Connect to a remote socket at \var{address}.
Fred Draked883ca11998-03-10 05:20:33 +0000494(The format of \var{address} depends on the address family --- see
Fred Drake0aa811c2001-10-20 04:24:09 +0000495above.) \note{This method has historically accepted a pair
Fred Drake7d686902000-04-04 17:48:30 +0000496of parameters for \constant{AF_INET} addresses instead of only a
Eric S. Raymond83210262001-01-10 19:34:52 +0000497tuple. This was never intentional and is no longer available in
Fred Drake0aa811c2001-10-20 04:24:09 +0000498Python 2.0 and later.}
Fred Drake3f1c4721998-04-03 07:04:45 +0000499\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000500
Fred Drake3f1c4721998-04-03 07:04:45 +0000501\begin{methoddesc}[socket]{connect_ex}{address}
Guido van Rossumeefcba61997-12-09 19:47:24 +0000502Like \code{connect(\var{address})}, but return an error indicator
Fred Drakeb0bc7f21999-05-06 22:03:50 +0000503instead of raising an exception for errors returned by the C-level
504\cfunction{connect()} call (other problems, such as ``host not found,''
505can still raise exceptions). The error indicator is \code{0} if the
Fred Draked883ca11998-03-10 05:20:33 +0000506operation succeeded, otherwise the value of the \cdata{errno}
Fred Drake87fa3aa2001-12-21 17:45:03 +0000507variable. This is useful to support, for example, asynchronous connects.
Fred Drake0aa811c2001-10-20 04:24:09 +0000508\note{This method has historically accepted a pair of
Fred Drake7d686902000-04-04 17:48:30 +0000509parameters for \constant{AF_INET} addresses instead of only a tuple.
Neal Norwitzba813e22004-04-03 18:02:37 +0000510This was never intentional and is no longer available in Python
Fred Drake0aa811c2001-10-20 04:24:09 +00005112.0 and later.}
Fred Drake3f1c4721998-04-03 07:04:45 +0000512\end{methoddesc}
Guido van Rossumf7790c61997-11-18 15:29:20 +0000513
Fred Drake3f1c4721998-04-03 07:04:45 +0000514\begin{methoddesc}[socket]{fileno}{}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000515Return the socket's file descriptor (a small integer). This is useful
Fred Draked883ca11998-03-10 05:20:33 +0000516with \function{select.select()}.
Brett Cannonb278ac42003-08-05 03:51:24 +0000517
518Under Windows the small integer returned by this method cannot be used where
519a file descriptor can be used (such as \function{os.fdopen()}). \UNIX{} does
520not have this limitation.
Fred Drake3f1c4721998-04-03 07:04:45 +0000521\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000522
Fred Drake3f1c4721998-04-03 07:04:45 +0000523\begin{methoddesc}[socket]{getpeername}{}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000524Return the remote address to which the socket is connected. This is
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000525useful to find out the port number of a remote IPv4/v6 socket, for instance.
Guido van Rossum86751151995-02-28 17:14:32 +0000526(The format of the address returned depends on the address family ---
Guido van Rossum781db5d1994-08-05 13:37:36 +0000527see above.) On some systems this function is not supported.
Fred Drake3f1c4721998-04-03 07:04:45 +0000528\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000529
Fred Drake3f1c4721998-04-03 07:04:45 +0000530\begin{methoddesc}[socket]{getsockname}{}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000531Return the socket's own address. This is useful to find out the port
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000532number of an IPv4/v6 socket, for instance.
Guido van Rossum86751151995-02-28 17:14:32 +0000533(The format of the address returned depends on the address family ---
Guido van Rossuma84ec511994-06-23 12:13:52 +0000534see above.)
Fred Drake3f1c4721998-04-03 07:04:45 +0000535\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000536
Fred Drake3f1c4721998-04-03 07:04:45 +0000537\begin{methoddesc}[socket]{getsockopt}{level, optname\optional{, buflen}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000538Return the value of the given socket option (see the \UNIX{} man page
Fred Draked883ca11998-03-10 05:20:33 +0000539\manpage{getsockopt}{2}). The needed symbolic constants
540(\constant{SO_*} etc.) are defined in this module. If \var{buflen}
Guido van Rossum470be141995-03-17 16:07:09 +0000541is absent, an integer option is assumed and its integer value
Guido van Rossum8df36371995-02-27 17:52:15 +0000542is returned by the function. If \var{buflen} is present, it specifies
543the maximum length of the buffer used to receive the option in, and
Guido van Rossum470be141995-03-17 16:07:09 +0000544this buffer is returned as a string. It is up to the caller to decode
Guido van Rossum8df36371995-02-27 17:52:15 +0000545the contents of the buffer (see the optional built-in module
Fred Drake318c0b11999-04-21 17:29:14 +0000546\refmodule{struct} for a way to decode C structures encoded as strings).
Fred Drake3f1c4721998-04-03 07:04:45 +0000547\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000548
Fred Drake3f1c4721998-04-03 07:04:45 +0000549\begin{methoddesc}[socket]{listen}{backlog}
Guido van Rossum470be141995-03-17 16:07:09 +0000550Listen for connections made to the socket. The \var{backlog} argument
551specifies the maximum number of queued connections and should be at
552least 1; the maximum value is system-dependent (usually 5).
Fred Drake3f1c4721998-04-03 07:04:45 +0000553\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000554
Fred Drake3f1c4721998-04-03 07:04:45 +0000555\begin{methoddesc}[socket]{makefile}{\optional{mode\optional{, bufsize}}}
Guido van Rossum470be141995-03-17 16:07:09 +0000556Return a \dfn{file object} associated with the socket. (File objects
Fred Drakea94f6761999-08-05 13:41:04 +0000557are described in \ref{bltin-file-objects}, ``File Objects.'')
Fred Draked883ca11998-03-10 05:20:33 +0000558The file object references a \cfunction{dup()}ped version of the
559socket file descriptor, so the file object and socket object may be
Fred Drakea94f6761999-08-05 13:41:04 +0000560closed or garbage-collected independently.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000561The socket must be in blocking mode (it can not have a timeout).
Fred Drakea94f6761999-08-05 13:41:04 +0000562\index{I/O control!buffering}The optional \var{mode}
Fred Draked883ca11998-03-10 05:20:33 +0000563and \var{bufsize} arguments are interpreted the same way as by the
Fred Drakeaad8bb52001-10-19 17:22:29 +0000564built-in \function{file()} function; see ``Built-in Functions''
565(section \ref{built-in-funcs}) for more information.
Fred Drake3f1c4721998-04-03 07:04:45 +0000566\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000567
Fred Drake3f1c4721998-04-03 07:04:45 +0000568\begin{methoddesc}[socket]{recv}{bufsize\optional{, flags}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000569Receive data from the socket. The return value is a string representing
570the data received. The maximum amount of data to be received
571at once is specified by \var{bufsize}. See the \UNIX{} manual page
Fred Draked883ca11998-03-10 05:20:33 +0000572\manpage{recv}{2} for the meaning of the optional argument
573\var{flags}; it defaults to zero.
Georg Brandl10141742005-12-26 23:07:46 +0000574\note{For best match with hardware and network realities, the value of
575\var{bufsize} should be a relatively small power of 2, for example, 4096.}
Fred Drake3f1c4721998-04-03 07:04:45 +0000576\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000577
Fred Drake3f1c4721998-04-03 07:04:45 +0000578\begin{methoddesc}[socket]{recvfrom}{bufsize\optional{, flags}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000579Receive data from the socket. The return value is a pair
580\code{(\var{string}, \var{address})} where \var{string} is a string
581representing the data received and \var{address} is the address of the
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000582socket sending the data. See the \UNIX{} manual page
583\manpage{recv}{2} for the meaning of the optional argument
584\var{flags}; it defaults to zero.
Guido van Rossum86751151995-02-28 17:14:32 +0000585(The format of \var{address} depends on the address family --- see above.)
Fred Drake3f1c4721998-04-03 07:04:45 +0000586\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000587
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000588\begin{methoddesc}[socket]{recvfrom_into}{buffer\optional{, nbytes\optional{, flags}}}
589Receive data from the socket, writing it into \var{buffer} instead of
590creating a new string. The return value is a pair
591\code{(\var{nbytes}, \var{address})} where \var{nbytes} is the number
592of bytes received and \var{address} is the address of the socket
593sending the data. See the \UNIX{} manual page
594\manpage{recv}{2} for the meaning of the optional argument
595\var{flags}; it defaults to zero. (The format of \var{address}
596depends on the address family --- see above.)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000597\versionadded{2.5}
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000598\end{methoddesc}
599
600\begin{methoddesc}[socket]{recv_into}{buffer\optional{, nbytes\optional{, flags}}}
601Receive up to \var{nbytes} bytes from the socket,
602storing the data into a buffer rather than creating a new string.
603If \var{nbytes} is not specified (or 0),
604receive up to the size available in the given buffer.
605See the \UNIX{} manual page \manpage{recv}{2} for the meaning of the
606optional argument \var{flags}; it defaults to zero.
Guido van Rossumd8faa362007-04-27 19:54:29 +0000607\versionadded{2.5}
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000608\end{methoddesc}
609
Fred Drake3f1c4721998-04-03 07:04:45 +0000610\begin{methoddesc}[socket]{send}{string\optional{, flags}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000611Send data to the socket. The socket must be connected to a remote
Guido van Rossum470be141995-03-17 16:07:09 +0000612socket. The optional \var{flags} argument has the same meaning as for
Fred Draked883ca11998-03-10 05:20:33 +0000613\method{recv()} above. Returns the number of bytes sent.
Fred Drake39368c12001-12-05 05:25:59 +0000614Applications are responsible for checking that all data has been sent;
615if only some of the data was transmitted, the application needs to
616attempt delivery of the remaining data.
617\end{methoddesc}
618
619\begin{methoddesc}[socket]{sendall}{string\optional{, flags}}
620Send data to the socket. The socket must be connected to a remote
621socket. The optional \var{flags} argument has the same meaning as for
622\method{recv()} above. Unlike \method{send()}, this method continues
623to send data from \var{string} until either all data has been sent or
624an error occurs. \code{None} is returned on success. On error, an
625exception is raised, and there is no way to determine how much data,
626if any, was successfully sent.
Fred Drake3f1c4721998-04-03 07:04:45 +0000627\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000628
Fred Drake3f1c4721998-04-03 07:04:45 +0000629\begin{methoddesc}[socket]{sendto}{string\optional{, flags}, address}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000630Send data to the socket. The socket should not be connected to a
631remote socket, since the destination socket is specified by
Fred Draked883ca11998-03-10 05:20:33 +0000632\var{address}. The optional \var{flags} argument has the same
633meaning as for \method{recv()} above. Return the number of bytes sent.
Guido van Rossum86751151995-02-28 17:14:32 +0000634(The format of \var{address} depends on the address family --- see above.)
Fred Drake3f1c4721998-04-03 07:04:45 +0000635\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000636
Fred Drake3f1c4721998-04-03 07:04:45 +0000637\begin{methoddesc}[socket]{setblocking}{flag}
Guido van Rossum91951481994-09-07 14:39:14 +0000638Set blocking or non-blocking mode of the socket: if \var{flag} is 0,
639the socket is set to non-blocking, else to blocking mode. Initially
640all sockets are in blocking mode. In non-blocking mode, if a
Fred Drake318c0b11999-04-21 17:29:14 +0000641\method{recv()} call doesn't find any data, or if a
642\method{send()} call can't immediately dispose of the data, a
643\exception{error} exception is raised; in blocking mode, the calls
644block until they can proceed.
Guido van Rossum11ba0942002-06-13 15:07:44 +0000645\code{s.setblocking(0)} is equivalent to \code{s.settimeout(0)};
646\code{s.setblocking(1)} is equivalent to \code{s.settimeout(None)}.
Fred Drake3f1c4721998-04-03 07:04:45 +0000647\end{methoddesc}
Guido van Rossum91951481994-09-07 14:39:14 +0000648
Guido van Rossumbe946bf2002-06-06 21:51:01 +0000649\begin{methoddesc}[socket]{settimeout}{value}
Guido van Rossum11ba0942002-06-13 15:07:44 +0000650Set a timeout on blocking socket operations. The \var{value} argument
651can be a nonnegative float expressing seconds, or \code{None}.
652If a float is
Raymond Hettingerbe2528d2003-06-29 04:55:59 +0000653given, subsequent socket operations will raise an \exception{timeout}
Guido van Rossumfc9823b2002-06-07 03:39:21 +0000654exception if the timeout period \var{value} has elapsed before the
655operation has completed. Setting a timeout of \code{None} disables
656timeouts on socket operations.
Neal Norwitz3a03de42003-06-20 17:11:39 +0000657\code{s.settimeout(0.0)} is equivalent to \code{s.setblocking(0)};
Guido van Rossum11ba0942002-06-13 15:07:44 +0000658\code{s.settimeout(None)} is equivalent to \code{s.setblocking(1)}.
Neal Norwitzbdbd84f2002-06-06 22:24:10 +0000659\versionadded{2.3}
Guido van Rossumbe946bf2002-06-06 21:51:01 +0000660\end{methoddesc}
661
662\begin{methoddesc}[socket]{gettimeout}{}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000663Return the timeout in floating seconds associated with socket
Guido van Rossum11ba0942002-06-13 15:07:44 +0000664operations, or \code{None} if no timeout is set. This reflects
665the last call to \method{setblocking()} or \method{settimeout()}.
Neal Norwitzbdbd84f2002-06-06 22:24:10 +0000666\versionadded{2.3}
Guido van Rossumbe946bf2002-06-06 21:51:01 +0000667\end{methoddesc}
668
Guido van Rossum11ba0942002-06-13 15:07:44 +0000669Some notes on socket blocking and timeouts: A socket object can be in
Raymond Hettinger476fcae2003-07-20 01:10:15 +0000670one of three modes: blocking, non-blocking, or timeout. Sockets are
Guido van Rossum11ba0942002-06-13 15:07:44 +0000671always created in blocking mode. In blocking mode, operations block
672until complete. In non-blocking mode, operations fail (with an error
673that is unfortunately system-dependent) if they cannot be completed
674immediately. In timeout mode, operations fail if they cannot be
675completed within the timeout specified for the socket. The
676\method{setblocking()} method is simply a shorthand for certain
677\method{settimeout()} calls.
Guido van Rossumbe946bf2002-06-06 21:51:01 +0000678
Guido van Rossum715b8612002-06-07 12:38:23 +0000679Timeout mode internally sets the socket in non-blocking mode. The
680blocking and timeout modes are shared between file descriptors and
681socket objects that refer to the same network endpoint. A consequence
682of this is that file objects returned by the \method{makefile()}
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000683method must only be used when the socket is in blocking mode; in
Guido van Rossum715b8612002-06-07 12:38:23 +0000684timeout or non-blocking mode file operations that cannot be completed
685immediately will fail.
686
Guido van Rossum5a921752003-12-13 22:12:53 +0000687Note that the \method{connect()} operation is subject to the timeout
688setting, and in general it is recommended to call
689\method{settimeout()} before calling \method{connect()}.
690
Fred Drake3f1c4721998-04-03 07:04:45 +0000691\begin{methoddesc}[socket]{setsockopt}{level, optname, value}
Fred Drake9a748aa2000-06-30 04:21:41 +0000692Set the value of the given socket option (see the \UNIX{} manual page
Fred Draked883ca11998-03-10 05:20:33 +0000693\manpage{setsockopt}{2}). The needed symbolic constants are defined in
Fred Draked198f382003-04-25 16:16:02 +0000694the \module{socket} module (\constant{SO_*} etc.). The value can be an
Guido van Rossum8df36371995-02-27 17:52:15 +0000695integer or a string representing a buffer. In the latter case it is
696up to the caller to ensure that the string contains the proper bits
697(see the optional built-in module
Fred Drake318c0b11999-04-21 17:29:14 +0000698\refmodule{struct}\refbimodindex{struct} for a way to encode C
699structures as strings).
Fred Drake3f1c4721998-04-03 07:04:45 +0000700\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000701
Fred Drake3f1c4721998-04-03 07:04:45 +0000702\begin{methoddesc}[socket]{shutdown}{how}
Fred Draked883ca11998-03-10 05:20:33 +0000703Shut down one or both halves of the connection. If \var{how} is
Martin v. Löwis94681fc2003-11-27 19:40:22 +0000704\constant{SHUT_RD}, further receives are disallowed. If \var{how} is \constant{SHUT_WR},
705further sends are disallowed. If \var{how} is \constant{SHUT_RDWR}, further sends
Fred Draked883ca11998-03-10 05:20:33 +0000706and receives are disallowed.
Fred Drake3f1c4721998-04-03 07:04:45 +0000707\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000708
Fred Draked883ca11998-03-10 05:20:33 +0000709Note that there are no methods \method{read()} or \method{write()};
710use \method{recv()} and \method{send()} without \var{flags} argument
711instead.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000712
Fred Drakeaa7524c2000-07-06 18:37:08 +0000713
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000714Socket objects also have these (read-only) attributes that correspond
715to the values given to the \class{socket} constructor.
716
717\begin{memberdesc}[socket]{family}
718The socket family.
719\versionadded{2.5}
720\end{memberdesc}
721
722\begin{memberdesc}[socket]{type}
723The socket type.
724\versionadded{2.5}
725\end{memberdesc}
726
727\begin{memberdesc}[socket]{proto}
728The socket protocol.
729\versionadded{2.5}
730\end{memberdesc}
731
732
Fred Drake9081bb12001-09-25 15:48:11 +0000733\subsection{SSL Objects \label{ssl-objects}}
734
735SSL objects have the following methods.
736
Guido van Rossumd8faa362007-04-27 19:54:29 +0000737\begin{methoddesc}[SSL]{write}{s}
Fred Drake9081bb12001-09-25 15:48:11 +0000738Writes the string \var{s} to the on the object's SSL connection.
739The return value is the number of bytes written.
740\end{methoddesc}
741
Guido van Rossumd8faa362007-04-27 19:54:29 +0000742\begin{methoddesc}[SSL]{read}{\optional{n}}
Fred Drake9081bb12001-09-25 15:48:11 +0000743If \var{n} is provided, read \var{n} bytes from the SSL connection, otherwise
744read until EOF. The return value is a string of the bytes read.
745\end{methoddesc}
746
Guido van Rossumd8faa362007-04-27 19:54:29 +0000747\begin{methoddesc}[SSL]{server}{}
Thomas Wouters89f507f2006-12-13 04:49:30 +0000748Returns a string describing the server's certificate.
749Useful for debugging purposes; do not parse the content of this string
750because its format can't be parsed unambiguously.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000751\end{methoddesc}
752
Guido van Rossumd8faa362007-04-27 19:54:29 +0000753\begin{methoddesc}[SSL]{issuer}{}
Thomas Wouters89f507f2006-12-13 04:49:30 +0000754Returns a string describing the issuer of the server's certificate.
755Useful for debugging purposes; do not parse the content of this string
756because its format can't be parsed unambiguously.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000757\end{methoddesc}
758
Fred Drakeaa7524c2000-07-06 18:37:08 +0000759\subsection{Example \label{socket-example}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000760
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000761Here are four minimal example programs using the TCP/IP protocol:\ a
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000762server that echoes all data that it receives back (servicing only one
763client), and a client using it. Note that a server must perform the
Fred Draked883ca11998-03-10 05:20:33 +0000764sequence \function{socket()}, \method{bind()}, \method{listen()},
765\method{accept()} (possibly repeating the \method{accept()} to service
766more than one client), while a client only needs the sequence
767\function{socket()}, \method{connect()}. Also note that the server
768does not \method{send()}/\method{recv()} on the
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000769socket it is listening on but on the new socket returned by
Fred Draked883ca11998-03-10 05:20:33 +0000770\method{accept()}.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000771
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000772The first two examples support IPv4 only.
773
Fred Drake19479911998-02-13 06:58:54 +0000774\begin{verbatim}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000775# Echo server program
Fred Drakeef52f602000-10-10 20:36:29 +0000776import socket
777
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000778HOST = '' # Symbolic name meaning the local host
Fred Drakeef52f602000-10-10 20:36:29 +0000779PORT = 50007 # Arbitrary non-privileged port
780s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Fred Drake3d69c0e2000-05-03 19:40:32 +0000781s.bind((HOST, PORT))
Guido van Rossum5da57551994-03-02 10:52:16 +0000782s.listen(1)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000783conn, addr = s.accept()
784print 'Connected by', addr
785while 1:
786 data = conn.recv(1024)
787 if not data: break
788 conn.send(data)
789conn.close()
Fred Drake19479911998-02-13 06:58:54 +0000790\end{verbatim}
Fred Draked883ca11998-03-10 05:20:33 +0000791
Fred Drake19479911998-02-13 06:58:54 +0000792\begin{verbatim}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000793# Echo client program
Fred Drakeef52f602000-10-10 20:36:29 +0000794import socket
795
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000796HOST = 'daring.cwi.nl' # The remote host
797PORT = 50007 # The same port as used by the server
Fred Drakeef52f602000-10-10 20:36:29 +0000798s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Fred Drake3d69c0e2000-05-03 19:40:32 +0000799s.connect((HOST, PORT))
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000800s.send('Hello, world')
801data = s.recv(1024)
802s.close()
Fred Drake175d1882004-06-03 16:23:23 +0000803print 'Received', repr(data)
Fred Drake19479911998-02-13 06:58:54 +0000804\end{verbatim}
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000805
806The next two examples are identical to the above two, but support both
807IPv4 and IPv6.
808The server side will listen to the first address family available
809(it should listen to both instead).
810On most of IPv6-ready systems, IPv6 will take precedence
811and the server may not accept IPv4 traffic.
812The client side will try to connect to the all addresses returned as a result
813of the name resolution, and sends traffic to the first one connected
814successfully.
815
816\begin{verbatim}
817# Echo server program
818import socket
819import sys
820
821HOST = '' # Symbolic name meaning the local host
822PORT = 50007 # Arbitrary non-privileged port
823s = None
824for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
825 af, socktype, proto, canonname, sa = res
826 try:
827 s = socket.socket(af, socktype, proto)
Guido van Rossumb940e112007-01-10 16:19:56 +0000828 except socket.error as msg:
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000829 s = None
830 continue
831 try:
832 s.bind(sa)
833 s.listen(1)
Guido van Rossumb940e112007-01-10 16:19:56 +0000834 except socket.error as msg:
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000835 s.close()
836 s = None
837 continue
838 break
839if s is None:
840 print 'could not open socket'
841 sys.exit(1)
842conn, addr = s.accept()
843print 'Connected by', addr
844while 1:
845 data = conn.recv(1024)
846 if not data: break
847 conn.send(data)
848conn.close()
849\end{verbatim}
850
851\begin{verbatim}
852# Echo client program
853import socket
854import sys
855
856HOST = 'daring.cwi.nl' # The remote host
857PORT = 50007 # The same port as used by the server
858s = None
859for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM):
860 af, socktype, proto, canonname, sa = res
861 try:
862 s = socket.socket(af, socktype, proto)
Guido van Rossumb940e112007-01-10 16:19:56 +0000863 except socket.error as msg:
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000864 s = None
865 continue
866 try:
867 s.connect(sa)
Guido van Rossumb940e112007-01-10 16:19:56 +0000868 except socket.error as msg:
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000869 s.close()
870 s = None
871 continue
872 break
873if s is None:
874 print 'could not open socket'
875 sys.exit(1)
876s.send('Hello, world')
877data = s.recv(1024)
878s.close()
Fred Drake175d1882004-06-03 16:23:23 +0000879print 'Received', repr(data)
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000880\end{verbatim}
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000881
882This example connects to an SSL server, prints the
883server and issuer's distinguished names, sends some bytes,
884and reads part of the response:
885
886\begin{verbatim}
887import socket
888
889s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
890s.connect(('www.verisign.com', 443))
891
892ssl_sock = socket.ssl(s)
893
894print repr(ssl_sock.server())
895print repr(ssl_sock.issuer())
896
897# Set a simple HTTP request -- use httplib in actual code.
898ssl_sock.write("""GET / HTTP/1.0\r
899Host: www.verisign.com\r\n\r\n""")
900
901# Read a chunk of data. Will not necessarily
902# read all the data returned by the server.
903data = ssl_sock.read()
904
905# Note that you need to close the underlying socket, not the SSL object.
906del ssl_sock
907s.close()
908\end{verbatim}
909
910At this writing, this SSL example prints the following output (line
911breaks inserted for readability):
912
913\begin{verbatim}
914'/C=US/ST=California/L=Mountain View/
915 O=VeriSign, Inc./OU=Production Services/
916 OU=Terms of use at www.verisign.com/rpa (c)00/
917 CN=www.verisign.com'
918'/O=VeriSign Trust Network/OU=VeriSign, Inc./
919 OU=VeriSign International Server CA - Class 3/
920 OU=www.verisign.com/CPS Incorp.by Ref. LIABILITY LTD.(c)97 VeriSign'
921\end{verbatim}