blob: 1026ef1858634bbf985d2482f6bdfc0be6d033c1 [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
13system calls also a valuable source of information on the details of
14socket 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
40Non-blocking and asynchronous mode are not supported; see module
41\code{select} for a way to do non-blocking socket I/O.
42
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
72\begin{funcdesc}{gethostbyname}{hostname}
73Translate a host name to IP address format. The IP address is
74returned as a string, e.g., \code{'100.50.200.5'}. If the host name
75is an IP address itself it is returned unchanged.
76\end{funcdesc}
77
Guido van Rossum781db5d1994-08-05 13:37:36 +000078\begin{funcdesc}{gethostname}{}
Guido van Rossum16d6e711994-08-08 12:30:22 +000079Return a string containing the hostname of the machine where
80the Python interpreter is currently executing. If you want to know the
81current machine's IP address, use
Guido van Rossum31cce971995-01-04 19:17:34 +000082\code{socket.gethostbyname(socket.gethostname())} instead.
83\end{funcdesc}
84
85\begin{funcdesc}{gethostbyaddr}{ip_address}
86Return a triple \code{(hostname, aliaslist, ipaddrlist)} where
87\code{hostname} is the primary host name responding to the given
88\var{ip_address}, \code{aliaslist} is a (possibly empty) list of
89alternative host names for the same address, and \code{ipaddrlist} is
90a list of IP addresses for the same interface on the same
91host (most likely containing only a single address).
Guido van Rossum781db5d1994-08-05 13:37:36 +000092\end{funcdesc}
93
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000094\begin{funcdesc}{getservbyname}{servicename\, protocolname}
95Translate an Internet service name and protocol name to a port number
96for that service. The protocol name should be \code{'tcp'} or
97\code{'udp'}.
98\end{funcdesc}
99
100\begin{funcdesc}{socket}{family\, type\, proto}
101Create a new socket using the given address family, socket type and
102protocol number. The address family should be \code{AF_INET} or
103\code{AF_UNIX}. The socket type should be \code{SOCK_STREAM},
104\code{SOCK_DGRAM} or perhaps one of the other \samp{SOCK_} constants.
105The protocol number is usually zero and may be omitted in that case.
106\end{funcdesc}
107
108\begin{funcdesc}{fromfd}{fd\, family\, type\, proto}
109Build a socket object from an existing file descriptor (an integer as
110returned by a file object's \code{fileno} method). Address family,
111socket type and protocol number are as for the \code{socket} function
112above. The file descriptor should refer to a socket, but this is not
113checked --- subsequent operations on the object may fail if the file
114descriptor is invalid. This function is rarely needed, but can be
115used to get or set socket options on a socket passed to a program as
116standard input or output (e.g. a server started by the \UNIX{} inet
117daemon).
118\end{funcdesc}
119
120\subsection{Socket Object Methods}
121
122\noindent
123Socket objects have the following methods. Except for
124\code{makefile()} these correspond to \UNIX{} system calls applicable to
125sockets.
126
127\renewcommand{\indexsubitem}{(socket method)}
128\begin{funcdesc}{accept}{}
129Accept a connection.
130The socket must be bound to an address and listening for connections.
131The return value is a pair \code{(\var{conn}, \var{address})}
132where \var{conn} is a \emph{new} socket object usable to send and
133receive data on the connection, and \var{address} is the address bound
134to the socket on the other end of the connection.
135\end{funcdesc}
136
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000137\begin{funcdesc}{bind}{address}
Guido van Rossuma84ec511994-06-23 12:13:52 +0000138Bind the socket to \var{address}. The socket must not already be bound.
139(The format of \var{address} depends on the address family -- see above.)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000140\end{funcdesc}
141
142\begin{funcdesc}{close}{}
143Close the socket. All future operations on the socket object will fail.
144The remote end will receive no more data (after queued data is flushed).
145Sockets are automatically closed when they are garbage-collected.
146\end{funcdesc}
147
148\begin{funcdesc}{connect}{address}
Guido van Rossuma84ec511994-06-23 12:13:52 +0000149Connect to a remote socket at \var{address}.
150(The format of \var{address} depends on the address family -- see above.)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000151\end{funcdesc}
152
153\begin{funcdesc}{fileno}{}
154Return the socket's file descriptor (a small integer). This is useful
155with \code{select}.
156\end{funcdesc}
157
158\begin{funcdesc}{getpeername}{}
159Return the remote address to which the socket is connected. This is
160useful to find out the port number of a remote IP socket, for instance.
Guido van Rossuma84ec511994-06-23 12:13:52 +0000161(The format of the address returned depends on the address family --
Guido van Rossum781db5d1994-08-05 13:37:36 +0000162see above.) On some systems this function is not supported.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000163\end{funcdesc}
164
165\begin{funcdesc}{getsockname}{}
166Return the socket's own address. This is useful to find out the port
167number of an IP socket, for instance.
Guido van Rossuma84ec511994-06-23 12:13:52 +0000168(The format of the address returned depends on the address family --
169see above.)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000170\end{funcdesc}
171
172\begin{funcdesc}{getsockopt}{level\, optname\, buflen}
173Return the value of the given socket option (see the \UNIX{} man page
174{\it getsockopt}(2)). The needed symbolic constants are defined in module
175SOCKET. If the optional third argument is absent, an integer option
176is assumed and its integer value is returned by the function. If
177\var{buflen} is present, it specifies the maximum length of the buffer used
178to receive the option in, and this buffer is returned as a string.
179It's up to the caller to decode the contents of the buffer (see the
180optional built-in module \code{struct} for a way to decode C structures
181encoded as strings).
182\end{funcdesc}
183
184\begin{funcdesc}{listen}{backlog}
185Listen for connections made to the socket.
Guido van Rossum5da57551994-03-02 10:52:16 +0000186The argument specifies the maximum number of queued connections and
187should be at least 1; the maximum value is system-dependent.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000188\end{funcdesc}
189
190\begin{funcdesc}{makefile}{mode}
191Return a \dfn{file object} associated with the socket.
192(File objects were described earlier under Built-in Types.)
193The file object references a \code{dup}ped version of the socket file
194descriptor, so the file object and socket object may be closed or
195garbage-collected independently.
196\end{funcdesc}
197
198\begin{funcdesc}{recv}{bufsize\, flags}
199Receive data from the socket. The return value is a string representing
200the data received. The maximum amount of data to be received
201at once is specified by \var{bufsize}. See the \UNIX{} manual page
202for the meaning of the optional argument \var{flags}; it defaults to
203zero.
204\end{funcdesc}
205
206\begin{funcdesc}{recvfrom}{bufsize}
207Receive data from the socket. The return value is a pair
208\code{(\var{string}, \var{address})} where \var{string} is a string
209representing the data received and \var{address} is the address of the
210socket sending the data.
Guido van Rossuma84ec511994-06-23 12:13:52 +0000211(The format of \var{address} depends on the address family -- see above.)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000212\end{funcdesc}
213
214\begin{funcdesc}{send}{string}
215Send data to the socket. The socket must be connected to a remote
Guido van Rossumab3a2501994-08-01 12:18:36 +0000216socket. Return the number of bytes sent.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000217\end{funcdesc}
218
219\begin{funcdesc}{sendto}{string\, address}
220Send data to the socket. The socket should not be connected to a
221remote socket, since the destination socket is specified by
Guido van Rossumab3a2501994-08-01 12:18:36 +0000222\code{address}. Return the number of bytes sent.
Guido van Rossuma84ec511994-06-23 12:13:52 +0000223(The format of \var{address} depends on the address family -- see above.)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000224\end{funcdesc}
225
Guido van Rossum91951481994-09-07 14:39:14 +0000226\begin{funcdesc}{setblocking}{flag}
227Set blocking or non-blocking mode of the socket: if \var{flag} is 0,
228the socket is set to non-blocking, else to blocking mode. Initially
229all sockets are in blocking mode. In non-blocking mode, if a
230\code{recv} call doesn't find any data, or if a \code{send} call can't
231immediately dispose of the data, a \code{socket.error} exception is
232raised; in blocking mode, the calls block until they can proceed.
233\end{funcdesc}
234
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000235\begin{funcdesc}{setsockopt}{level\, optname\, value}
236Set the value of the given socket option (see the \UNIX{} man page
237{\it setsockopt}(2)). The needed symbolic constants are defined in module
238\code{SOCKET}. The value can be an integer or a string representing a
239buffer. In the latter case it is up to the caller to ensure that the
240string contains the proper bits (see the optional built-in module
241\code{struct} for a way to encode C structures as strings).
242\end{funcdesc}
243
244\begin{funcdesc}{shutdown}{how}
245Shut down one or both halves of the connection. If \var{how} is \code{0},
246further receives are disallowed. If \var{how} is \code{1}, further sends are
247disallowed. If \var{how} is \code{2}, further sends and receives are
248disallowed.
249\end{funcdesc}
250
251Note that there are no methods \code{read()} or \code{write()}; use
252\code{recv()} and \code{send()} without \var{flags} argument instead.
253
254\subsection{Example}
255\nodename{Socket Example}
256
257Here are two minimal example programs using the TCP/IP protocol: a
258server that echoes all data that it receives back (servicing only one
259client), and a client using it. Note that a server must perform the
260sequence \code{socket}, \code{bind}, \code{listen}, \code{accept}
261(possibly repeating the \code{accept} to service more than one client),
262while a client only needs the sequence \code{socket}, \code{connect}.
263Also note that the server does not \code{send}/\code{receive} on the
264socket it is listening on but on the new socket returned by
265\code{accept}.
266
267\bcode\begin{verbatim}
268# Echo server program
269from socket import *
270HOST = '' # Symbolic name meaning the local host
271PORT = 50007 # Arbitrary non-privileged server
272s = socket(AF_INET, SOCK_STREAM)
273s.bind(HOST, PORT)
Guido van Rossum5da57551994-03-02 10:52:16 +0000274s.listen(1)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000275conn, addr = s.accept()
276print 'Connected by', addr
277while 1:
278 data = conn.recv(1024)
279 if not data: break
280 conn.send(data)
281conn.close()
282\end{verbatim}\ecode
283
284\bcode\begin{verbatim}
285# Echo client program
286from socket import *
287HOST = 'daring.cwi.nl' # The remote host
288PORT = 50007 # The same port as used by the server
289s = socket(AF_INET, SOCK_STREAM)
290s.connect(HOST, PORT)
291s.send('Hello, world')
292data = s.recv(1024)
293s.close()
294print 'Received', `data`
295\end{verbatim}\ecode