1 \section{\module{socket
} ---
2 Low-level networking interface
}
4 \declaremodule{builtin
}{socket
}
5 \modulesynopsis{Low-level networking interface.
}
8 This module provides access to the BSD
\emph{socket
} interface.
9 It is available on
\UNIX{} systems that support this interface.
11 For an introduction to socket programming (in C), see the following
12 papers:
\citetitle{An Introductory
4.3BSD Interprocess Communication
13 Tutorial
}, by Stuart Sechrest and
\citetitle{An Advanced
4.3BSD
14 Interprocess Communication Tutorial
}, by Samuel J. Leffler et al,
15 both in the
\citetitle{\UNIX{} Programmer's Manual, Supplementary Documents
1}
16 (sections PS1:
7 and PS1:
8). The
\UNIX{} manual pages for the various
17 socket-related system calls are also a valuable source of information
18 on the details of socket semantics.
20 The Python interface is a straightforward transliteration of the
21 \UNIX{} system call and library interface for sockets to Python's
22 object-oriented style: the
\function{socket()
} function returns a
23 \dfn{socket object
}\obindex{socket
} whose methods implement the
24 various socket system calls. Parameter types are somewhat
25 higher-level than in the C interface: as with
\method{read()
} and
26 \method{write()
} operations on Python files, buffer allocation on
27 receive operations is automatic, and buffer length is implicit on send
30 Socket addresses are represented as a single string for the
31 \constant{AF_UNIX
} address family and as a pair
32 \code{(
\var{host
},
\var{port
})
} for the
\constant{AF_INET
} address
33 family, where
\var{host
} is a string representing
34 either a hostname in Internet domain notation like
35 \code{'daring.cwi.nl'
} or an IP address like
\code{'
100.50.200.5'
},
36 and
\var{port
} is an integral port number. Other address families are
37 currently not supported. The address format required by a particular
38 socket object is automatically selected based on the address family
39 specified when the socket object was created.
41 For IP addresses, two special forms are accepted instead of a host
42 address: the empty string represents
\constant{INADDR_ANY
}, and the string
43 \code{'<broadcast>'
} represents
\constant{INADDR_BROADCAST
}.
45 All errors raise exceptions. The normal exceptions for invalid
46 argument types and out-of-memory conditions can be raised; errors
47 related to socket or address semantics raise the error
48 \exception{socket.error
}.
50 Non-blocking mode is supported through the
51 \method{setblocking()
} method.
53 The module
\module{socket
} exports the following constants and functions:
56 \begin{excdesc
}{error
}
57 This exception is raised for socket- or address-related errors.
58 The accompanying value is either a string telling what went wrong or a
59 pair
\code{(
\var{errno
},
\var{string
})
}
60 representing an error returned by a system
61 call, similar to the value accompanying
\exception{os.error
}.
62 See the module
\refmodule{errno
}\refbimodindex{errno
}, which contains
63 names for the error codes defined by the underlying operating system.
66 \begin{datadesc
}{AF_UNIX
}
68 These constants represent the address (and protocol) families,
69 used for the first argument to
\function{socket()
}. If the
70 \constant{AF_UNIX
} constant is not defined then this protocol is
74 \begin{datadesc
}{SOCK_STREAM
}
78 \dataline{SOCK_SEQPACKET
}
79 These constants represent the socket types,
80 used for the second argument to
\function{socket()
}.
81 (Only
\constant{SOCK_STREAM
} and
82 \constant{SOCK_DGRAM
} appear to be generally useful.)
85 \begin{datadesc
}{SO_*
}
93 Many constants of these forms, documented in the
\UNIX{} documentation on
94 sockets and/or the IP protocol, are also defined in the socket module.
95 They are generally used in arguments to the
\method{setsockopt()
} and
96 \method{getsockopt()
} methods of socket objects. In most cases, only
97 those symbols that are defined in the
\UNIX{} header files are defined;
98 for a few symbols, default values are provided.
101 \begin{funcdesc
}{gethostbyname
}{hostname
}
102 Translate a host name to IP address format. The IP address is
103 returned as a string, e.g.,
\code{'
100.50.200.5'
}. If the host name
104 is an IP address itself it is returned unchanged. See
105 \function{gethostbyname_ex()
} for a more complete interface.
108 \begin{funcdesc
}{gethostbyname_ex
}{hostname
}
109 Translate a host name to IP address format, extended interface.
110 Return 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
113 alternative host names for the same address, and
\code{ipaddrlist
} is
114 a list of IP addresses for the same interface on the same
115 host (often but not always a single address).
118 \begin{funcdesc
}{gethostname
}{}
119 Return a string containing the hostname of the machine where
120 the Python interpreter is currently executing. If you want to know the
121 current machine's IP address, use
\code{gethostbyname(gethostname())
}.
122 Note:
\function{gethostname()
} doesn't always return the fully qualified
123 domain name; use
\code{gethostbyaddr(gethostname())
}
127 \begin{funcdesc
}{gethostbyaddr
}{ip_address
}
128 Return a triple
\code{(
\var{hostname
},
\var{aliaslist
},
129 \var{ipaddrlist
})
} where
\var{hostname
} is the primary host name
130 responding to the given
\var{ip_address
},
\var{aliaslist
} is a
131 (possibly empty) list of alternative host names for the same address,
132 and
\var{ipaddrlist
} is a list of IP addresses for the same interface
133 on the same host (most likely containing only a single address).
134 To find the fully qualified domain name, check
\var{hostname
} and the
135 items of
\var{aliaslist
} for an entry containing at least one period.
138 \begin{funcdesc
}{getprotobyname
}{protocolname
}
139 Translate an Internet protocol name (e.g.\
\code{'icmp'
}) to a constant
140 suitable for passing as the (optional) third argument to the
141 \function{socket()
} function. This is usually only needed for sockets
142 opened in ``raw'' mode (
\constant{SOCK_RAW
}); for the normal socket
143 modes, the correct protocol is chosen automatically if the protocol is
147 \begin{funcdesc
}{getservbyname
}{servicename, protocolname
}
148 Translate an Internet service name and protocol name to a port number
149 for that service. The protocol name should be
\code{'tcp'
} or
153 \begin{funcdesc
}{socket
}{family, type
\optional{, proto
}}
154 Create a new socket using the given address family, socket type and
155 protocol number. The address family should be
\constant{AF_INET
} or
156 \constant{AF_UNIX
}. The socket type should be
\constant{SOCK_STREAM
},
157 \constant{SOCK_DGRAM
} or perhaps one of the other
\samp{SOCK_
} constants.
158 The protocol number is usually zero and may be omitted in that case.
161 \begin{funcdesc
}{fromfd
}{fd, family, type
\optional{, proto
}}
162 Build a socket object from an existing file descriptor (an integer as
163 returned by a file object's
\method{fileno()
} method). Address family,
164 socket type and protocol number are as for the
\function{socket()
} function
165 above. The file descriptor should refer to a socket, but this is not
166 checked --- subsequent operations on the object may fail if the file
167 descriptor is invalid. This function is rarely needed, but can be
168 used to get or set socket options on a socket passed to a program as
169 standard input or output (e.g.\ a server started by the
\UNIX{} inet
173 \begin{funcdesc
}{ntohl
}{x
}
174 Convert
32-bit integers from network to host byte order. On machines
175 where the host byte order is the same as network byte order, this is a
176 no-op; otherwise, it performs a
4-byte swap operation.
179 \begin{funcdesc
}{ntohs
}{x
}
180 Convert
16-bit integers from network to host byte order. On machines
181 where the host byte order is the same as network byte order, this is a
182 no-op; otherwise, it performs a
2-byte swap operation.
185 \begin{funcdesc
}{htonl
}{x
}
186 Convert
32-bit integers from host to network byte order. On machines
187 where the host byte order is the same as network byte order, this is a
188 no-op; otherwise, it performs a
4-byte swap operation.
191 \begin{funcdesc
}{htons
}{x
}
192 Convert
16-bit integers from host to network byte order. On machines
193 where the host byte order is the same as network byte order, this is a
194 no-op; otherwise, it performs a
2-byte swap operation.
197 \begin{funcdesc
}{inet_aton
}{ip_string
}
198 Convert an IP address from dotted-quad string format
199 (e.g.\ '
123.45.67.89') to
32-bit packed binary format, as a string four
200 characters in length.
202 Useful when conversing with a program that uses the standard C library
203 and needs objects of type
\ctype{struct in_addr
}, which is the C type
204 for the
32-bit packed binary this function returns.
206 If the IP address string passed to this function is invalid,
207 \exception{socket.error
} will be raised. Note that exactly what is
208 valid depends on the underlying C implementation of
209 \cfunction{inet_aton()
}.
212 \begin{funcdesc
}{inet_ntoa
}{packed_ip
}
213 Convert a
32-bit packed IP address (a string four characters in
214 length) to its standard dotted-quad string representation
215 (e.g. '
123.45.67.89').
217 Useful when conversing with a program that uses the standard C library
218 and needs objects of type
\ctype{struct in_addr
}, which is the C type
219 for the
32-bit packed binary this function takes as an argument.
221 If the string passed to this function is not exactly
4 bytes in
222 length,
\exception{socket.error
} will be raised.
225 \begin{datadesc
}{SocketType
}
226 This is a Python type object that represents the socket object type.
227 It is the same as
\code{type(socket(...))
}.
230 \subsection{Socket Objects
\label{socket-objects
}}
232 Socket objects have the following methods. Except for
233 \method{makefile()
} these correspond to
\UNIX{} system calls
234 applicable to sockets.
236 \begin{methoddesc
}[socket
]{accept
}{}
238 The socket must be bound to an address and listening for connections.
239 The return value is a pair
\code{(
\var{conn
},
\var{address
})
}
240 where
\var{conn
} is a
\emph{new
} socket object usable to send and
241 receive data on the connection, and
\var{address
} is the address bound
242 to the socket on the other end of the connection.
245 \begin{methoddesc
}[socket
]{bind
}{address
}
246 Bind the socket to
\var{address
}. The socket must not already be bound.
247 (The format of
\var{address
} depends on the address family --- see above.)
250 \begin{methoddesc
}[socket
]{close
}{}
251 Close the socket. All future operations on the socket object will fail.
252 The remote end will receive no more data (after queued data is flushed).
253 Sockets are automatically closed when they are garbage-collected.
256 \begin{methoddesc
}[socket
]{connect
}{address
}
257 Connect to a remote socket at
\var{address
}.
258 (The format of
\var{address
} depends on the address family --- see
262 \begin{methoddesc
}[socket
]{connect_ex
}{address
}
263 Like
\code{connect(
\var{address
})
}, but return an error indicator
264 instead of raising an exception for errors returned by the C-level
265 \cfunction{connect()
} call (other problems, such as ``host not found,''
266 can still raise exceptions). The error indicator is
\code{0} if the
267 operation succeeded, otherwise the value of the
\cdata{errno
}
268 variable. This is useful, e.g., for asynchronous connects.
271 \begin{methoddesc
}[socket
]{fileno
}{}
272 Return the socket's file descriptor (a small integer). This is useful
273 with
\function{select.select()
}.
276 \begin{methoddesc
}[socket
]{getpeername
}{}
277 Return the remote address to which the socket is connected. This is
278 useful to find out the port number of a remote IP socket, for instance.
279 (The format of the address returned depends on the address family ---
280 see above.) On some systems this function is not supported.
283 \begin{methoddesc
}[socket
]{getsockname
}{}
284 Return the socket's own address. This is useful to find out the port
285 number of an IP socket, for instance.
286 (The format of the address returned depends on the address family ---
290 \begin{methoddesc
}[socket
]{getsockopt
}{level, optname
\optional{, buflen
}}
291 Return the value of the given socket option (see the
\UNIX{} man page
292 \manpage{getsockopt
}{2}). The needed symbolic constants
293 (
\constant{SO_*
} etc.) are defined in this module. If
\var{buflen
}
294 is absent, an integer option is assumed and its integer value
295 is returned by the function. If
\var{buflen
} is present, it specifies
296 the maximum length of the buffer used to receive the option in, and
297 this buffer is returned as a string. It is up to the caller to decode
298 the contents of the buffer (see the optional built-in module
299 \refmodule{struct
} for a way to decode C structures encoded as strings).
302 \begin{methoddesc
}[socket
]{listen
}{backlog
}
303 Listen for connections made to the socket. The
\var{backlog
} argument
304 specifies the maximum number of queued connections and should be at
305 least
1; the maximum value is system-dependent (usually
5).
308 \begin{methoddesc
}[socket
]{makefile
}{\optional{mode
\optional{, bufsize
}}}
309 Return a
\dfn{file object
} associated with the socket. (File objects
310 are described in
\ref{bltin-file-objects
}, ``File Objects.'')
311 The file object references a
\cfunction{dup()
}ped version of the
312 socket file descriptor, so the file object and socket object may be
313 closed or garbage-collected independently.
314 \index{I/O control!buffering
}The optional
\var{mode
}
315 and
\var{bufsize
} arguments are interpreted the same way as by the
316 built-in
\function{open()
} function.
319 \begin{methoddesc
}[socket
]{recv
}{bufsize
\optional{, flags
}}
320 Receive data from the socket. The return value is a string representing
321 the data received. The maximum amount of data to be received
322 at once is specified by
\var{bufsize
}. See the
\UNIX{} manual page
323 \manpage{recv
}{2} for the meaning of the optional argument
324 \var{flags
}; it defaults to zero.
327 \begin{methoddesc
}[socket
]{recvfrom
}{bufsize
\optional{, flags
}}
328 Receive data from the socket. The return value is a pair
329 \code{(
\var{string
},
\var{address
})
} where
\var{string
} is a string
330 representing the data received and
\var{address
} is the address of the
331 socket sending the data. The optional
\var{flags
} argument has the
332 same meaning as for
\method{recv()
} above.
333 (The format of
\var{address
} depends on the address family --- see above.)
336 \begin{methoddesc
}[socket
]{send
}{string
\optional{, flags
}}
337 Send data to the socket. The socket must be connected to a remote
338 socket. The optional
\var{flags
} argument has the same meaning as for
339 \method{recv()
} above. Returns the number of bytes sent.
342 \begin{methoddesc
}[socket
]{sendto
}{string
\optional{, flags
}, address
}
343 Send data to the socket. The socket should not be connected to a
344 remote socket, since the destination socket is specified by
345 \var{address
}. The optional
\var{flags
} argument has the same
346 meaning as for
\method{recv()
} above. Return the number of bytes sent.
347 (The format of
\var{address
} depends on the address family --- see above.)
350 \begin{methoddesc
}[socket
]{setblocking
}{flag
}
351 Set blocking or non-blocking mode of the socket: if
\var{flag
} is
0,
352 the socket is set to non-blocking, else to blocking mode. Initially
353 all sockets are in blocking mode. In non-blocking mode, if a
354 \method{recv()
} call doesn't find any data, or if a
355 \method{send()
} call can't immediately dispose of the data, a
356 \exception{error
} exception is raised; in blocking mode, the calls
357 block until they can proceed.
360 \begin{methoddesc
}[socket
]{setsockopt
}{level, optname, value
}
361 Set the value of the given socket option (see the
\UNIX{} man page
362 \manpage{setsockopt
}{2}). The needed symbolic constants are defined in
363 the
\module{socket
} module (
\code{SO_*
} etc.). The value can be an
364 integer or a string representing a buffer. In the latter case it is
365 up to the caller to ensure that the string contains the proper bits
366 (see the optional built-in module
367 \refmodule{struct
}\refbimodindex{struct
} for a way to encode C
368 structures as strings).
371 \begin{methoddesc
}[socket
]{shutdown
}{how
}
372 Shut down one or both halves of the connection. If
\var{how
} is
373 \code{0}, further receives are disallowed. If
\var{how
} is
\code{1},
374 further sends are disallowed. If
\var{how
} is
\code{2}, further sends
375 and receives are disallowed.
378 Note that there are no methods
\method{read()
} or
\method{write()
};
379 use
\method{recv()
} and
\method{send()
} without
\var{flags
} argument
383 \nodename{Socket Example
}
385 Here are two minimal example programs using the TCP/IP protocol:\ a
386 server that echoes all data that it receives back (servicing only one
387 client), and a client using it. Note that a server must perform the
388 sequence
\function{socket()
},
\method{bind()
},
\method{listen()
},
389 \method{accept()
} (possibly repeating the
\method{accept()
} to service
390 more than one client), while a client only needs the sequence
391 \function{socket()
},
\method{connect()
}. Also note that the server
392 does not
\method{send()
}/
\method{recv()
} on the
393 socket it is listening on but on the new socket returned by
397 # Echo server program
399 HOST = '' # Symbolic name meaning the local host
400 PORT =
50007 # Arbitrary non-privileged server
401 s = socket(AF_INET, SOCK_STREAM)
404 conn, addr = s.accept()
405 print 'Connected by', addr
407 data = conn.recv(
1024)
414 # Echo client program
416 HOST = 'daring.cwi.nl' # The remote host
417 PORT =
50007 # The same port as used by the server
418 s = socket(AF_INET, SOCK_STREAM)
419 s.connect(HOST, PORT)
420 s.send('Hello, world')
423 print 'Received', `data`
427 \seemodule{SocketServer
}{classes that simplify writing network servers
}