blob: 375d38ed4bebe2d69f854926dec92258d7360897 [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,
57used for the first argument to \code{socket()}.
58\end{datadesc}
59
60\begin{datadesc}{SOCK_STREAM}
61\dataline{SOCK_DGRAM}
62These constants represent the socket types,
63used for the second argument to \code{socket()}.
64(There are other types, but only \code{SOCK_STREAM} and
65\code{SOCK_DGRAM} appear to be generally useful.)
66\end{datadesc}
67
68\begin{funcdesc}{gethostbyname}{hostname}
69Translate a host name to IP address format. The IP address is
70returned as a string, e.g., \code{'100.50.200.5'}. If the host name
71is an IP address itself it is returned unchanged.
72\end{funcdesc}
73
74\begin{funcdesc}{getservbyname}{servicename\, protocolname}
75Translate an Internet service name and protocol name to a port number
76for that service. The protocol name should be \code{'tcp'} or
77\code{'udp'}.
78\end{funcdesc}
79
80\begin{funcdesc}{socket}{family\, type\, proto}
81Create a new socket using the given address family, socket type and
82protocol number. The address family should be \code{AF_INET} or
83\code{AF_UNIX}. The socket type should be \code{SOCK_STREAM},
84\code{SOCK_DGRAM} or perhaps one of the other \samp{SOCK_} constants.
85The protocol number is usually zero and may be omitted in that case.
86\end{funcdesc}
87
88\begin{funcdesc}{fromfd}{fd\, family\, type\, proto}
89Build a socket object from an existing file descriptor (an integer as
90returned by a file object's \code{fileno} method). Address family,
91socket type and protocol number are as for the \code{socket} function
92above. The file descriptor should refer to a socket, but this is not
93checked --- subsequent operations on the object may fail if the file
94descriptor is invalid. This function is rarely needed, but can be
95used to get or set socket options on a socket passed to a program as
96standard input or output (e.g. a server started by the \UNIX{} inet
97daemon).
98\end{funcdesc}
99
100\subsection{Socket Object Methods}
101
102\noindent
103Socket objects have the following methods. Except for
104\code{makefile()} these correspond to \UNIX{} system calls applicable to
105sockets.
106
107\renewcommand{\indexsubitem}{(socket method)}
108\begin{funcdesc}{accept}{}
109Accept a connection.
110The socket must be bound to an address and listening for connections.
111The return value is a pair \code{(\var{conn}, \var{address})}
112where \var{conn} is a \emph{new} socket object usable to send and
113receive data on the connection, and \var{address} is the address bound
114to the socket on the other end of the connection.
115\end{funcdesc}
116
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000117\begin{funcdesc}{bind}{address}
118Bind the socket to an address. The socket must not already be bound.
119\end{funcdesc}
120
121\begin{funcdesc}{close}{}
122Close the socket. All future operations on the socket object will fail.
123The remote end will receive no more data (after queued data is flushed).
124Sockets are automatically closed when they are garbage-collected.
125\end{funcdesc}
126
127\begin{funcdesc}{connect}{address}
128Connect to a remote socket.
129\end{funcdesc}
130
131\begin{funcdesc}{fileno}{}
132Return the socket's file descriptor (a small integer). This is useful
133with \code{select}.
134\end{funcdesc}
135
136\begin{funcdesc}{getpeername}{}
137Return the remote address to which the socket is connected. This is
138useful to find out the port number of a remote IP socket, for instance.
139\end{funcdesc}
140
141\begin{funcdesc}{getsockname}{}
142Return the socket's own address. This is useful to find out the port
143number of an IP socket, for instance.
144\end{funcdesc}
145
146\begin{funcdesc}{getsockopt}{level\, optname\, buflen}
147Return the value of the given socket option (see the \UNIX{} man page
148{\it getsockopt}(2)). The needed symbolic constants are defined in module
149SOCKET. If the optional third argument is absent, an integer option
150is assumed and its integer value is returned by the function. If
151\var{buflen} is present, it specifies the maximum length of the buffer used
152to receive the option in, and this buffer is returned as a string.
153It's up to the caller to decode the contents of the buffer (see the
154optional built-in module \code{struct} for a way to decode C structures
155encoded as strings).
156\end{funcdesc}
157
158\begin{funcdesc}{listen}{backlog}
159Listen for connections made to the socket.
Guido van Rossum5da57551994-03-02 10:52:16 +0000160The argument specifies the maximum number of queued connections and
161should be at least 1; the maximum value is system-dependent.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000162\end{funcdesc}
163
164\begin{funcdesc}{makefile}{mode}
165Return a \dfn{file object} associated with the socket.
166(File objects were described earlier under Built-in Types.)
167The file object references a \code{dup}ped version of the socket file
168descriptor, so the file object and socket object may be closed or
169garbage-collected independently.
170\end{funcdesc}
171
172\begin{funcdesc}{recv}{bufsize\, flags}
173Receive data from the socket. The return value is a string representing
174the data received. The maximum amount of data to be received
175at once is specified by \var{bufsize}. See the \UNIX{} manual page
176for the meaning of the optional argument \var{flags}; it defaults to
177zero.
178\end{funcdesc}
179
180\begin{funcdesc}{recvfrom}{bufsize}
181Receive data from the socket. The return value is a pair
182\code{(\var{string}, \var{address})} where \var{string} is a string
183representing the data received and \var{address} is the address of the
184socket sending the data.
185\end{funcdesc}
186
187\begin{funcdesc}{send}{string}
188Send data to the socket. The socket must be connected to a remote
189socket.
190\end{funcdesc}
191
192\begin{funcdesc}{sendto}{string\, address}
193Send data to the socket. The socket should not be connected to a
194remote socket, since the destination socket is specified by
195\code{address}.
196\end{funcdesc}
197
198\begin{funcdesc}{setsockopt}{level\, optname\, value}
199Set the value of the given socket option (see the \UNIX{} man page
200{\it setsockopt}(2)). The needed symbolic constants are defined in module
201\code{SOCKET}. The value can be an integer or a string representing a
202buffer. In the latter case it is up to the caller to ensure that the
203string contains the proper bits (see the optional built-in module
204\code{struct} for a way to encode C structures as strings).
205\end{funcdesc}
206
207\begin{funcdesc}{shutdown}{how}
208Shut down one or both halves of the connection. If \var{how} is \code{0},
209further receives are disallowed. If \var{how} is \code{1}, further sends are
210disallowed. If \var{how} is \code{2}, further sends and receives are
211disallowed.
212\end{funcdesc}
213
214Note that there are no methods \code{read()} or \code{write()}; use
215\code{recv()} and \code{send()} without \var{flags} argument instead.
216
217\subsection{Example}
218\nodename{Socket Example}
219
220Here are two minimal example programs using the TCP/IP protocol: a
221server that echoes all data that it receives back (servicing only one
222client), and a client using it. Note that a server must perform the
223sequence \code{socket}, \code{bind}, \code{listen}, \code{accept}
224(possibly repeating the \code{accept} to service more than one client),
225while a client only needs the sequence \code{socket}, \code{connect}.
226Also note that the server does not \code{send}/\code{receive} on the
227socket it is listening on but on the new socket returned by
228\code{accept}.
229
230\bcode\begin{verbatim}
231# Echo server program
232from socket import *
233HOST = '' # Symbolic name meaning the local host
234PORT = 50007 # Arbitrary non-privileged server
235s = socket(AF_INET, SOCK_STREAM)
236s.bind(HOST, PORT)
Guido van Rossum5da57551994-03-02 10:52:16 +0000237s.listen(1)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000238conn, addr = s.accept()
239print 'Connected by', addr
240while 1:
241 data = conn.recv(1024)
242 if not data: break
243 conn.send(data)
244conn.close()
245\end{verbatim}\ecode
246
247\bcode\begin{verbatim}
248# Echo client program
249from socket import *
250HOST = 'daring.cwi.nl' # The remote host
251PORT = 50007 # The same port as used by the server
252s = socket(AF_INET, SOCK_STREAM)
253s.connect(HOST, PORT)
254s.send('Hello, world')
255data = s.recv(1024)
256s.close()
257print 'Received', `data`
258\end{verbatim}\ecode