1 \section{Built-in Module
\sectcode{socket
}}
4 This module provides access to the BSD
{\em socket
} interface.
5 It is available on
\UNIX{} systems that support this interface.
7 For an introduction to socket programming (in C), see the following
8 papers:
\emph{An Introductory
4.3BSD Interprocess Communication
9 Tutorial
}, by Stuart Sechrest and
\emph{An Advanced
4.3BSD Interprocess
10 Communication Tutorial
}, by Samuel J. Leffler et al, both in the
11 \UNIX{} Programmer's Manual, Supplementary Documents
1 (sections PS1:
7
12 and PS1:
8). The
\UNIX{} manual pages for the various socket-related
13 system calls are also a valuable source of information on the details of
16 The Python interface is a straightforward transliteration of the
17 \UNIX{} system call and library interface for sockets to Python's
18 object-oriented style: the
\code{socket()
} function returns a
19 \dfn{socket object
} whose methods implement the various socket system
20 calls. Parameter types are somewhat higer-level than in the C
21 interface: as with
\code{read()
} and
\code{write()
} operations on Python
22 files, buffer allocation on receive operations is automatic, and
23 buffer length is implicit on send operations.
25 Socket 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,
28 where
\var{host
} is a string representing
29 either a hostname in Internet domain notation like
30 \code{'daring.cwi.nl'
} or an IP address like
\code{'
100.50.200.5'
},
31 and
\var{port
} is an integral port number. Other address families are
32 currently not supported. The address format required by a particular
33 socket object is automatically selected based on the address family
34 specified when the socket object was created.
36 All errors raise exceptions. The normal exceptions for invalid
37 argument types and out-of-memory conditions can be raised; errors
38 related to socket or address semantics raise the error
\code{socket.error
}.
40 Non-blocking and asynchronous mode are not supported; see module
41 \code{select
} for a way to do non-blocking socket I/O.
43 The module
\code{socket
} exports the following constants and functions:
45 \renewcommand{\indexsubitem}{(in module socket)
}
46 \begin{excdesc
}{error
}
47 This exception is raised for socket- or address-related errors.
48 The accompanying value is either a string telling what went wrong or a
49 pair
\code{(
\var{errno
},
\var{string
})
}
50 representing an error returned by a system
51 call, similar to the value accompanying
\code{posix.error
}.
54 \begin{datadesc
}{AF_UNIX
}
56 These constants represent the address (and protocol) families,
57 used for the first argument to
\code{socket()
}. If the
\code{AF_UNIX
}
58 constant is not defined then this protocol is unsupported.
61 \begin{datadesc
}{SOCK_STREAM
}
65 \dataline{SOCK_SEQPACKET
}
66 These constants represent the socket types,
67 used for the second argument to
\code{socket()
}.
68 (Only
\code{SOCK_STREAM
} and
69 \code{SOCK_DGRAM
} appear to be generally useful.)
72 \begin{datadesc
}{SO_*
}
80 Many constants of these forms, documented in the
\UNIX{} documentation on
81 sockets and/or the IP protocol, are also defined in the socket module.
82 They are generally used in arguments to the
\code{setsockopt
} and
83 \code{getsockopt
} methods of socket objects. In most cases, only
84 those symbols that are defined in the
\UNIX{} header files are defined;
85 for a few symbols, default values are provided.
88 \begin{funcdesc
}{gethostbyname
}{hostname
}
89 Translate a host name to IP address format. The IP address is
90 returned as a string, e.g.,
\code{'
100.50.200.5'
}. If the host name
91 is an IP address itself it is returned unchanged.
94 \begin{funcdesc
}{gethostname
}{}
95 Return a string containing the hostname of the machine where
96 the Python interpreter is currently executing. If you want to know the
97 current machine's IP address, use
98 \code{socket.gethostbyname(socket.gethostname())
} instead.
101 \begin{funcdesc
}{gethostbyaddr
}{ip_address
}
102 Return a triple
\code{(hostname, aliaslist, ipaddrlist)
} where
103 \code{hostname
} is the primary host name responding to the given
104 \var{ip_address
},
\code{aliaslist
} is a (possibly empty) list of
105 alternative host names for the same address, and
\code{ipaddrlist
} is
106 a list of IP addresses for the same interface on the same
107 host (most likely containing only a single address).
110 \begin{funcdesc
}{getservbyname
}{servicename\, protocolname
}
111 Translate an Internet service name and protocol name to a port number
112 for that service. The protocol name should be
\code{'tcp'
} or
116 \begin{funcdesc
}{socket
}{family\, type
\optional{\, proto
}}
117 Create a new socket using the given address family, socket type and
118 protocol number. The address family should be
\code{AF_INET
} or
119 \code{AF_UNIX
}. The socket type should be
\code{SOCK_STREAM
},
120 \code{SOCK_DGRAM
} or perhaps one of the other
\samp{SOCK_
} constants.
121 The protocol number is usually zero and may be omitted in that case.
124 \begin{funcdesc
}{fromfd
}{fd\, family\, type
\optional{\, proto
}}
125 Build a socket object from an existing file descriptor (an integer as
126 returned by a file object's
\code{fileno
} method). Address family,
127 socket type and protocol number are as for the
\code{socket
} function
128 above. The file descriptor should refer to a socket, but this is not
129 checked --- subsequent operations on the object may fail if the file
130 descriptor is invalid. This function is rarely needed, but can be
131 used to get or set socket options on a socket passed to a program as
132 standard input or output (e.g.\ a server started by the
\UNIX{} inet
136 \subsection{Socket Object Methods
}
139 Socket objects have the following methods. Except for
140 \code{makefile()
} these correspond to
\UNIX{} system calls applicable to
143 \renewcommand{\indexsubitem}{(socket method)
}
144 \begin{funcdesc
}{accept
}{}
146 The socket must be bound to an address and listening for connections.
147 The return value is a pair
\code{(
\var{conn
},
\var{address
})
}
148 where
\var{conn
} is a
\emph{new
} socket object usable to send and
149 receive data on the connection, and
\var{address
} is the address bound
150 to the socket on the other end of the connection.
153 \begin{funcdesc
}{bind
}{address
}
154 Bind the socket to
\var{address
}. The socket must not already be bound.
155 (The format of
\var{address
} depends on the address family --- see above.)
158 \begin{funcdesc
}{close
}{}
159 Close the socket. All future operations on the socket object will fail.
160 The remote end will receive no more data (after queued data is flushed).
161 Sockets are automatically closed when they are garbage-collected.
164 \begin{funcdesc
}{connect
}{address
}
165 Connect to a remote socket at
\var{address
}.
166 (The format of
\var{address
} depends on the address family --- see above.)
169 \begin{funcdesc
}{fileno
}{}
170 Return the socket's file descriptor (a small integer). This is useful
174 \begin{funcdesc
}{getpeername
}{}
175 Return the remote address to which the socket is connected. This is
176 useful to find out the port number of a remote IP socket, for instance.
177 (The format of the address returned depends on the address family ---
178 see above.) On some systems this function is not supported.
181 \begin{funcdesc
}{getsockname
}{}
182 Return the socket's own address. This is useful to find out the port
183 number of an IP socket, for instance.
184 (The format of the address returned depends on the address family ---
188 \begin{funcdesc
}{getsockopt
}{level\, optname
\optional{\, buflen
}}
189 Return the value of the given socket option (see the
\UNIX{} man page
190 {\it getsockopt
}(
2)). The needed symbolic constants are defined in
191 the
\code{socket
} module (
\code{SO_*
} etc.). If the optional third
192 argument is absent, an integer option is assumed and its integer value
193 is returned by the function. If
\var{buflen
} is present, it specifies
194 the maximum length of the buffer used to receive the option in, and
195 this buffer is returned as a string. It's up to the caller to decode
196 the contents of the buffer (see the optional built-in module
197 \code{struct
} for a way to decode C structures encoded as strings).
200 \begin{funcdesc
}{listen
}{backlog
}
201 Listen for connections made to the socket.
202 The argument specifies the maximum number of queued connections and
203 should be at least
1; the maximum value is system-dependent.
206 \begin{funcdesc
}{makefile
}{mode
}
207 Return a
\dfn{file object
} associated with the socket.
208 (File objects were described earlier under Built-in Types.)
209 The file object references a
\code{dup
}ped version of the socket file
210 descriptor, so the file object and socket object may be closed or
211 garbage-collected independently.
214 \begin{funcdesc
}{recv
}{bufsize
\optional{\, flags
}}
215 Receive data from the socket. The return value is a string representing
216 the data received. The maximum amount of data to be received
217 at once is specified by
\var{bufsize
}. See the
\UNIX{} manual page
218 for the meaning of the optional argument
\var{flags
}; it defaults to
222 \begin{funcdesc
}{recvfrom
}{bufsize
}
223 Receive data from the socket. The return value is a pair
224 \code{(
\var{string
},
\var{address
})
} where
\var{string
} is a string
225 representing the data received and
\var{address
} is the address of the
226 socket sending the data.
227 (The format of
\var{address
} depends on the address family --- see above.)
230 \begin{funcdesc
}{send
}{string
}
231 Send data to the socket. The socket must be connected to a remote
232 socket. Return the number of bytes sent.
235 \begin{funcdesc
}{sendto
}{string\, address
}
236 Send data to the socket. The socket should not be connected to a
237 remote socket, since the destination socket is specified by
238 \code{address
}. Return the number of bytes sent.
239 (The format of
\var{address
} depends on the address family --- see above.)
242 \begin{funcdesc
}{setblocking
}{flag
}
243 Set blocking or non-blocking mode of the socket: if
\var{flag
} is
0,
244 the socket is set to non-blocking, else to blocking mode. Initially
245 all sockets are in blocking mode. In non-blocking mode, if a
246 \code{recv
} call doesn't find any data, or if a
\code{send
} call can't
247 immediately dispose of the data, a
\code{socket.error
} exception is
248 raised; in blocking mode, the calls block until they can proceed.
251 \begin{funcdesc
}{setsockopt
}{level\, optname\, value
}
252 Set the value of the given socket option (see the
\UNIX{} man page
253 {\it setsockopt
}(
2)). The needed symbolic constants are defined in
254 the
\code{socket
} module (
\code{SO_*
} etc.). The value can be an
255 integer or a string representing a buffer. In the latter case it is
256 up to the caller to ensure that the string contains the proper bits
257 (see the optional built-in module
258 \code{struct
} for a way to encode C structures as strings).
261 \begin{funcdesc
}{shutdown
}{how
}
262 Shut down one or both halves of the connection. If
\var{how
} is
\code{0},
263 further receives are disallowed. If
\var{how
} is
\code{1}, further sends are
264 disallowed. If
\var{how
} is
\code{2}, further sends and receives are
268 Note that there are no methods
\code{read()
} or
\code{write()
}; use
269 \code{recv()
} and
\code{send()
} without
\var{flags
} argument instead.
272 \nodename{Socket Example
}
274 Here are two minimal example programs using the TCP/IP protocol:\ a
275 server that echoes all data that it receives back (servicing only one
276 client), and a client using it. Note that a server must perform the
277 sequence
\code{socket
},
\code{bind
},
\code{listen
},
\code{accept
}
278 (possibly repeating the
\code{accept
} to service more than one client),
279 while a client only needs the sequence
\code{socket
},
\code{connect
}.
280 Also note that the server does not
\code{send
}/
\code{receive
} on the
281 socket it is listening on but on the new socket returned by
284 \bcode\begin{verbatim
}
285 # Echo server program
287 HOST = '' # Symbolic name meaning the local host
288 PORT =
50007 # Arbitrary non-privileged server
289 s = socket(AF_INET, SOCK_STREAM)
292 conn, addr = s.accept()
293 print 'Connected by', addr
295 data = conn.recv(
1024)
301 \bcode\begin{verbatim
}
302 # Echo client program
304 HOST = 'daring.cwi.nl' # The remote host
305 PORT =
50007 # The same port as used by the server
306 s = socket(AF_INET, SOCK_STREAM)
307 s.connect(HOST, PORT)
308 s.send('Hello, world')
311 print 'Received', `data`