blob: b105b228d7972acfb08c1ed863cda5bb44d0ed7e [file] [log] [blame]
Guido van Rossum5fdeeea1994-01-02 01:22:07 +00001\section{Built-in Module \sectcode{socket}}
2
3\bimodindex{socket}
4This module provides access to the BSD {\em socket} interface.
5It is available on \UNIX{} systems that support this interface.
6
7For an introduction to socket programming (in C), see the following
8papers: \emph{An Introductory 4.3BSD Interprocess Communication
9Tutorial}, by Stuart Sechrest and \emph{An Advanced 4.3BSD Interprocess
10Communication Tutorial}, by Samuel J. Leffler et al, both in the
11\UNIX{} Programmer's Manual, Supplementary Documents 1 (sections PS1:7
12and PS1:8). The \UNIX{} manual pages for the various socket-related
Guido van Rossum6bb1adc1995-03-13 10:03:32 +000013system calls are also a valuable source of information on the details of
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000014socket semantics.
15
16The Python interface is a straightforward transliteration of the
17\UNIX{} system call and library interface for sockets to Python's
18object-oriented style: the \code{socket()} function returns a
19\dfn{socket object} whose methods implement the various socket system
20calls. Parameter types are somewhat higer-level than in the C
21interface: as with \code{read()} and \code{write()} operations on Python
22files, buffer allocation on receive operations is automatic, and
23buffer length is implicit on send operations.
24
25Socket addresses are represented as a single string for the
26\code{AF_UNIX} address family and as a pair
27\code{(\var{host}, \var{port})} for the \code{AF_INET} address family,
28where \var{host} is a string representing
29either a hostname in Internet domain notation like
30\code{'daring.cwi.nl'} or an IP address like \code{'100.50.200.5'},
31and \var{port} is an integral port number. Other address families are
32currently not supported. The address format required by a particular
33socket object is automatically selected based on the address family
34specified when the socket object was created.
35
36All errors raise exceptions. The normal exceptions for invalid
37argument types and out-of-memory conditions can be raised; errors
38related to socket or address semantics raise the error \code{socket.error}.
39
Guido van Rossum470be141995-03-17 16:07:09 +000040Non-blocking mode is supported through the \code{setblocking()}
41method.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000042
43The module \code{socket} exports the following constants and functions:
44
45\renewcommand{\indexsubitem}{(in module socket)}
46\begin{excdesc}{error}
47This exception is raised for socket- or address-related errors.
48The accompanying value is either a string telling what went wrong or a
49pair \code{(\var{errno}, \var{string})}
50representing an error returned by a system
51call, similar to the value accompanying \code{posix.error}.
52\end{excdesc}
53
54\begin{datadesc}{AF_UNIX}
55\dataline{AF_INET}
56These constants represent the address (and protocol) families,
Guido van Rossum781db5d1994-08-05 13:37:36 +000057used for the first argument to \code{socket()}. If the \code{AF_UNIX}
58constant is not defined then this protocol is unsupported.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000059\end{datadesc}
60
61\begin{datadesc}{SOCK_STREAM}
62\dataline{SOCK_DGRAM}
Guido van Rossum781db5d1994-08-05 13:37:36 +000063\dataline{SOCK_RAW}
64\dataline{SOCK_RDM}
65\dataline{SOCK_SEQPACKET}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000066These constants represent the socket types,
67used for the second argument to \code{socket()}.
Guido van Rossum781db5d1994-08-05 13:37:36 +000068(Only \code{SOCK_STREAM} and
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000069\code{SOCK_DGRAM} appear to be generally useful.)
70\end{datadesc}
71
Guido van Rossumed2bad81995-02-16 16:29:18 +000072\begin{datadesc}{SO_*}
73\dataline{SOMAXCONN}
74\dataline{MSG_*}
75\dataline{SOL_*}
76\dataline{IPPROTO_*}
77\dataline{IPPORT_*}
78\dataline{INADDR_*}
79\dataline{IP_*}
Guido van Rossum6bb1adc1995-03-13 10:03:32 +000080Many constants of these forms, documented in the \UNIX{} documentation on
Guido van Rossumed2bad81995-02-16 16:29:18 +000081sockets and/or the IP protocol, are also defined in the socket module.
82They are generally used in arguments to the \code{setsockopt} and
83\code{getsockopt} methods of socket objects. In most cases, only
Guido van Rossum6bb1adc1995-03-13 10:03:32 +000084those symbols that are defined in the \UNIX{} header files are defined;
Guido van Rossumed2bad81995-02-16 16:29:18 +000085for a few symbols, default values are provided.
86\end{datadesc}
87
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000088\begin{funcdesc}{gethostbyname}{hostname}
89Translate a host name to IP address format. The IP address is
90returned as a string, e.g., \code{'100.50.200.5'}. If the host name
91is an IP address itself it is returned unchanged.
92\end{funcdesc}
93
Guido van Rossum781db5d1994-08-05 13:37:36 +000094\begin{funcdesc}{gethostname}{}
Guido van Rossum16d6e711994-08-08 12:30:22 +000095Return a string containing the hostname of the machine where
96the Python interpreter is currently executing. If you want to know the
97current machine's IP address, use
Guido van Rossum470be141995-03-17 16:07:09 +000098\code{socket.gethostbyname(socket.gethostname())}.
Guido van Rossum31cce971995-01-04 19:17:34 +000099\end{funcdesc}
100
101\begin{funcdesc}{gethostbyaddr}{ip_address}
102Return a triple \code{(hostname, aliaslist, ipaddrlist)} where
103\code{hostname} is the primary host name responding to the given
104\var{ip_address}, \code{aliaslist} is a (possibly empty) list of
105alternative host names for the same address, and \code{ipaddrlist} is
106a list of IP addresses for the same interface on the same
107host (most likely containing only a single address).
Guido van Rossum781db5d1994-08-05 13:37:36 +0000108\end{funcdesc}
109
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000110\begin{funcdesc}{getservbyname}{servicename\, protocolname}
111Translate an Internet service name and protocol name to a port number
112for that service. The protocol name should be \code{'tcp'} or
113\code{'udp'}.
114\end{funcdesc}
115
Guido van Rossum6bb1adc1995-03-13 10:03:32 +0000116\begin{funcdesc}{socket}{family\, type\optional{\, proto}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000117Create a new socket using the given address family, socket type and
118protocol number. The address family should be \code{AF_INET} or
119\code{AF_UNIX}. The socket type should be \code{SOCK_STREAM},
120\code{SOCK_DGRAM} or perhaps one of the other \samp{SOCK_} constants.
121The protocol number is usually zero and may be omitted in that case.
122\end{funcdesc}
123
Guido van Rossum6bb1adc1995-03-13 10:03:32 +0000124\begin{funcdesc}{fromfd}{fd\, family\, type\optional{\, proto}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000125Build a socket object from an existing file descriptor (an integer as
126returned by a file object's \code{fileno} method). Address family,
127socket type and protocol number are as for the \code{socket} function
128above. The file descriptor should refer to a socket, but this is not
129checked --- subsequent operations on the object may fail if the file
130descriptor is invalid. This function is rarely needed, but can be
131used to get or set socket options on a socket passed to a program as
Guido van Rossum6bb1adc1995-03-13 10:03:32 +0000132standard input or output (e.g.\ a server started by the \UNIX{} inet
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000133daemon).
134\end{funcdesc}
135
Guido van Rossumbda7ca71996-12-02 17:24:10 +0000136\begin{funcdesc}{ntohl}{x}
137\funcline{ntohs}{x}
138\funcline{htonl}{x}
139\funcline{htons}{x}
140These functions convert 32-bit (`l' suffix) and 16-bit (`s' suffix)
141integers between network and host byte order. On machines where the
142host byte order is the same as the network byte order, they are no-ops
143(assuming the values fit in the indicated size); otherwise, they
144perform 2-byte or 4-byte swap operations.
145\end{funcdesc}
146
Guido van Rossum470be141995-03-17 16:07:09 +0000147\subsection{Socket Objects}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000148
149\noindent
150Socket objects have the following methods. Except for
151\code{makefile()} these correspond to \UNIX{} system calls applicable to
152sockets.
153
154\renewcommand{\indexsubitem}{(socket method)}
155\begin{funcdesc}{accept}{}
156Accept a connection.
157The socket must be bound to an address and listening for connections.
158The return value is a pair \code{(\var{conn}, \var{address})}
159where \var{conn} is a \emph{new} socket object usable to send and
160receive data on the connection, and \var{address} is the address bound
161to the socket on the other end of the connection.
162\end{funcdesc}
163
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000164\begin{funcdesc}{bind}{address}
Guido van Rossuma84ec511994-06-23 12:13:52 +0000165Bind the socket to \var{address}. The socket must not already be bound.
Guido van Rossum86751151995-02-28 17:14:32 +0000166(The format of \var{address} depends on the address family --- see above.)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000167\end{funcdesc}
168
169\begin{funcdesc}{close}{}
170Close the socket. All future operations on the socket object will fail.
171The remote end will receive no more data (after queued data is flushed).
172Sockets are automatically closed when they are garbage-collected.
173\end{funcdesc}
174
175\begin{funcdesc}{connect}{address}
Guido van Rossuma84ec511994-06-23 12:13:52 +0000176Connect to a remote socket at \var{address}.
Guido van Rossum86751151995-02-28 17:14:32 +0000177(The format of \var{address} depends on the address family --- see above.)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000178\end{funcdesc}
179
180\begin{funcdesc}{fileno}{}
181Return the socket's file descriptor (a small integer). This is useful
182with \code{select}.
183\end{funcdesc}
184
185\begin{funcdesc}{getpeername}{}
186Return the remote address to which the socket is connected. This is
187useful to find out the port number of a remote IP socket, for instance.
Guido van Rossum86751151995-02-28 17:14:32 +0000188(The format of the address returned depends on the address family ---
Guido van Rossum781db5d1994-08-05 13:37:36 +0000189see above.) On some systems this function is not supported.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000190\end{funcdesc}
191
192\begin{funcdesc}{getsockname}{}
193Return the socket's own address. This is useful to find out the port
194number of an IP socket, for instance.
Guido van Rossum86751151995-02-28 17:14:32 +0000195(The format of the address returned depends on the address family ---
Guido van Rossuma84ec511994-06-23 12:13:52 +0000196see above.)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000197\end{funcdesc}
198
Guido van Rossum6bb1adc1995-03-13 10:03:32 +0000199\begin{funcdesc}{getsockopt}{level\, optname\optional{\, buflen}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000200Return the value of the given socket option (see the \UNIX{} man page
Guido van Rossum470be141995-03-17 16:07:09 +0000201{\it getsockopt}(2)). The needed symbolic constants (\code{SO_*} etc.)
202are defined in this module. If \var{buflen}
203is absent, an integer option is assumed and its integer value
Guido van Rossum8df36371995-02-27 17:52:15 +0000204is returned by the function. If \var{buflen} is present, it specifies
205the maximum length of the buffer used to receive the option in, and
Guido van Rossum470be141995-03-17 16:07:09 +0000206this buffer is returned as a string. It is up to the caller to decode
Guido van Rossum8df36371995-02-27 17:52:15 +0000207the contents of the buffer (see the optional built-in module
208\code{struct} for a way to decode C structures encoded as strings).
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000209\end{funcdesc}
210
211\begin{funcdesc}{listen}{backlog}
Guido van Rossum470be141995-03-17 16:07:09 +0000212Listen for connections made to the socket. The \var{backlog} argument
213specifies the maximum number of queued connections and should be at
214least 1; the maximum value is system-dependent (usually 5).
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000215\end{funcdesc}
216
Guido van Rossum470be141995-03-17 16:07:09 +0000217\begin{funcdesc}{makefile}{\optional{mode\optional{\, bufsize}}}
218Return a \dfn{file object} associated with the socket. (File objects
219were described earlier under Built-in Types.) The file object
220references a \code{dup()}ped version of the socket file descriptor, so
221the file object and socket object may be closed or garbage-collected
222independently. The optional \var{mode} and \var{bufsize} arguments
223are interpreted the same way as by the built-in
224\code{open()} function.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000225\end{funcdesc}
226
Guido van Rossum6bb1adc1995-03-13 10:03:32 +0000227\begin{funcdesc}{recv}{bufsize\optional{\, flags}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000228Receive data from the socket. The return value is a string representing
229the data received. The maximum amount of data to be received
230at once is specified by \var{bufsize}. See the \UNIX{} manual page
231for the meaning of the optional argument \var{flags}; it defaults to
232zero.
233\end{funcdesc}
234
Guido van Rossum470be141995-03-17 16:07:09 +0000235\begin{funcdesc}{recvfrom}{bufsize\optional{\, flags}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000236Receive data from the socket. The return value is a pair
237\code{(\var{string}, \var{address})} where \var{string} is a string
238representing the data received and \var{address} is the address of the
Guido van Rossum470be141995-03-17 16:07:09 +0000239socket sending the data. The optional \var{flags} argument has the
240same meaning as for \code{recv()} above.
Guido van Rossum86751151995-02-28 17:14:32 +0000241(The format of \var{address} depends on the address family --- see above.)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000242\end{funcdesc}
243
Guido van Rossum470be141995-03-17 16:07:09 +0000244\begin{funcdesc}{send}{string\optional{\, flags}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000245Send data to the socket. The socket must be connected to a remote
Guido van Rossum470be141995-03-17 16:07:09 +0000246socket. The optional \var{flags} argument has the same meaning as for
247\code{recv()} above. Return the number of bytes sent.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000248\end{funcdesc}
249
Guido van Rossum470be141995-03-17 16:07:09 +0000250\begin{funcdesc}{sendto}{string\optional{\, flags}\, address}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000251Send data to the socket. The socket should not be connected to a
252remote socket, since the destination socket is specified by
Guido van Rossum470be141995-03-17 16:07:09 +0000253\code{address}. The optional \var{flags} argument has the same
254meaning as for \code{recv()} above. Return the number of bytes sent.
Guido van Rossum86751151995-02-28 17:14:32 +0000255(The format of \var{address} depends on the address family --- see above.)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000256\end{funcdesc}
257
Guido van Rossum91951481994-09-07 14:39:14 +0000258\begin{funcdesc}{setblocking}{flag}
259Set blocking or non-blocking mode of the socket: if \var{flag} is 0,
260the socket is set to non-blocking, else to blocking mode. Initially
261all sockets are in blocking mode. In non-blocking mode, if a
262\code{recv} call doesn't find any data, or if a \code{send} call can't
263immediately dispose of the data, a \code{socket.error} exception is
264raised; in blocking mode, the calls block until they can proceed.
265\end{funcdesc}
266
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000267\begin{funcdesc}{setsockopt}{level\, optname\, value}
268Set the value of the given socket option (see the \UNIX{} man page
Guido van Rossum8df36371995-02-27 17:52:15 +0000269{\it setsockopt}(2)). The needed symbolic constants are defined in
270the \code{socket} module (\code{SO_*} etc.). The value can be an
271integer or a string representing a buffer. In the latter case it is
272up to the caller to ensure that the string contains the proper bits
273(see the optional built-in module
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000274\code{struct} for a way to encode C structures as strings).
275\end{funcdesc}
276
277\begin{funcdesc}{shutdown}{how}
278Shut down one or both halves of the connection. If \var{how} is \code{0},
279further receives are disallowed. If \var{how} is \code{1}, further sends are
280disallowed. If \var{how} is \code{2}, further sends and receives are
281disallowed.
282\end{funcdesc}
283
284Note that there are no methods \code{read()} or \code{write()}; use
285\code{recv()} and \code{send()} without \var{flags} argument instead.
286
287\subsection{Example}
288\nodename{Socket Example}
289
Guido van Rossum6bb1adc1995-03-13 10:03:32 +0000290Here are two minimal example programs using the TCP/IP protocol:\ a
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000291server that echoes all data that it receives back (servicing only one
292client), and a client using it. Note that a server must perform the
293sequence \code{socket}, \code{bind}, \code{listen}, \code{accept}
294(possibly repeating the \code{accept} to service more than one client),
295while a client only needs the sequence \code{socket}, \code{connect}.
296Also note that the server does not \code{send}/\code{receive} on the
297socket it is listening on but on the new socket returned by
298\code{accept}.
299
300\bcode\begin{verbatim}
301# Echo server program
302from socket import *
303HOST = '' # Symbolic name meaning the local host
304PORT = 50007 # Arbitrary non-privileged server
305s = socket(AF_INET, SOCK_STREAM)
306s.bind(HOST, PORT)
Guido van Rossum5da57551994-03-02 10:52:16 +0000307s.listen(1)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000308conn, addr = s.accept()
309print 'Connected by', addr
310while 1:
311 data = conn.recv(1024)
312 if not data: break
313 conn.send(data)
314conn.close()
315\end{verbatim}\ecode
316
317\bcode\begin{verbatim}
318# Echo client program
319from socket import *
320HOST = 'daring.cwi.nl' # The remote host
321PORT = 50007 # The same port as used by the server
322s = socket(AF_INET, SOCK_STREAM)
323s.connect(HOST, PORT)
324s.send('Hello, world')
325data = s.recv(1024)
326s.close()
327print 'Received', `data`
328\end{verbatim}\ecode