blob: 60b9d15b889bd33a9b712fb97d78db5da352c78a [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
82\code{socket.gethostbyname( socket.gethostname() )} instead.
Guido van Rossum781db5d1994-08-05 13:37:36 +000083\end{funcdesc}
84
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000085\begin{funcdesc}{getservbyname}{servicename\, protocolname}
86Translate an Internet service name and protocol name to a port number
87for that service. The protocol name should be \code{'tcp'} or
88\code{'udp'}.
89\end{funcdesc}
90
91\begin{funcdesc}{socket}{family\, type\, proto}
92Create a new socket using the given address family, socket type and
93protocol number. The address family should be \code{AF_INET} or
94\code{AF_UNIX}. The socket type should be \code{SOCK_STREAM},
95\code{SOCK_DGRAM} or perhaps one of the other \samp{SOCK_} constants.
96The protocol number is usually zero and may be omitted in that case.
97\end{funcdesc}
98
99\begin{funcdesc}{fromfd}{fd\, family\, type\, proto}
100Build a socket object from an existing file descriptor (an integer as
101returned by a file object's \code{fileno} method). Address family,
102socket type and protocol number are as for the \code{socket} function
103above. The file descriptor should refer to a socket, but this is not
104checked --- subsequent operations on the object may fail if the file
105descriptor is invalid. This function is rarely needed, but can be
106used to get or set socket options on a socket passed to a program as
107standard input or output (e.g. a server started by the \UNIX{} inet
108daemon).
109\end{funcdesc}
110
111\subsection{Socket Object Methods}
112
113\noindent
114Socket objects have the following methods. Except for
115\code{makefile()} these correspond to \UNIX{} system calls applicable to
116sockets.
117
118\renewcommand{\indexsubitem}{(socket method)}
119\begin{funcdesc}{accept}{}
120Accept a connection.
121The socket must be bound to an address and listening for connections.
122The return value is a pair \code{(\var{conn}, \var{address})}
123where \var{conn} is a \emph{new} socket object usable to send and
124receive data on the connection, and \var{address} is the address bound
125to the socket on the other end of the connection.
126\end{funcdesc}
127
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000128\begin{funcdesc}{bind}{address}
Guido van Rossuma84ec511994-06-23 12:13:52 +0000129Bind the socket to \var{address}. The socket must not already be bound.
130(The format of \var{address} depends on the address family -- see above.)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000131\end{funcdesc}
132
133\begin{funcdesc}{close}{}
134Close the socket. All future operations on the socket object will fail.
135The remote end will receive no more data (after queued data is flushed).
136Sockets are automatically closed when they are garbage-collected.
137\end{funcdesc}
138
139\begin{funcdesc}{connect}{address}
Guido van Rossuma84ec511994-06-23 12:13:52 +0000140Connect to a remote socket at \var{address}.
141(The format of \var{address} depends on the address family -- see above.)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000142\end{funcdesc}
143
144\begin{funcdesc}{fileno}{}
145Return the socket's file descriptor (a small integer). This is useful
146with \code{select}.
147\end{funcdesc}
148
149\begin{funcdesc}{getpeername}{}
150Return the remote address to which the socket is connected. This is
151useful to find out the port number of a remote IP socket, for instance.
Guido van Rossuma84ec511994-06-23 12:13:52 +0000152(The format of the address returned depends on the address family --
Guido van Rossum781db5d1994-08-05 13:37:36 +0000153see above.) On some systems this function is not supported.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000154\end{funcdesc}
155
156\begin{funcdesc}{getsockname}{}
157Return the socket's own address. This is useful to find out the port
158number of an IP socket, for instance.
Guido van Rossuma84ec511994-06-23 12:13:52 +0000159(The format of the address returned depends on the address family --
160see above.)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000161\end{funcdesc}
162
163\begin{funcdesc}{getsockopt}{level\, optname\, buflen}
164Return the value of the given socket option (see the \UNIX{} man page
165{\it getsockopt}(2)). The needed symbolic constants are defined in module
166SOCKET. If the optional third argument is absent, an integer option
167is assumed and its integer value is returned by the function. If
168\var{buflen} is present, it specifies the maximum length of the buffer used
169to receive the option in, and this buffer is returned as a string.
170It's up to the caller to decode the contents of the buffer (see the
171optional built-in module \code{struct} for a way to decode C structures
172encoded as strings).
173\end{funcdesc}
174
175\begin{funcdesc}{listen}{backlog}
176Listen for connections made to the socket.
Guido van Rossum5da57551994-03-02 10:52:16 +0000177The argument specifies the maximum number of queued connections and
178should be at least 1; the maximum value is system-dependent.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000179\end{funcdesc}
180
181\begin{funcdesc}{makefile}{mode}
182Return a \dfn{file object} associated with the socket.
183(File objects were described earlier under Built-in Types.)
184The file object references a \code{dup}ped version of the socket file
185descriptor, so the file object and socket object may be closed or
186garbage-collected independently.
187\end{funcdesc}
188
189\begin{funcdesc}{recv}{bufsize\, flags}
190Receive data from the socket. The return value is a string representing
191the data received. The maximum amount of data to be received
192at once is specified by \var{bufsize}. See the \UNIX{} manual page
193for the meaning of the optional argument \var{flags}; it defaults to
194zero.
195\end{funcdesc}
196
197\begin{funcdesc}{recvfrom}{bufsize}
198Receive data from the socket. The return value is a pair
199\code{(\var{string}, \var{address})} where \var{string} is a string
200representing the data received and \var{address} is the address of the
201socket sending the data.
Guido van Rossuma84ec511994-06-23 12:13:52 +0000202(The format of \var{address} depends on the address family -- see above.)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000203\end{funcdesc}
204
205\begin{funcdesc}{send}{string}
206Send data to the socket. The socket must be connected to a remote
Guido van Rossumab3a2501994-08-01 12:18:36 +0000207socket. Return the number of bytes sent.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000208\end{funcdesc}
209
210\begin{funcdesc}{sendto}{string\, address}
211Send data to the socket. The socket should not be connected to a
212remote socket, since the destination socket is specified by
Guido van Rossumab3a2501994-08-01 12:18:36 +0000213\code{address}. Return the number of bytes sent.
Guido van Rossuma84ec511994-06-23 12:13:52 +0000214(The format of \var{address} depends on the address family -- see above.)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000215\end{funcdesc}
216
Guido van Rossum91951481994-09-07 14:39:14 +0000217\begin{funcdesc}{setblocking}{flag}
218Set blocking or non-blocking mode of the socket: if \var{flag} is 0,
219the socket is set to non-blocking, else to blocking mode. Initially
220all sockets are in blocking mode. In non-blocking mode, if a
221\code{recv} call doesn't find any data, or if a \code{send} call can't
222immediately dispose of the data, a \code{socket.error} exception is
223raised; in blocking mode, the calls block until they can proceed.
224\end{funcdesc}
225
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000226\begin{funcdesc}{setsockopt}{level\, optname\, value}
227Set the value of the given socket option (see the \UNIX{} man page
228{\it setsockopt}(2)). The needed symbolic constants are defined in module
229\code{SOCKET}. The value can be an integer or a string representing a
230buffer. In the latter case it is up to the caller to ensure that the
231string contains the proper bits (see the optional built-in module
232\code{struct} for a way to encode C structures as strings).
233\end{funcdesc}
234
235\begin{funcdesc}{shutdown}{how}
236Shut down one or both halves of the connection. If \var{how} is \code{0},
237further receives are disallowed. If \var{how} is \code{1}, further sends are
238disallowed. If \var{how} is \code{2}, further sends and receives are
239disallowed.
240\end{funcdesc}
241
242Note that there are no methods \code{read()} or \code{write()}; use
243\code{recv()} and \code{send()} without \var{flags} argument instead.
244
245\subsection{Example}
246\nodename{Socket Example}
247
248Here are two minimal example programs using the TCP/IP protocol: a
249server that echoes all data that it receives back (servicing only one
250client), and a client using it. Note that a server must perform the
251sequence \code{socket}, \code{bind}, \code{listen}, \code{accept}
252(possibly repeating the \code{accept} to service more than one client),
253while a client only needs the sequence \code{socket}, \code{connect}.
254Also note that the server does not \code{send}/\code{receive} on the
255socket it is listening on but on the new socket returned by
256\code{accept}.
257
258\bcode\begin{verbatim}
259# Echo server program
260from socket import *
261HOST = '' # Symbolic name meaning the local host
262PORT = 50007 # Arbitrary non-privileged server
263s = socket(AF_INET, SOCK_STREAM)
264s.bind(HOST, PORT)
Guido van Rossum5da57551994-03-02 10:52:16 +0000265s.listen(1)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000266conn, addr = s.accept()
267print 'Connected by', addr
268while 1:
269 data = conn.recv(1024)
270 if not data: break
271 conn.send(data)
272conn.close()
273\end{verbatim}\ecode
274
275\bcode\begin{verbatim}
276# Echo client program
277from socket import *
278HOST = 'daring.cwi.nl' # The remote host
279PORT = 50007 # The same port as used by the server
280s = socket(AF_INET, SOCK_STREAM)
281s.connect(HOST, PORT)
282s.send('Hello, world')
283data = s.recv(1024)
284s.close()
285print 'Received', `data`
286\end{verbatim}\ecode