blob: 8599451cf0e272cc4759a95b4396648c35225690 [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}
Guido van Rossuma84ec511994-06-23 12:13:52 +0000118Bind the socket to \var{address}. The socket must not already be bound.
119(The format of \var{address} depends on the address family -- see above.)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000120\end{funcdesc}
121
122\begin{funcdesc}{close}{}
123Close the socket. All future operations on the socket object will fail.
124The remote end will receive no more data (after queued data is flushed).
125Sockets are automatically closed when they are garbage-collected.
126\end{funcdesc}
127
128\begin{funcdesc}{connect}{address}
Guido van Rossuma84ec511994-06-23 12:13:52 +0000129Connect to a remote socket at \var{address}.
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}{fileno}{}
134Return the socket's file descriptor (a small integer). This is useful
135with \code{select}.
136\end{funcdesc}
137
138\begin{funcdesc}{getpeername}{}
139Return the remote address to which the socket is connected. This is
140useful to find out the port number of a remote IP socket, for instance.
Guido van Rossuma84ec511994-06-23 12:13:52 +0000141(The format of the address returned depends on the address family --
142see above.)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000143\end{funcdesc}
144
145\begin{funcdesc}{getsockname}{}
146Return the socket's own address. This is useful to find out the port
147number of an IP socket, for instance.
Guido van Rossuma84ec511994-06-23 12:13:52 +0000148(The format of the address returned depends on the address family --
149see above.)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000150\end{funcdesc}
151
152\begin{funcdesc}{getsockopt}{level\, optname\, buflen}
153Return the value of the given socket option (see the \UNIX{} man page
154{\it getsockopt}(2)). The needed symbolic constants are defined in module
155SOCKET. If the optional third argument is absent, an integer option
156is assumed and its integer value is returned by the function. If
157\var{buflen} is present, it specifies the maximum length of the buffer used
158to receive the option in, and this buffer is returned as a string.
159It's up to the caller to decode the contents of the buffer (see the
160optional built-in module \code{struct} for a way to decode C structures
161encoded as strings).
162\end{funcdesc}
163
164\begin{funcdesc}{listen}{backlog}
165Listen for connections made to the socket.
Guido van Rossum5da57551994-03-02 10:52:16 +0000166The argument specifies the maximum number of queued connections and
167should be at least 1; the maximum value is system-dependent.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000168\end{funcdesc}
169
170\begin{funcdesc}{makefile}{mode}
171Return a \dfn{file object} associated with the socket.
172(File objects were described earlier under Built-in Types.)
173The file object references a \code{dup}ped version of the socket file
174descriptor, so the file object and socket object may be closed or
175garbage-collected independently.
176\end{funcdesc}
177
178\begin{funcdesc}{recv}{bufsize\, flags}
179Receive data from the socket. The return value is a string representing
180the data received. The maximum amount of data to be received
181at once is specified by \var{bufsize}. See the \UNIX{} manual page
182for the meaning of the optional argument \var{flags}; it defaults to
183zero.
184\end{funcdesc}
185
186\begin{funcdesc}{recvfrom}{bufsize}
187Receive data from the socket. The return value is a pair
188\code{(\var{string}, \var{address})} where \var{string} is a string
189representing the data received and \var{address} is the address of the
190socket sending the data.
Guido van Rossuma84ec511994-06-23 12:13:52 +0000191(The format of \var{address} depends on the address family -- see above.)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000192\end{funcdesc}
193
194\begin{funcdesc}{send}{string}
195Send data to the socket. The socket must be connected to a remote
196socket.
197\end{funcdesc}
198
199\begin{funcdesc}{sendto}{string\, address}
200Send data to the socket. The socket should not be connected to a
201remote socket, since the destination socket is specified by
202\code{address}.
Guido van Rossuma84ec511994-06-23 12:13:52 +0000203(The format of \var{address} depends on the address family -- see above.)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000204\end{funcdesc}
205
206\begin{funcdesc}{setsockopt}{level\, optname\, value}
207Set the value of the given socket option (see the \UNIX{} man page
208{\it setsockopt}(2)). The needed symbolic constants are defined in module
209\code{SOCKET}. The value can be an integer or a string representing a
210buffer. In the latter case it is up to the caller to ensure that the
211string contains the proper bits (see the optional built-in module
212\code{struct} for a way to encode C structures as strings).
213\end{funcdesc}
214
215\begin{funcdesc}{shutdown}{how}
216Shut down one or both halves of the connection. If \var{how} is \code{0},
217further receives are disallowed. If \var{how} is \code{1}, further sends are
218disallowed. If \var{how} is \code{2}, further sends and receives are
219disallowed.
220\end{funcdesc}
221
222Note that there are no methods \code{read()} or \code{write()}; use
223\code{recv()} and \code{send()} without \var{flags} argument instead.
224
225\subsection{Example}
226\nodename{Socket Example}
227
228Here are two minimal example programs using the TCP/IP protocol: a
229server that echoes all data that it receives back (servicing only one
230client), and a client using it. Note that a server must perform the
231sequence \code{socket}, \code{bind}, \code{listen}, \code{accept}
232(possibly repeating the \code{accept} to service more than one client),
233while a client only needs the sequence \code{socket}, \code{connect}.
234Also note that the server does not \code{send}/\code{receive} on the
235socket it is listening on but on the new socket returned by
236\code{accept}.
237
238\bcode\begin{verbatim}
239# Echo server program
240from socket import *
241HOST = '' # Symbolic name meaning the local host
242PORT = 50007 # Arbitrary non-privileged server
243s = socket(AF_INET, SOCK_STREAM)
244s.bind(HOST, PORT)
Guido van Rossum5da57551994-03-02 10:52:16 +0000245s.listen(1)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000246conn, addr = s.accept()
247print 'Connected by', addr
248while 1:
249 data = conn.recv(1024)
250 if not data: break
251 conn.send(data)
252conn.close()
253\end{verbatim}\ecode
254
255\bcode\begin{verbatim}
256# Echo client program
257from socket import *
258HOST = 'daring.cwi.nl' # The remote host
259PORT = 50007 # The same port as used by the server
260s = socket(AF_INET, SOCK_STREAM)
261s.connect(HOST, PORT)
262s.send('Hello, world')
263data = s.recv(1024)
264s.close()
265print 'Received', `data`
266\end{verbatim}\ecode