blob: 8f6df692e7c488b15bf2ba6e42953be13b034f3c [file] [log] [blame]
Guido van Rossum5fdeeea1994-01-02 01:22:07 +00001\section{Built-in Module \sectcode{socket}}
Guido van Rossume47da0a1997-07-17 16:34:52 +00002\label{module-socket}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +00003
4\bimodindex{socket}
5This module provides access to the BSD {\em socket} interface.
6It is available on \UNIX{} systems that support this interface.
7
8For an introduction to socket programming (in C), see the following
9papers: \emph{An Introductory 4.3BSD Interprocess Communication
10Tutorial}, by Stuart Sechrest and \emph{An Advanced 4.3BSD Interprocess
11Communication Tutorial}, by Samuel J. Leffler et al, both in the
12\UNIX{} Programmer's Manual, Supplementary Documents 1 (sections PS1:7
13and PS1:8). The \UNIX{} manual pages for the various socket-related
Guido van Rossum6bb1adc1995-03-13 10:03:32 +000014system calls are also a valuable source of information on the details of
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000015socket semantics.
16
17The Python interface is a straightforward transliteration of the
18\UNIX{} system call and library interface for sockets to Python's
19object-oriented style: the \code{socket()} function returns a
20\dfn{socket object} whose methods implement the various socket system
Barry Warsawd44be3f1997-01-03 20:19:05 +000021calls. Parameter types are somewhat higher-level than in the C
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000022interface: as with \code{read()} and \code{write()} operations on Python
23files, buffer allocation on receive operations is automatic, and
24buffer length is implicit on send operations.
25
26Socket addresses are represented as a single string for the
27\code{AF_UNIX} address family and as a pair
28\code{(\var{host}, \var{port})} for the \code{AF_INET} address family,
29where \var{host} is a string representing
30either a hostname in Internet domain notation like
31\code{'daring.cwi.nl'} or an IP address like \code{'100.50.200.5'},
32and \var{port} is an integral port number. Other address families are
33currently not supported. The address format required by a particular
34socket object is automatically selected based on the address family
35specified when the socket object was created.
36
Guido van Rossume4f347e1997-05-09 02:21:51 +000037For IP addresses, two special forms are accepted instead of a host
38address: the empty string represents \code{INADDR_ANY}, and the string
39\code{"<broadcast>"} represents \code{INADDR_BROADCAST}.
40
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000041All errors raise exceptions. The normal exceptions for invalid
42argument types and out-of-memory conditions can be raised; errors
43related to socket or address semantics raise the error \code{socket.error}.
44
Guido van Rossum470be141995-03-17 16:07:09 +000045Non-blocking mode is supported through the \code{setblocking()}
46method.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000047
48The module \code{socket} exports the following constants and functions:
49
50\renewcommand{\indexsubitem}{(in module socket)}
51\begin{excdesc}{error}
52This exception is raised for socket- or address-related errors.
53The accompanying value is either a string telling what went wrong or a
54pair \code{(\var{errno}, \var{string})}
55representing an error returned by a system
56call, similar to the value accompanying \code{posix.error}.
57\end{excdesc}
58
59\begin{datadesc}{AF_UNIX}
60\dataline{AF_INET}
61These constants represent the address (and protocol) families,
Guido van Rossum781db5d1994-08-05 13:37:36 +000062used for the first argument to \code{socket()}. If the \code{AF_UNIX}
63constant is not defined then this protocol is unsupported.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000064\end{datadesc}
65
66\begin{datadesc}{SOCK_STREAM}
67\dataline{SOCK_DGRAM}
Guido van Rossum781db5d1994-08-05 13:37:36 +000068\dataline{SOCK_RAW}
69\dataline{SOCK_RDM}
70\dataline{SOCK_SEQPACKET}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000071These constants represent the socket types,
72used for the second argument to \code{socket()}.
Guido van Rossum781db5d1994-08-05 13:37:36 +000073(Only \code{SOCK_STREAM} and
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000074\code{SOCK_DGRAM} appear to be generally useful.)
75\end{datadesc}
76
Guido van Rossumed2bad81995-02-16 16:29:18 +000077\begin{datadesc}{SO_*}
78\dataline{SOMAXCONN}
79\dataline{MSG_*}
80\dataline{SOL_*}
81\dataline{IPPROTO_*}
82\dataline{IPPORT_*}
83\dataline{INADDR_*}
84\dataline{IP_*}
Guido van Rossum6bb1adc1995-03-13 10:03:32 +000085Many constants of these forms, documented in the \UNIX{} documentation on
Guido van Rossumed2bad81995-02-16 16:29:18 +000086sockets and/or the IP protocol, are also defined in the socket module.
87They are generally used in arguments to the \code{setsockopt} and
88\code{getsockopt} methods of socket objects. In most cases, only
Guido van Rossum6bb1adc1995-03-13 10:03:32 +000089those symbols that are defined in the \UNIX{} header files are defined;
Guido van Rossumed2bad81995-02-16 16:29:18 +000090for a few symbols, default values are provided.
91\end{datadesc}
92
Guido van Rossum5fdeeea1994-01-02 01:22:07 +000093\begin{funcdesc}{gethostbyname}{hostname}
94Translate a host name to IP address format. The IP address is
95returned as a string, e.g., \code{'100.50.200.5'}. If the host name
96is an IP address itself it is returned unchanged.
97\end{funcdesc}
98
Guido van Rossum781db5d1994-08-05 13:37:36 +000099\begin{funcdesc}{gethostname}{}
Guido van Rossum16d6e711994-08-08 12:30:22 +0000100Return a string containing the hostname of the machine where
101the Python interpreter is currently executing. If you want to know the
102current machine's IP address, use
Guido van Rossum470be141995-03-17 16:07:09 +0000103\code{socket.gethostbyname(socket.gethostname())}.
Guido van Rossumfe27a501997-01-11 17:04:56 +0000104Note: \code{gethostname()} doesn't always return the fully qualified
105domain name; use \code{socket.gethostbyaddr(socket.gethostname())}
106(see below).
Guido van Rossum31cce971995-01-04 19:17:34 +0000107\end{funcdesc}
108
109\begin{funcdesc}{gethostbyaddr}{ip_address}
110Return a triple \code{(hostname, aliaslist, ipaddrlist)} where
111\code{hostname} is the primary host name responding to the given
112\var{ip_address}, \code{aliaslist} is a (possibly empty) list of
113alternative host names for the same address, and \code{ipaddrlist} is
114a list of IP addresses for the same interface on the same
115host (most likely containing only a single address).
Guido van Rossumfe27a501997-01-11 17:04:56 +0000116To find the fully qualified domain name, check \var{hostname} and the
117items of \var{aliaslist} for an entry containing at least one period.
Guido van Rossum781db5d1994-08-05 13:37:36 +0000118\end{funcdesc}
119
Guido van Rossum62ac99e1996-12-19 16:43:25 +0000120\begin{funcdesc}{getprotobyname}{protocolname}
121Translate an Internet protocol name (e.g. \code{'icmp'}) to a constant
122suitable for passing as the (optional) third argument to the
123\code{socket()} function. This is usually only needed for sockets
124opened in ``raw'' mode (\code{SOCK_RAW}); for the normal socket modes,
125the correct protocol is chosen automatically if the protocol is
126omitted or zero.
127\end{funcdesc}
128
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000129\begin{funcdesc}{getservbyname}{servicename\, protocolname}
130Translate an Internet service name and protocol name to a port number
131for that service. The protocol name should be \code{'tcp'} or
132\code{'udp'}.
133\end{funcdesc}
134
Guido van Rossum6bb1adc1995-03-13 10:03:32 +0000135\begin{funcdesc}{socket}{family\, type\optional{\, proto}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000136Create a new socket using the given address family, socket type and
137protocol number. The address family should be \code{AF_INET} or
138\code{AF_UNIX}. The socket type should be \code{SOCK_STREAM},
139\code{SOCK_DGRAM} or perhaps one of the other \samp{SOCK_} constants.
140The protocol number is usually zero and may be omitted in that case.
141\end{funcdesc}
142
Guido van Rossum6bb1adc1995-03-13 10:03:32 +0000143\begin{funcdesc}{fromfd}{fd\, family\, type\optional{\, proto}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000144Build a socket object from an existing file descriptor (an integer as
145returned by a file object's \code{fileno} method). Address family,
146socket type and protocol number are as for the \code{socket} function
147above. The file descriptor should refer to a socket, but this is not
148checked --- subsequent operations on the object may fail if the file
149descriptor is invalid. This function is rarely needed, but can be
150used to get or set socket options on a socket passed to a program as
Guido van Rossum6bb1adc1995-03-13 10:03:32 +0000151standard input or output (e.g.\ a server started by the \UNIX{} inet
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000152daemon).
153\end{funcdesc}
154
Guido van Rossumbda7ca71996-12-02 17:24:10 +0000155\begin{funcdesc}{ntohl}{x}
Fred Drakec5aec051997-12-08 21:25:41 +0000156Convert 32-bit integers from network to host byte order. On machines
157where the host byte order is the same as network byte order, this is a
158no-op; otherwise, it performs a 4-byte swap operation.
159\end{funcdesc}
160
161\begin{funcdesc}{ntohs}{x}
162Convert 16-bit integers from network to host byte order. On machines
163where the host byte order is the same as network byte order, this is a
164no-op; otherwise, it performs a 2-byte swap operation.
165\end{funcdesc}
166
167\begin{funcdesc}{htonl}{x}
168Convert 32-bit integers from host to network byte order. On machines
169where the host byte order is the same as network byte order, this is a
170no-op; otherwise, it performs a 4-byte swap operation.
171\end{funcdesc}
172
173\begin{funcdesc}{htons}{x}
174Convert 16-bit integers from host to network byte order. On machines
175where the host byte order is the same as network byte order, this is a
176no-op; otherwise, it performs a 2-byte swap operation.
Guido van Rossumbda7ca71996-12-02 17:24:10 +0000177\end{funcdesc}
178
Fred Drake5451d671997-10-13 21:31:02 +0000179\begin{datadesc}{SocketType}
Guido van Rossum2335c5e1997-05-21 14:41:42 +0000180This is a Python type object that represents the socket object type.
181It is the same as \code{type(socket.socket(...))}.
182\end{datadesc}
183
Guido van Rossum470be141995-03-17 16:07:09 +0000184\subsection{Socket Objects}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000185
186\noindent
187Socket objects have the following methods. Except for
188\code{makefile()} these correspond to \UNIX{} system calls applicable to
189sockets.
190
191\renewcommand{\indexsubitem}{(socket method)}
192\begin{funcdesc}{accept}{}
193Accept a connection.
194The socket must be bound to an address and listening for connections.
195The return value is a pair \code{(\var{conn}, \var{address})}
196where \var{conn} is a \emph{new} socket object usable to send and
197receive data on the connection, and \var{address} is the address bound
198to the socket on the other end of the connection.
199\end{funcdesc}
200
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000201\begin{funcdesc}{bind}{address}
Guido van Rossuma84ec511994-06-23 12:13:52 +0000202Bind the socket to \var{address}. The socket must not already be bound.
Guido van Rossum86751151995-02-28 17:14:32 +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}{close}{}
207Close the socket. All future operations on the socket object will fail.
208The remote end will receive no more data (after queued data is flushed).
209Sockets are automatically closed when they are garbage-collected.
210\end{funcdesc}
211
212\begin{funcdesc}{connect}{address}
Guido van Rossuma84ec511994-06-23 12:13:52 +0000213Connect to a remote socket at \var{address}.
Guido van Rossum86751151995-02-28 17:14:32 +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 Rossumf7790c61997-11-18 15:29:20 +0000217\begin{funcdesc}{connect_ex}{address}
218Likecode{connect(\var{address})}, but return an error indicator
219instead of raising an exception. The error indicator is 0 if the
220operation succeeded, otherwise the value of the \code{errno}
221variable. This is useful e.g. for asynchronous connects.
222\end{funcdesc}
223
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000224\begin{funcdesc}{fileno}{}
225Return the socket's file descriptor (a small integer). This is useful
226with \code{select}.
227\end{funcdesc}
228
229\begin{funcdesc}{getpeername}{}
230Return the remote address to which the socket is connected. This is
231useful to find out the port number of a remote IP socket, for instance.
Guido van Rossum86751151995-02-28 17:14:32 +0000232(The format of the address returned depends on the address family ---
Guido van Rossum781db5d1994-08-05 13:37:36 +0000233see above.) On some systems this function is not supported.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000234\end{funcdesc}
235
236\begin{funcdesc}{getsockname}{}
237Return the socket's own address. This is useful to find out the port
238number of an IP socket, for instance.
Guido van Rossum86751151995-02-28 17:14:32 +0000239(The format of the address returned depends on the address family ---
Guido van Rossuma84ec511994-06-23 12:13:52 +0000240see above.)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000241\end{funcdesc}
242
Guido van Rossum6bb1adc1995-03-13 10:03:32 +0000243\begin{funcdesc}{getsockopt}{level\, optname\optional{\, buflen}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000244Return the value of the given socket option (see the \UNIX{} man page
Guido van Rossum470be141995-03-17 16:07:09 +0000245{\it getsockopt}(2)). The needed symbolic constants (\code{SO_*} etc.)
246are defined in this module. If \var{buflen}
247is absent, an integer option is assumed and its integer value
Guido van Rossum8df36371995-02-27 17:52:15 +0000248is returned by the function. If \var{buflen} is present, it specifies
249the maximum length of the buffer used to receive the option in, and
Guido van Rossum470be141995-03-17 16:07:09 +0000250this buffer is returned as a string. It is up to the caller to decode
Guido van Rossum8df36371995-02-27 17:52:15 +0000251the contents of the buffer (see the optional built-in module
252\code{struct} for a way to decode C structures encoded as strings).
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000253\end{funcdesc}
254
255\begin{funcdesc}{listen}{backlog}
Guido van Rossum470be141995-03-17 16:07:09 +0000256Listen for connections made to the socket. The \var{backlog} argument
257specifies the maximum number of queued connections and should be at
258least 1; the maximum value is system-dependent (usually 5).
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000259\end{funcdesc}
260
Guido van Rossum470be141995-03-17 16:07:09 +0000261\begin{funcdesc}{makefile}{\optional{mode\optional{\, bufsize}}}
262Return a \dfn{file object} associated with the socket. (File objects
263were described earlier under Built-in Types.) The file object
264references a \code{dup()}ped version of the socket file descriptor, so
265the file object and socket object may be closed or garbage-collected
266independently. The optional \var{mode} and \var{bufsize} arguments
267are interpreted the same way as by the built-in
268\code{open()} function.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000269\end{funcdesc}
270
Guido van Rossum6bb1adc1995-03-13 10:03:32 +0000271\begin{funcdesc}{recv}{bufsize\optional{\, flags}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000272Receive data from the socket. The return value is a string representing
273the data received. The maximum amount of data to be received
274at once is specified by \var{bufsize}. See the \UNIX{} manual page
275for the meaning of the optional argument \var{flags}; it defaults to
276zero.
277\end{funcdesc}
278
Guido van Rossum470be141995-03-17 16:07:09 +0000279\begin{funcdesc}{recvfrom}{bufsize\optional{\, flags}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000280Receive data from the socket. The return value is a pair
281\code{(\var{string}, \var{address})} where \var{string} is a string
282representing the data received and \var{address} is the address of the
Guido van Rossum470be141995-03-17 16:07:09 +0000283socket sending the data. The optional \var{flags} argument has the
284same meaning as for \code{recv()} above.
Guido van Rossum86751151995-02-28 17:14:32 +0000285(The format of \var{address} depends on the address family --- see above.)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000286\end{funcdesc}
287
Guido van Rossum470be141995-03-17 16:07:09 +0000288\begin{funcdesc}{send}{string\optional{\, flags}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000289Send data to the socket. The socket must be connected to a remote
Guido van Rossum470be141995-03-17 16:07:09 +0000290socket. The optional \var{flags} argument has the same meaning as for
291\code{recv()} above. Return the number of bytes sent.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000292\end{funcdesc}
293
Guido van Rossum470be141995-03-17 16:07:09 +0000294\begin{funcdesc}{sendto}{string\optional{\, flags}\, address}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000295Send data to the socket. The socket should not be connected to a
296remote socket, since the destination socket is specified by
Guido van Rossum470be141995-03-17 16:07:09 +0000297\code{address}. The optional \var{flags} argument has the same
298meaning as for \code{recv()} above. Return the number of bytes sent.
Guido van Rossum86751151995-02-28 17:14:32 +0000299(The format of \var{address} depends on the address family --- see above.)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000300\end{funcdesc}
301
Guido van Rossum91951481994-09-07 14:39:14 +0000302\begin{funcdesc}{setblocking}{flag}
303Set blocking or non-blocking mode of the socket: if \var{flag} is 0,
304the socket is set to non-blocking, else to blocking mode. Initially
305all sockets are in blocking mode. In non-blocking mode, if a
306\code{recv} call doesn't find any data, or if a \code{send} call can't
307immediately dispose of the data, a \code{socket.error} exception is
308raised; in blocking mode, the calls block until they can proceed.
309\end{funcdesc}
310
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000311\begin{funcdesc}{setsockopt}{level\, optname\, value}
312Set the value of the given socket option (see the \UNIX{} man page
Guido van Rossum8df36371995-02-27 17:52:15 +0000313{\it setsockopt}(2)). The needed symbolic constants are defined in
314the \code{socket} module (\code{SO_*} etc.). The value can be an
315integer or a string representing a buffer. In the latter case it is
316up to the caller to ensure that the string contains the proper bits
317(see the optional built-in module
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000318\code{struct} for a way to encode C structures as strings).
319\end{funcdesc}
320
321\begin{funcdesc}{shutdown}{how}
322Shut down one or both halves of the connection. If \var{how} is \code{0},
323further receives are disallowed. If \var{how} is \code{1}, further sends are
324disallowed. If \var{how} is \code{2}, further sends and receives are
325disallowed.
326\end{funcdesc}
327
328Note that there are no methods \code{read()} or \code{write()}; use
329\code{recv()} and \code{send()} without \var{flags} argument instead.
330
331\subsection{Example}
332\nodename{Socket Example}
333
Guido van Rossum6bb1adc1995-03-13 10:03:32 +0000334Here are two minimal example programs using the TCP/IP protocol:\ a
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000335server that echoes all data that it receives back (servicing only one
336client), and a client using it. Note that a server must perform the
337sequence \code{socket}, \code{bind}, \code{listen}, \code{accept}
338(possibly repeating the \code{accept} to service more than one client),
339while a client only needs the sequence \code{socket}, \code{connect}.
340Also note that the server does not \code{send}/\code{receive} on the
341socket it is listening on but on the new socket returned by
342\code{accept}.
343
344\bcode\begin{verbatim}
345# Echo server program
346from socket import *
347HOST = '' # Symbolic name meaning the local host
348PORT = 50007 # Arbitrary non-privileged server
349s = socket(AF_INET, SOCK_STREAM)
350s.bind(HOST, PORT)
Guido van Rossum5da57551994-03-02 10:52:16 +0000351s.listen(1)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000352conn, addr = s.accept()
353print 'Connected by', addr
354while 1:
355 data = conn.recv(1024)
356 if not data: break
357 conn.send(data)
358conn.close()
359\end{verbatim}\ecode
Guido van Rossume47da0a1997-07-17 16:34:52 +0000360%
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000361\bcode\begin{verbatim}
362# Echo client program
363from socket import *
364HOST = 'daring.cwi.nl' # The remote host
365PORT = 50007 # The same port as used by the server
366s = socket(AF_INET, SOCK_STREAM)
367s.connect(HOST, PORT)
368s.send('Hello, world')
369data = s.recv(1024)
370s.close()
371print 'Received', `data`
372\end{verbatim}\ecode
Guido van Rossume47da0a1997-07-17 16:34:52 +0000373%
374\begin{seealso}
375\seemodule{SocketServer}{classes that simplify writing network servers}
376\end{seealso}