blob: ea6cae3971003a7e7b5111b7e1093db6348e3626 [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}
156\funcline{ntohs}{x}
157\funcline{htonl}{x}
158\funcline{htons}{x}
159These functions convert 32-bit (`l' suffix) and 16-bit (`s' suffix)
160integers between network and host byte order. On machines where the
161host byte order is the same as the network byte order, they are no-ops
162(assuming the values fit in the indicated size); otherwise, they
163perform 2-byte or 4-byte swap operations.
164\end{funcdesc}
165
Fred Drake5451d671997-10-13 21:31:02 +0000166\begin{datadesc}{SocketType}
Guido van Rossum2335c5e1997-05-21 14:41:42 +0000167This is a Python type object that represents the socket object type.
168It is the same as \code{type(socket.socket(...))}.
169\end{datadesc}
170
Guido van Rossum470be141995-03-17 16:07:09 +0000171\subsection{Socket Objects}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000172
173\noindent
174Socket objects have the following methods. Except for
175\code{makefile()} these correspond to \UNIX{} system calls applicable to
176sockets.
177
178\renewcommand{\indexsubitem}{(socket method)}
179\begin{funcdesc}{accept}{}
180Accept a connection.
181The socket must be bound to an address and listening for connections.
182The return value is a pair \code{(\var{conn}, \var{address})}
183where \var{conn} is a \emph{new} socket object usable to send and
184receive data on the connection, and \var{address} is the address bound
185to the socket on the other end of the connection.
186\end{funcdesc}
187
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000188\begin{funcdesc}{bind}{address}
Guido van Rossuma84ec511994-06-23 12:13:52 +0000189Bind the socket to \var{address}. The socket must not already be bound.
Guido van Rossum86751151995-02-28 17:14:32 +0000190(The format of \var{address} depends on the address family --- see above.)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000191\end{funcdesc}
192
193\begin{funcdesc}{close}{}
194Close the socket. All future operations on the socket object will fail.
195The remote end will receive no more data (after queued data is flushed).
196Sockets are automatically closed when they are garbage-collected.
197\end{funcdesc}
198
199\begin{funcdesc}{connect}{address}
Guido van Rossuma84ec511994-06-23 12:13:52 +0000200Connect to a remote socket at \var{address}.
Guido van Rossum86751151995-02-28 17:14:32 +0000201(The format of \var{address} depends on the address family --- see above.)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000202\end{funcdesc}
203
204\begin{funcdesc}{fileno}{}
205Return the socket's file descriptor (a small integer). This is useful
206with \code{select}.
207\end{funcdesc}
208
209\begin{funcdesc}{getpeername}{}
210Return the remote address to which the socket is connected. This is
211useful to find out the port number of a remote IP socket, for instance.
Guido van Rossum86751151995-02-28 17:14:32 +0000212(The format of the address returned depends on the address family ---
Guido van Rossum781db5d1994-08-05 13:37:36 +0000213see above.) On some systems this function is not supported.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000214\end{funcdesc}
215
216\begin{funcdesc}{getsockname}{}
217Return the socket's own address. This is useful to find out the port
218number of an IP socket, for instance.
Guido van Rossum86751151995-02-28 17:14:32 +0000219(The format of the address returned depends on the address family ---
Guido van Rossuma84ec511994-06-23 12:13:52 +0000220see above.)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000221\end{funcdesc}
222
Guido van Rossum6bb1adc1995-03-13 10:03:32 +0000223\begin{funcdesc}{getsockopt}{level\, optname\optional{\, buflen}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000224Return the value of the given socket option (see the \UNIX{} man page
Guido van Rossum470be141995-03-17 16:07:09 +0000225{\it getsockopt}(2)). The needed symbolic constants (\code{SO_*} etc.)
226are defined in this module. If \var{buflen}
227is absent, an integer option is assumed and its integer value
Guido van Rossum8df36371995-02-27 17:52:15 +0000228is returned by the function. If \var{buflen} is present, it specifies
229the maximum length of the buffer used to receive the option in, and
Guido van Rossum470be141995-03-17 16:07:09 +0000230this buffer is returned as a string. It is up to the caller to decode
Guido van Rossum8df36371995-02-27 17:52:15 +0000231the contents of the buffer (see the optional built-in module
232\code{struct} for a way to decode C structures encoded as strings).
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000233\end{funcdesc}
234
235\begin{funcdesc}{listen}{backlog}
Guido van Rossum470be141995-03-17 16:07:09 +0000236Listen for connections made to the socket. The \var{backlog} argument
237specifies the maximum number of queued connections and should be at
238least 1; the maximum value is system-dependent (usually 5).
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000239\end{funcdesc}
240
Guido van Rossum470be141995-03-17 16:07:09 +0000241\begin{funcdesc}{makefile}{\optional{mode\optional{\, bufsize}}}
242Return a \dfn{file object} associated with the socket. (File objects
243were described earlier under Built-in Types.) The file object
244references a \code{dup()}ped version of the socket file descriptor, so
245the file object and socket object may be closed or garbage-collected
246independently. The optional \var{mode} and \var{bufsize} arguments
247are interpreted the same way as by the built-in
248\code{open()} function.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000249\end{funcdesc}
250
Guido van Rossum6bb1adc1995-03-13 10:03:32 +0000251\begin{funcdesc}{recv}{bufsize\optional{\, flags}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000252Receive data from the socket. The return value is a string representing
253the data received. The maximum amount of data to be received
254at once is specified by \var{bufsize}. See the \UNIX{} manual page
255for the meaning of the optional argument \var{flags}; it defaults to
256zero.
257\end{funcdesc}
258
Guido van Rossum470be141995-03-17 16:07:09 +0000259\begin{funcdesc}{recvfrom}{bufsize\optional{\, flags}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000260Receive data from the socket. The return value is a pair
261\code{(\var{string}, \var{address})} where \var{string} is a string
262representing the data received and \var{address} is the address of the
Guido van Rossum470be141995-03-17 16:07:09 +0000263socket sending the data. The optional \var{flags} argument has the
264same meaning as for \code{recv()} above.
Guido van Rossum86751151995-02-28 17:14:32 +0000265(The format of \var{address} depends on the address family --- see above.)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000266\end{funcdesc}
267
Guido van Rossum470be141995-03-17 16:07:09 +0000268\begin{funcdesc}{send}{string\optional{\, flags}}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000269Send data to the socket. The socket must be connected to a remote
Guido van Rossum470be141995-03-17 16:07:09 +0000270socket. The optional \var{flags} argument has the same meaning as for
271\code{recv()} above. Return the number of bytes sent.
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000272\end{funcdesc}
273
Guido van Rossum470be141995-03-17 16:07:09 +0000274\begin{funcdesc}{sendto}{string\optional{\, flags}\, address}
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000275Send data to the socket. The socket should not be connected to a
276remote socket, since the destination socket is specified by
Guido van Rossum470be141995-03-17 16:07:09 +0000277\code{address}. The optional \var{flags} argument has the same
278meaning as for \code{recv()} above. Return the number of bytes sent.
Guido van Rossum86751151995-02-28 17:14:32 +0000279(The format of \var{address} depends on the address family --- see above.)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000280\end{funcdesc}
281
Guido van Rossum91951481994-09-07 14:39:14 +0000282\begin{funcdesc}{setblocking}{flag}
283Set blocking or non-blocking mode of the socket: if \var{flag} is 0,
284the socket is set to non-blocking, else to blocking mode. Initially
285all sockets are in blocking mode. In non-blocking mode, if a
286\code{recv} call doesn't find any data, or if a \code{send} call can't
287immediately dispose of the data, a \code{socket.error} exception is
288raised; in blocking mode, the calls block until they can proceed.
289\end{funcdesc}
290
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000291\begin{funcdesc}{setsockopt}{level\, optname\, value}
292Set the value of the given socket option (see the \UNIX{} man page
Guido van Rossum8df36371995-02-27 17:52:15 +0000293{\it setsockopt}(2)). The needed symbolic constants are defined in
294the \code{socket} module (\code{SO_*} etc.). The value can be an
295integer or a string representing a buffer. In the latter case it is
296up to the caller to ensure that the string contains the proper bits
297(see the optional built-in module
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000298\code{struct} for a way to encode C structures as strings).
299\end{funcdesc}
300
301\begin{funcdesc}{shutdown}{how}
302Shut down one or both halves of the connection. If \var{how} is \code{0},
303further receives are disallowed. If \var{how} is \code{1}, further sends are
304disallowed. If \var{how} is \code{2}, further sends and receives are
305disallowed.
306\end{funcdesc}
307
308Note that there are no methods \code{read()} or \code{write()}; use
309\code{recv()} and \code{send()} without \var{flags} argument instead.
310
311\subsection{Example}
312\nodename{Socket Example}
313
Guido van Rossum6bb1adc1995-03-13 10:03:32 +0000314Here are two minimal example programs using the TCP/IP protocol:\ a
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000315server that echoes all data that it receives back (servicing only one
316client), and a client using it. Note that a server must perform the
317sequence \code{socket}, \code{bind}, \code{listen}, \code{accept}
318(possibly repeating the \code{accept} to service more than one client),
319while a client only needs the sequence \code{socket}, \code{connect}.
320Also note that the server does not \code{send}/\code{receive} on the
321socket it is listening on but on the new socket returned by
322\code{accept}.
323
324\bcode\begin{verbatim}
325# Echo server program
326from socket import *
327HOST = '' # Symbolic name meaning the local host
328PORT = 50007 # Arbitrary non-privileged server
329s = socket(AF_INET, SOCK_STREAM)
330s.bind(HOST, PORT)
Guido van Rossum5da57551994-03-02 10:52:16 +0000331s.listen(1)
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000332conn, addr = s.accept()
333print 'Connected by', addr
334while 1:
335 data = conn.recv(1024)
336 if not data: break
337 conn.send(data)
338conn.close()
339\end{verbatim}\ecode
Guido van Rossume47da0a1997-07-17 16:34:52 +0000340%
Guido van Rossum5fdeeea1994-01-02 01:22:07 +0000341\bcode\begin{verbatim}
342# Echo client program
343from socket import *
344HOST = 'daring.cwi.nl' # The remote host
345PORT = 50007 # The same port as used by the server
346s = socket(AF_INET, SOCK_STREAM)
347s.connect(HOST, PORT)
348s.send('Hello, world')
349data = s.recv(1024)
350s.close()
351print 'Received', `data`
352\end{verbatim}\ecode
Guido van Rossume47da0a1997-07-17 16:34:52 +0000353%
354\begin{seealso}
355\seemodule{SocketServer}{classes that simplify writing network servers}
356\end{seealso}