blob: b067f9757d2bd0810825993dc009c8e053f12031 [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
Fred Drake318c0b11999-04-21 17:29:14 +000075Non-blocking mode is supported through the
76\method{setblocking()} method.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000077
Fred Draked883ca11998-03-10 05:20:33 +000078The module \module{socket} exports the following constants and functions:
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000079
Fred Draked883ca11998-03-10 05:20:33 +000080
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000081\begin{excdesc}{error}
Martin v. Löwisc9908c42001-08-04 22:22:45 +000082This exception is raised for socket-related errors.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000083The accompanying value is either a string telling what went wrong or a
84pair \code{(\var{errno}, \var{string})}
85representing an error returned by a system
Fred Drake318c0b11999-04-21 17:29:14 +000086call, similar to the value accompanying \exception{os.error}.
87See the module \refmodule{errno}\refbimodindex{errno}, which contains
Guido van Rossum8e1e68d1998-02-06 15:18:25 +000088names for the error codes defined by the underlying operating system.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000089\end{excdesc}
90
Martin v. Löwisc9908c42001-08-04 22:22:45 +000091\begin{excdesc}{herror}
92This exception is raised for address-related errors, i.e. for
Fred Drake87fa3aa2001-12-21 17:45:03 +000093functions that use \var{h_errno} in the C API, including
94\function{gethostbyname_ex()} and \function{gethostbyaddr()}.
Martin v. Löwisc9908c42001-08-04 22:22:45 +000095
96The accompanying value is a pair \code{(\var{h_errno}, \var{string})}
97representing an error returned by a library call. \var{string}
98represents the description of \var{h_errno}, as returned by
Fred Drake87fa3aa2001-12-21 17:45:03 +000099the \cfunction{hstrerror()} C function.
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000100\end{excdesc}
101
102\begin{excdesc}{gaierror}
103This exception is raised for address-related errors, for
Fred Drake87fa3aa2001-12-21 17:45:03 +0000104\function{getaddrinfo()} and \function{getnameinfo()}.
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000105The accompanying value is a pair \code{(\var{error}, \var{string})}
106representing an error returned by a library call.
107\var{string} represents the description of \var{error}, as returned
Fred Drake87fa3aa2001-12-21 17:45:03 +0000108by the \cfunction{gai_strerror()} C function.
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000109\end{excdesc}
110
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000111\begin{datadesc}{AF_UNIX}
112\dataline{AF_INET}
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000113\dataline{AF_INET6}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000114These constants represent the address (and protocol) families,
Fred Draked883ca11998-03-10 05:20:33 +0000115used for the first argument to \function{socket()}. If the
116\constant{AF_UNIX} constant is not defined then this protocol is
117unsupported.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000118\end{datadesc}
119
120\begin{datadesc}{SOCK_STREAM}
121\dataline{SOCK_DGRAM}
Guido van Rossum781db5d1994-08-05 13:37:36 +0000122\dataline{SOCK_RAW}
123\dataline{SOCK_RDM}
124\dataline{SOCK_SEQPACKET}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000125These constants represent the socket types,
Fred Draked883ca11998-03-10 05:20:33 +0000126used for the second argument to \function{socket()}.
127(Only \constant{SOCK_STREAM} and
128\constant{SOCK_DGRAM} appear to be generally useful.)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000129\end{datadesc}
130
Guido van Rossumed2bad81995-02-16 16:29:18 +0000131\begin{datadesc}{SO_*}
132\dataline{SOMAXCONN}
133\dataline{MSG_*}
134\dataline{SOL_*}
135\dataline{IPPROTO_*}
136\dataline{IPPORT_*}
137\dataline{INADDR_*}
138\dataline{IP_*}
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000139\dataline{IPV6_*}
140\dataline{EAI_*}
141\dataline{AI_*}
142\dataline{NI_*}
Guido van Rossum6bb1adc1995-03-13 10:03:32 +0000143Many constants of these forms, documented in the \UNIX{} documentation on
Guido van Rossumed2bad81995-02-16 16:29:18 +0000144sockets and/or the IP protocol, are also defined in the socket module.
Fred Draked883ca11998-03-10 05:20:33 +0000145They are generally used in arguments to the \method{setsockopt()} and
146\method{getsockopt()} methods of socket objects. In most cases, only
Guido van Rossum6bb1adc1995-03-13 10:03:32 +0000147those symbols that are defined in the \UNIX{} header files are defined;
Guido van Rossumed2bad81995-02-16 16:29:18 +0000148for a few symbols, default values are provided.
149\end{datadesc}
150
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000151\begin{funcdesc}{getaddrinfo}{host, port\optional{, family, socktype, proto, flags}}
152
153Resolves the \var{host}/\var{port} argument, into a sequence of
1545-tuples that contain all the necessary argument for the sockets
155manipulation. \var{host} is a domain name, a string representation of
156IPv4/v6 address or \code{None}.
157\var{port} is a string service name (like \code{``http''}), a numeric
158port number or \code{None}.
159
160The rest of the arguments are optional and must be numeric if
161specified. For \var{host} and \var{port}, by passing either an empty
162string or \code{None}, you can pass \code{NULL} to the C API. The
163\function{getaddrinfo()} function returns a list of 5-tuples with
164the following structure:
165
166\code{(\var{family}, \var{socktype}, \var{proto}, \var{canonname}, \var{sockaddr})}.
167
168\var{family}, \var{socktype}, \var{proto} are all integer and are meant to
169be passed to the \function{socket()} function.
170\var{canonname} is a string representing the canonical name of the \var{host}.
171It can be a numeric IPv4/v6 address when \code{AI_CANONNAME} is specified
172for a numeric \var{host}.
173\var{sockaddr} is a tuple describing a socket address, as described above.
174See \code{Lib/httplib.py} and other library files
175for a typical usage of the function.
176\versionadded{2.2}
177\end{funcdesc}
178
Fred Drake5772c862000-08-16 14:21:42 +0000179\begin{funcdesc}{getfqdn}{\optional{name}}
180Return a fully qualified domain name for \var{name}.
181If \var{name} is omitted or empty, it is interpreted as the local
182host. To find the fully qualified name, the hostname returned by
183\function{gethostbyaddr()} is checked, then aliases for the host, if
184available. The first name which includes a period is selected. In
185case no fully qualified domain name is available, the hostname is
186returned.
Fred Drake8b2e8f82000-09-06 02:22:16 +0000187\versionadded{2.0}
Fred Drake5772c862000-08-16 14:21:42 +0000188\end{funcdesc}
189
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000190\begin{funcdesc}{gethostbyname}{hostname}
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000191Translate a host name to IPv4 address format. The IPv4 address is
Fred Drake87fa3aa2001-12-21 17:45:03 +0000192returned as a string, such as \code{'100.50.200.5'}. If the host name
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000193is an IPv4 address itself it is returned unchanged. See
Fred Drake318c0b11999-04-21 17:29:14 +0000194\function{gethostbyname_ex()} for a more complete interface.
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000195\function{gethostbyname()} does not support IPv6 name resolution, and
196\function{getaddrinfo()} should be used instead for IPv4/v6 dual stack support.
Guido van Rossumcdf6af11998-08-07 18:07:36 +0000197\end{funcdesc}
198
199\begin{funcdesc}{gethostbyname_ex}{hostname}
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000200Translate a host name to IPv4 address format, extended interface.
Guido van Rossumcdf6af11998-08-07 18:07:36 +0000201Return a triple \code{(hostname, aliaslist, ipaddrlist)} where
202\code{hostname} is the primary host name responding to the given
203\var{ip_address}, \code{aliaslist} is a (possibly empty) list of
204alternative host names for the same address, and \code{ipaddrlist} is
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000205a list of IPv4 addresses for the same interface on the same
Guido van Rossumcdf6af11998-08-07 18:07:36 +0000206host (often but not always a single address).
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000207\function{gethostbyname_ex()} does not support IPv6 name resolution, and
208\function{getaddrinfo()} should be used instead for IPv4/v6 dual stack support.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000209\end{funcdesc}
210
Guido van Rossum781db5d1994-08-05 13:37:36 +0000211\begin{funcdesc}{gethostname}{}
Guido van Rossum16d6e711994-08-08 12:30:22 +0000212Return a string containing the hostname of the machine where
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000213the Python interpreter is currently executing.
214If you want to know the current machine's IP address, you may want to use
215\code{gethostbyname(gethostname())}.
216This operation assumes that there is a valid address-to-host mapping for
217the host, and the assumption does not always hold.
Fred Draked883ca11998-03-10 05:20:33 +0000218Note: \function{gethostname()} doesn't always return the fully qualified
219domain name; use \code{gethostbyaddr(gethostname())}
Guido van Rossumfe27a501997-01-11 17:04:56 +0000220(see below).
Guido van Rossum31cce971995-01-04 19:17:34 +0000221\end{funcdesc}
222
223\begin{funcdesc}{gethostbyaddr}{ip_address}
Fred Draked883ca11998-03-10 05:20:33 +0000224Return a triple \code{(\var{hostname}, \var{aliaslist},
225\var{ipaddrlist})} where \var{hostname} is the primary host name
226responding to the given \var{ip_address}, \var{aliaslist} is a
227(possibly empty) list of alternative host names for the same address,
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000228and \var{ipaddrlist} is a list of IPv4/v6 addresses for the same interface
Fred Draked883ca11998-03-10 05:20:33 +0000229on the same host (most likely containing only a single address).
Fred Drake5772c862000-08-16 14:21:42 +0000230To find the fully qualified domain name, use the function
231\function{getfqdn()}.
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000232\function{gethostbyaddr} supports both IPv4 and IPv6.
233\end{funcdesc}
234
235\begin{funcdesc}{getnameinfo}{sockaddr, flags}
236Translate a socket address \var{sockaddr} into a 2-tuple
237\code{(\var{host}, \var{port})}.
238Depending on the settings of \var{flags}, the result can contain a
239fully-qualified domain name or numeric address representation in
240\var{host}. Similarly, \var{port} can contain a string port name or a
241numeric port number.
242\versionadded{2.2}
Guido van Rossum781db5d1994-08-05 13:37:36 +0000243\end{funcdesc}
244
Guido van Rossum62ac99e1996-12-19 16:43:25 +0000245\begin{funcdesc}{getprotobyname}{protocolname}
Fred Drake87fa3aa2001-12-21 17:45:03 +0000246Translate an Internet protocol name (for example, \code{'icmp'}) to a constant
Guido van Rossum62ac99e1996-12-19 16:43:25 +0000247suitable for passing as the (optional) third argument to the
Fred Draked883ca11998-03-10 05:20:33 +0000248\function{socket()} function. This is usually only needed for sockets
249opened in ``raw'' mode (\constant{SOCK_RAW}); for the normal socket
250modes, the correct protocol is chosen automatically if the protocol is
Guido van Rossum62ac99e1996-12-19 16:43:25 +0000251omitted or zero.
252\end{funcdesc}
253
Fred Draked883ca11998-03-10 05:20:33 +0000254\begin{funcdesc}{getservbyname}{servicename, protocolname}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000255Translate an Internet service name and protocol name to a port number
256for that service. The protocol name should be \code{'tcp'} or
257\code{'udp'}.
258\end{funcdesc}
259
Fred Draked883ca11998-03-10 05:20:33 +0000260\begin{funcdesc}{socket}{family, type\optional{, proto}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000261Create a new socket using the given address family, socket type and
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000262protocol number. The address family should be \constant{AF_INET}, \constant{AF_INET6} or
Fred Draked883ca11998-03-10 05:20:33 +0000263\constant{AF_UNIX}. The socket type should be \constant{SOCK_STREAM},
264\constant{SOCK_DGRAM} or perhaps one of the other \samp{SOCK_} constants.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000265The protocol number is usually zero and may be omitted in that case.
266\end{funcdesc}
267
Jeremy Hyltoncb43c082001-10-11 16:17:22 +0000268\begin{funcdesc}{ssl}{sock\optional{, keyfile, certfile}}
Fred Drake9081bb12001-09-25 15:48:11 +0000269Initiate a SSL connection over the socket \var{sock}. \var{keyfile} is
270the name of a PEM formatted file that contains your private
271key. \var{certfile} is a PEM formatted certificate chain file. On
272success, a new \class{SSLObject} is returned.
273
Fred Drake0aa811c2001-10-20 04:24:09 +0000274\warning{This does not do any certificate verification!}
Fred Drake9081bb12001-09-25 15:48:11 +0000275\end{funcdesc}
276
Fred Draked883ca11998-03-10 05:20:33 +0000277\begin{funcdesc}{fromfd}{fd, family, type\optional{, proto}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000278Build a socket object from an existing file descriptor (an integer as
Fred Draked883ca11998-03-10 05:20:33 +0000279returned by a file object's \method{fileno()} method). Address family,
Fred Drake318c0b11999-04-21 17:29:14 +0000280socket type and protocol number are as for the \function{socket()} function
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000281above. The file descriptor should refer to a socket, but this is not
282checked --- subsequent operations on the object may fail if the file
283descriptor is invalid. This function is rarely needed, but can be
284used to get or set socket options on a socket passed to a program as
Fred Drake87fa3aa2001-12-21 17:45:03 +0000285standard input or output (such as a server started by the \UNIX{} inet
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000286daemon).
Fred Drake87fa3aa2001-12-21 17:45:03 +0000287Availability: \UNIX.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000288\end{funcdesc}
289
Guido van Rossumbda7ca71996-12-02 17:24:10 +0000290\begin{funcdesc}{ntohl}{x}
Fred Drakec5aec051997-12-08 21:25:41 +0000291Convert 32-bit integers from network to host byte order. On machines
292where the host byte order is the same as network byte order, this is a
293no-op; otherwise, it performs a 4-byte swap operation.
294\end{funcdesc}
295
296\begin{funcdesc}{ntohs}{x}
297Convert 16-bit integers from network to host byte order. On machines
298where the host byte order is the same as network byte order, this is a
299no-op; otherwise, it performs a 2-byte swap operation.
300\end{funcdesc}
301
302\begin{funcdesc}{htonl}{x}
303Convert 32-bit integers from host to network byte order. On machines
304where the host byte order is the same as network byte order, this is a
305no-op; otherwise, it performs a 4-byte swap operation.
306\end{funcdesc}
307
308\begin{funcdesc}{htons}{x}
309Convert 16-bit integers from host to network byte order. On machines
310where the host byte order is the same as network byte order, this is a
311no-op; otherwise, it performs a 2-byte swap operation.
Guido van Rossumbda7ca71996-12-02 17:24:10 +0000312\end{funcdesc}
313
Fred Drakee6fb1c41999-09-16 15:50:00 +0000314\begin{funcdesc}{inet_aton}{ip_string}
Fred Drake87fa3aa2001-12-21 17:45:03 +0000315Convert an IPv4 address from dotted-quad string format (for example,
316'123.45.67.89') to 32-bit packed binary format, as a string four
Fred Drakee6fb1c41999-09-16 15:50:00 +0000317characters in length.
318
319Useful when conversing with a program that uses the standard C library
320and needs objects of type \ctype{struct in_addr}, which is the C type
321for the 32-bit packed binary this function returns.
322
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000323If the IPv4 address string passed to this function is invalid,
Fred Drakee6fb1c41999-09-16 15:50:00 +0000324\exception{socket.error} will be raised. Note that exactly what is
325valid depends on the underlying C implementation of
326\cfunction{inet_aton()}.
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000327
328\function{inet_aton} does not support IPv6, and
329\function{getnameinfo()} should be used instead for IPv4/v6 dual stack support.
Fred Drakee6fb1c41999-09-16 15:50:00 +0000330\end{funcdesc}
331
332\begin{funcdesc}{inet_ntoa}{packed_ip}
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000333Convert a 32-bit packed IPv4 address (a string four characters in
Fred Drakee6fb1c41999-09-16 15:50:00 +0000334length) to its standard dotted-quad string representation
Fred Drake87fa3aa2001-12-21 17:45:03 +0000335(for example, '123.45.67.89').
Fred Drakee6fb1c41999-09-16 15:50:00 +0000336
337Useful when conversing with a program that uses the standard C library
338and needs objects of type \ctype{struct in_addr}, which is the C type
339for the 32-bit packed binary this function takes as an argument.
340
341If the string passed to this function is not exactly 4 bytes in
342length, \exception{socket.error} will be raised.
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000343
344\function{inet_ntoa} does not support IPv6, and
345\function{getnameinfo()} should be used instead for IPv4/v6 dual stack support.
Fred Drakee6fb1c41999-09-16 15:50:00 +0000346\end{funcdesc}
347
Fred Drake5451d671997-10-13 21:31:02 +0000348\begin{datadesc}{SocketType}
Guido van Rossum2335c5e1997-05-21 14:41:42 +0000349This is a Python type object that represents the socket object type.
Fred Draked883ca11998-03-10 05:20:33 +0000350It is the same as \code{type(socket(...))}.
Guido van Rossum2335c5e1997-05-21 14:41:42 +0000351\end{datadesc}
352
Fred Drakeaa7524c2000-07-06 18:37:08 +0000353
354\begin{seealso}
355 \seemodule{SocketServer}{Classes that simplify writing network servers.}
356\end{seealso}
357
358
Fred Drakea94f6761999-08-05 13:41:04 +0000359\subsection{Socket Objects \label{socket-objects}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000360
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000361Socket objects have the following methods. Except for
Fred Draked883ca11998-03-10 05:20:33 +0000362\method{makefile()} these correspond to \UNIX{} system calls
363applicable to sockets.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000364
Fred Drake3f1c4721998-04-03 07:04:45 +0000365\begin{methoddesc}[socket]{accept}{}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000366Accept a connection.
367The socket must be bound to an address and listening for connections.
368The return value is a pair \code{(\var{conn}, \var{address})}
369where \var{conn} is a \emph{new} socket object usable to send and
370receive data on the connection, and \var{address} is the address bound
371to the socket on the other end of the connection.
Fred Drake3f1c4721998-04-03 07:04:45 +0000372\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000373
Fred Drake3f1c4721998-04-03 07:04:45 +0000374\begin{methoddesc}[socket]{bind}{address}
Guido van Rossuma84ec511994-06-23 12:13:52 +0000375Bind the socket to \var{address}. The socket must not already be bound.
Fred Drake7d686902000-04-04 17:48:30 +0000376(The format of \var{address} depends on the address family --- see
Fred Drake0aa811c2001-10-20 04:24:09 +0000377above.) \note{This method has historically accepted a pair
Fred Drake7d686902000-04-04 17:48:30 +0000378of parameters for \constant{AF_INET} addresses instead of only a
Eric S. Raymond83210262001-01-10 19:34:52 +0000379tuple. This was never intentional and is no longer be available in
Fred Drake0aa811c2001-10-20 04:24:09 +0000380Python 2.0.}
Fred Drake3f1c4721998-04-03 07:04:45 +0000381\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000382
Fred Drake3f1c4721998-04-03 07:04:45 +0000383\begin{methoddesc}[socket]{close}{}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000384Close the socket. All future operations on the socket object will fail.
385The remote end will receive no more data (after queued data is flushed).
386Sockets are automatically closed when they are garbage-collected.
Fred Drake3f1c4721998-04-03 07:04:45 +0000387\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000388
Fred Drake3f1c4721998-04-03 07:04:45 +0000389\begin{methoddesc}[socket]{connect}{address}
Guido van Rossuma84ec511994-06-23 12:13:52 +0000390Connect to a remote socket at \var{address}.
Fred Draked883ca11998-03-10 05:20:33 +0000391(The format of \var{address} depends on the address family --- see
Fred Drake0aa811c2001-10-20 04:24:09 +0000392above.) \note{This method has historically accepted a pair
Fred Drake7d686902000-04-04 17:48:30 +0000393of parameters for \constant{AF_INET} addresses instead of only a
Eric S. Raymond83210262001-01-10 19:34:52 +0000394tuple. This was never intentional and is no longer available in
Fred Drake0aa811c2001-10-20 04:24:09 +0000395Python 2.0 and later.}
Fred Drake3f1c4721998-04-03 07:04:45 +0000396\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000397
Fred Drake3f1c4721998-04-03 07:04:45 +0000398\begin{methoddesc}[socket]{connect_ex}{address}
Guido van Rossumeefcba61997-12-09 19:47:24 +0000399Like \code{connect(\var{address})}, but return an error indicator
Fred Drakeb0bc7f21999-05-06 22:03:50 +0000400instead of raising an exception for errors returned by the C-level
401\cfunction{connect()} call (other problems, such as ``host not found,''
402can still raise exceptions). The error indicator is \code{0} if the
Fred Draked883ca11998-03-10 05:20:33 +0000403operation succeeded, otherwise the value of the \cdata{errno}
Fred Drake87fa3aa2001-12-21 17:45:03 +0000404variable. This is useful to support, for example, asynchronous connects.
Fred Drake0aa811c2001-10-20 04:24:09 +0000405\note{This method has historically accepted a pair of
Fred Drake7d686902000-04-04 17:48:30 +0000406parameters for \constant{AF_INET} addresses instead of only a tuple.
Eric S. Raymond83210262001-01-10 19:34:52 +0000407This was never intentional and is no longer be available in Python
Fred Drake0aa811c2001-10-20 04:24:09 +00004082.0 and later.}
Fred Drake3f1c4721998-04-03 07:04:45 +0000409\end{methoddesc}
Guido van Rossumf7790c61997-11-18 15:29:20 +0000410
Fred Drake3f1c4721998-04-03 07:04:45 +0000411\begin{methoddesc}[socket]{fileno}{}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000412Return the socket's file descriptor (a small integer). This is useful
Fred Draked883ca11998-03-10 05:20:33 +0000413with \function{select.select()}.
Fred Drake3f1c4721998-04-03 07:04:45 +0000414\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000415
Fred Drake3f1c4721998-04-03 07:04:45 +0000416\begin{methoddesc}[socket]{getpeername}{}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000417Return the remote address to which the socket is connected. This is
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000418useful to find out the port number of a remote IPv4/v6 socket, for instance.
Guido van Rossum86751151995-02-28 17:14:32 +0000419(The format of the address returned depends on the address family ---
Guido van Rossum781db5d1994-08-05 13:37:36 +0000420see above.) On some systems this function is not supported.
Fred Drake3f1c4721998-04-03 07:04:45 +0000421\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000422
Fred Drake3f1c4721998-04-03 07:04:45 +0000423\begin{methoddesc}[socket]{getsockname}{}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000424Return the socket's own address. This is useful to find out the port
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000425number of an IPv4/v6 socket, for instance.
Guido van Rossum86751151995-02-28 17:14:32 +0000426(The format of the address returned depends on the address family ---
Guido van Rossuma84ec511994-06-23 12:13:52 +0000427see above.)
Fred Drake3f1c4721998-04-03 07:04:45 +0000428\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000429
Fred Drake3f1c4721998-04-03 07:04:45 +0000430\begin{methoddesc}[socket]{getsockopt}{level, optname\optional{, buflen}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000431Return the value of the given socket option (see the \UNIX{} man page
Fred Draked883ca11998-03-10 05:20:33 +0000432\manpage{getsockopt}{2}). The needed symbolic constants
433(\constant{SO_*} etc.) are defined in this module. If \var{buflen}
Guido van Rossum470be141995-03-17 16:07:09 +0000434is absent, an integer option is assumed and its integer value
Guido van Rossum8df36371995-02-27 17:52:15 +0000435is returned by the function. If \var{buflen} is present, it specifies
436the maximum length of the buffer used to receive the option in, and
Guido van Rossum470be141995-03-17 16:07:09 +0000437this buffer is returned as a string. It is up to the caller to decode
Guido van Rossum8df36371995-02-27 17:52:15 +0000438the contents of the buffer (see the optional built-in module
Fred Drake318c0b11999-04-21 17:29:14 +0000439\refmodule{struct} for a way to decode C structures encoded as strings).
Fred Drake3f1c4721998-04-03 07:04:45 +0000440\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000441
Fred Drake3f1c4721998-04-03 07:04:45 +0000442\begin{methoddesc}[socket]{listen}{backlog}
Guido van Rossum470be141995-03-17 16:07:09 +0000443Listen for connections made to the socket. The \var{backlog} argument
444specifies the maximum number of queued connections and should be at
445least 1; the maximum value is system-dependent (usually 5).
Fred Drake3f1c4721998-04-03 07:04:45 +0000446\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000447
Fred Drake3f1c4721998-04-03 07:04:45 +0000448\begin{methoddesc}[socket]{makefile}{\optional{mode\optional{, bufsize}}}
Guido van Rossum470be141995-03-17 16:07:09 +0000449Return a \dfn{file object} associated with the socket. (File objects
Fred Drakea94f6761999-08-05 13:41:04 +0000450are described in \ref{bltin-file-objects}, ``File Objects.'')
Fred Draked883ca11998-03-10 05:20:33 +0000451The file object references a \cfunction{dup()}ped version of the
452socket file descriptor, so the file object and socket object may be
Fred Drakea94f6761999-08-05 13:41:04 +0000453closed or garbage-collected independently.
454\index{I/O control!buffering}The optional \var{mode}
Fred Draked883ca11998-03-10 05:20:33 +0000455and \var{bufsize} arguments are interpreted the same way as by the
Fred Drakeaad8bb52001-10-19 17:22:29 +0000456built-in \function{file()} function; see ``Built-in Functions''
457(section \ref{built-in-funcs}) for more information.
Fred Drake87fa3aa2001-12-21 17:45:03 +0000458Availability: \UNIX.
Fred Drake3f1c4721998-04-03 07:04:45 +0000459\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000460
Fred Drake3f1c4721998-04-03 07:04:45 +0000461\begin{methoddesc}[socket]{recv}{bufsize\optional{, flags}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000462Receive data from the socket. The return value is a string representing
463the data received. The maximum amount of data to be received
464at once is specified by \var{bufsize}. See the \UNIX{} manual page
Fred Draked883ca11998-03-10 05:20:33 +0000465\manpage{recv}{2} for the meaning of the optional argument
466\var{flags}; it defaults to zero.
Fred Drake3f1c4721998-04-03 07:04:45 +0000467\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000468
Fred Drake3f1c4721998-04-03 07:04:45 +0000469\begin{methoddesc}[socket]{recvfrom}{bufsize\optional{, flags}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000470Receive data from the socket. The return value is a pair
471\code{(\var{string}, \var{address})} where \var{string} is a string
472representing the data received and \var{address} is the address of the
Guido van Rossum470be141995-03-17 16:07:09 +0000473socket sending the data. The optional \var{flags} argument has the
Fred Draked883ca11998-03-10 05:20:33 +0000474same meaning as for \method{recv()} above.
Guido van Rossum86751151995-02-28 17:14:32 +0000475(The format of \var{address} depends on the address family --- see above.)
Fred Drake3f1c4721998-04-03 07:04:45 +0000476\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000477
Fred Drake3f1c4721998-04-03 07:04:45 +0000478\begin{methoddesc}[socket]{send}{string\optional{, flags}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000479Send data to the socket. The socket must be connected to a remote
Guido van Rossum470be141995-03-17 16:07:09 +0000480socket. The optional \var{flags} argument has the same meaning as for
Fred Draked883ca11998-03-10 05:20:33 +0000481\method{recv()} above. Returns the number of bytes sent.
Fred Drake39368c12001-12-05 05:25:59 +0000482Applications are responsible for checking that all data has been sent;
483if only some of the data was transmitted, the application needs to
484attempt delivery of the remaining data.
485\end{methoddesc}
486
487\begin{methoddesc}[socket]{sendall}{string\optional{, flags}}
488Send data to the socket. The socket must be connected to a remote
489socket. The optional \var{flags} argument has the same meaning as for
490\method{recv()} above. Unlike \method{send()}, this method continues
491to send data from \var{string} until either all data has been sent or
492an error occurs. \code{None} is returned on success. On error, an
493exception is raised, and there is no way to determine how much data,
494if any, was successfully sent.
Fred Drake3f1c4721998-04-03 07:04:45 +0000495\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000496
Fred Drake3f1c4721998-04-03 07:04:45 +0000497\begin{methoddesc}[socket]{sendto}{string\optional{, flags}, address}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000498Send data to the socket. The socket should not be connected to a
499remote socket, since the destination socket is specified by
Fred Draked883ca11998-03-10 05:20:33 +0000500\var{address}. The optional \var{flags} argument has the same
501meaning as for \method{recv()} above. Return the number of bytes sent.
Guido van Rossum86751151995-02-28 17:14:32 +0000502(The format of \var{address} depends on the address family --- see above.)
Fred Drake3f1c4721998-04-03 07:04:45 +0000503\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000504
Fred Drake3f1c4721998-04-03 07:04:45 +0000505\begin{methoddesc}[socket]{setblocking}{flag}
Guido van Rossum91951481994-09-07 14:39:14 +0000506Set blocking or non-blocking mode of the socket: if \var{flag} is 0,
507the socket is set to non-blocking, else to blocking mode. Initially
508all sockets are in blocking mode. In non-blocking mode, if a
Fred Drake318c0b11999-04-21 17:29:14 +0000509\method{recv()} call doesn't find any data, or if a
510\method{send()} call can't immediately dispose of the data, a
511\exception{error} exception is raised; in blocking mode, the calls
512block until they can proceed.
Fred Drake3f1c4721998-04-03 07:04:45 +0000513\end{methoddesc}
Guido van Rossum91951481994-09-07 14:39:14 +0000514
Fred Drake3f1c4721998-04-03 07:04:45 +0000515\begin{methoddesc}[socket]{setsockopt}{level, optname, value}
Fred Drake9a748aa2000-06-30 04:21:41 +0000516Set the value of the given socket option (see the \UNIX{} manual page
Fred Draked883ca11998-03-10 05:20:33 +0000517\manpage{setsockopt}{2}). The needed symbolic constants are defined in
518the \module{socket} module (\code{SO_*} etc.). The value can be an
Guido van Rossum8df36371995-02-27 17:52:15 +0000519integer or a string representing a buffer. In the latter case it is
520up to the caller to ensure that the string contains the proper bits
521(see the optional built-in module
Fred Drake318c0b11999-04-21 17:29:14 +0000522\refmodule{struct}\refbimodindex{struct} for a way to encode C
523structures as strings).
Fred Drake3f1c4721998-04-03 07:04:45 +0000524\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000525
Fred Drake3f1c4721998-04-03 07:04:45 +0000526\begin{methoddesc}[socket]{shutdown}{how}
Fred Draked883ca11998-03-10 05:20:33 +0000527Shut down one or both halves of the connection. If \var{how} is
528\code{0}, further receives are disallowed. If \var{how} is \code{1},
529further sends are disallowed. If \var{how} is \code{2}, further sends
530and receives are disallowed.
Fred Drake3f1c4721998-04-03 07:04:45 +0000531\end{methoddesc}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000532
Fred Draked883ca11998-03-10 05:20:33 +0000533Note that there are no methods \method{read()} or \method{write()};
534use \method{recv()} and \method{send()} without \var{flags} argument
535instead.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000536
Fred Drakeaa7524c2000-07-06 18:37:08 +0000537
Fred Drake9081bb12001-09-25 15:48:11 +0000538\subsection{SSL Objects \label{ssl-objects}}
539
540SSL objects have the following methods.
541
542\begin{methoddesc}{write}{s}
543Writes the string \var{s} to the on the object's SSL connection.
544The return value is the number of bytes written.
545\end{methoddesc}
546
547\begin{methoddesc}{read}{\optional{n}}
548If \var{n} is provided, read \var{n} bytes from the SSL connection, otherwise
549read until EOF. The return value is a string of the bytes read.
550\end{methoddesc}
551
Fred Drakeaa7524c2000-07-06 18:37:08 +0000552\subsection{Example \label{socket-example}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000553
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000554Here are four minimal example programs using the TCP/IP protocol:\ a
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000555server that echoes all data that it receives back (servicing only one
556client), and a client using it. Note that a server must perform the
Fred Draked883ca11998-03-10 05:20:33 +0000557sequence \function{socket()}, \method{bind()}, \method{listen()},
558\method{accept()} (possibly repeating the \method{accept()} to service
559more than one client), while a client only needs the sequence
560\function{socket()}, \method{connect()}. Also note that the server
561does not \method{send()}/\method{recv()} on the
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000562socket it is listening on but on the new socket returned by
Fred Draked883ca11998-03-10 05:20:33 +0000563\method{accept()}.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000564
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000565The first two examples support IPv4 only.
566
Fred Drake19479911998-02-13 06:58:54 +0000567\begin{verbatim}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000568# Echo server program
Fred Drakeef52f602000-10-10 20:36:29 +0000569import socket
570
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000571HOST = '' # Symbolic name meaning the local host
Fred Drakeef52f602000-10-10 20:36:29 +0000572PORT = 50007 # Arbitrary non-privileged port
573s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Fred Drake3d69c0e2000-05-03 19:40:32 +0000574s.bind((HOST, PORT))
Guido van Rossum5da57551994-03-02 10:52:16 +0000575s.listen(1)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000576conn, addr = s.accept()
577print 'Connected by', addr
578while 1:
579 data = conn.recv(1024)
580 if not data: break
581 conn.send(data)
582conn.close()
Fred Drake19479911998-02-13 06:58:54 +0000583\end{verbatim}
Fred Draked883ca11998-03-10 05:20:33 +0000584
Fred Drake19479911998-02-13 06:58:54 +0000585\begin{verbatim}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000586# Echo client program
Fred Drakeef52f602000-10-10 20:36:29 +0000587import socket
588
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000589HOST = 'daring.cwi.nl' # The remote host
590PORT = 50007 # The same port as used by the server
Fred Drakeef52f602000-10-10 20:36:29 +0000591s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Fred Drake3d69c0e2000-05-03 19:40:32 +0000592s.connect((HOST, PORT))
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000593s.send('Hello, world')
594data = s.recv(1024)
595s.close()
596print 'Received', `data`
Fred Drake19479911998-02-13 06:58:54 +0000597\end{verbatim}
Martin v. Löwisc9908c42001-08-04 22:22:45 +0000598
599The next two examples are identical to the above two, but support both
600IPv4 and IPv6.
601The server side will listen to the first address family available
602(it should listen to both instead).
603On most of IPv6-ready systems, IPv6 will take precedence
604and the server may not accept IPv4 traffic.
605The client side will try to connect to the all addresses returned as a result
606of the name resolution, and sends traffic to the first one connected
607successfully.
608
609\begin{verbatim}
610# Echo server program
611import socket
612import sys
613
614HOST = '' # Symbolic name meaning the local host
615PORT = 50007 # Arbitrary non-privileged port
616s = None
617for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
618 af, socktype, proto, canonname, sa = res
619 try:
620 s = socket.socket(af, socktype, proto)
621 except socket.error, msg:
622 s = None
623 continue
624 try:
625 s.bind(sa)
626 s.listen(1)
627 except socket.error, msg:
628 s.close()
629 s = None
630 continue
631 break
632if s is None:
633 print 'could not open socket'
634 sys.exit(1)
635conn, addr = s.accept()
636print 'Connected by', addr
637while 1:
638 data = conn.recv(1024)
639 if not data: break
640 conn.send(data)
641conn.close()
642\end{verbatim}
643
644\begin{verbatim}
645# Echo client program
646import socket
647import sys
648
649HOST = 'daring.cwi.nl' # The remote host
650PORT = 50007 # The same port as used by the server
651s = None
652for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM):
653 af, socktype, proto, canonname, sa = res
654 try:
655 s = socket.socket(af, socktype, proto)
656 except socket.error, msg:
657 s = None
658 continue
659 try:
660 s.connect(sa)
661 except socket.error, msg:
662 s.close()
663 s = None
664 continue
665 break
666if s is None:
667 print 'could not open socket'
668 sys.exit(1)
669s.send('Hello, world')
670data = s.recv(1024)
671s.close()
672print 'Received', `data`
673\end{verbatim}