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