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 all modern
\UNIX{} systems, Windows, MacOS, BeOS,
10 OS/
2, and probably additional platforms.
12 For an introduction to socket programming (in C), see the following
13 papers:
\citetitle{An Introductory
4.3BSD Interprocess Communication
14 Tutorial
}, by Stuart Sechrest and
\citetitle{An Advanced
4.3BSD
15 Interprocess Communication Tutorial
}, by Samuel J. Leffler et al,
16 both in the
\citetitle{\UNIX{} Programmer's Manual, Supplementary Documents
1}
17 (sections PS1:
7 and PS1:
8). The platform-specific reference material
18 for the various socket-related system calls are also a valuable source
19 of information on the details of socket semantics. For
\UNIX, refer
20 to the manual pages; for Windows, see the WinSock (or Winsock
2)
23 The Python interface is a straightforward transliteration of the
24 \UNIX{} system call and library interface for sockets to Python's
25 object-oriented style: the
\function{socket()
} function returns a
26 \dfn{socket object
}\obindex{socket
} whose methods implement the
27 various socket system calls. Parameter types are somewhat
28 higher-level than in the C interface: as with
\method{read()
} and
29 \method{write()
} operations on Python files, buffer allocation on
30 receive operations is automatic, and buffer length is implicit on send
33 Socket addresses are represented as a single string for the
34 \constant{AF_UNIX
} address family and as a pair
35 \code{(
\var{host
},
\var{port
})
} for the
\constant{AF_INET
} address
36 family, where
\var{host
} is a string representing
37 either a hostname in Internet domain notation like
38 \code{'daring.cwi.nl'
} or an IP address like
\code{'
100.50.200.5'
},
39 and
\var{port
} is an integral port number. Other address families are
40 currently not supported. The address format required by a particular
41 socket object is automatically selected based on the address family
42 specified when the socket object was created.
44 For IP addresses, two special forms are accepted instead of a host
45 address: the empty string represents
\constant{INADDR_ANY
}, and the string
46 \code{'<broadcast>'
} represents
\constant{INADDR_BROADCAST
}.
48 All errors raise exceptions. The normal exceptions for invalid
49 argument types and out-of-memory conditions can be raised; errors
50 related to socket or address semantics raise the error
51 \exception{socket.error
}.
53 Non-blocking mode is supported through the
54 \method{setblocking()
} method.
56 The module
\module{socket
} exports the following constants and functions:
59 \begin{excdesc
}{error
}
60 This exception is raised for socket- or address-related errors.
61 The accompanying value is either a string telling what went wrong or a
62 pair
\code{(
\var{errno
},
\var{string
})
}
63 representing an error returned by a system
64 call, similar to the value accompanying
\exception{os.error
}.
65 See the module
\refmodule{errno
}\refbimodindex{errno
}, which contains
66 names for the error codes defined by the underlying operating system.
69 \begin{datadesc
}{AF_UNIX
}
71 These constants represent the address (and protocol) families,
72 used for the first argument to
\function{socket()
}. If the
73 \constant{AF_UNIX
} constant is not defined then this protocol is
77 \begin{datadesc
}{SOCK_STREAM
}
81 \dataline{SOCK_SEQPACKET
}
82 These constants represent the socket types,
83 used for the second argument to
\function{socket()
}.
84 (Only
\constant{SOCK_STREAM
} and
85 \constant{SOCK_DGRAM
} appear to be generally useful.)
88 \begin{datadesc
}{SO_*
}
96 Many constants of these forms, documented in the
\UNIX{} documentation on
97 sockets and/or the IP protocol, are also defined in the socket module.
98 They are generally used in arguments to the
\method{setsockopt()
} and
99 \method{getsockopt()
} methods of socket objects. In most cases, only
100 those symbols that are defined in the
\UNIX{} header files are defined;
101 for a few symbols, default values are provided.
104 \begin{funcdesc
}{gethostbyname
}{hostname
}
105 Translate a host name to IP address format. The IP address is
106 returned as a string, e.g.,
\code{'
100.50.200.5'
}. If the host name
107 is an IP address itself it is returned unchanged. See
108 \function{gethostbyname_ex()
} for a more complete interface.
111 \begin{funcdesc
}{gethostbyname_ex
}{hostname
}
112 Translate a host name to IP address format, extended interface.
113 Return a triple
\code{(hostname, aliaslist, ipaddrlist)
} where
114 \code{hostname
} is the primary host name responding to the given
115 \var{ip_address
},
\code{aliaslist
} is a (possibly empty) list of
116 alternative host names for the same address, and
\code{ipaddrlist
} is
117 a list of IP addresses for the same interface on the same
118 host (often but not always a single address).
121 \begin{funcdesc
}{gethostname
}{}
122 Return a string containing the hostname of the machine where
123 the Python interpreter is currently executing. If you want to know the
124 current machine's IP address, use
\code{gethostbyname(gethostname())
}.
125 Note:
\function{gethostname()
} doesn't always return the fully qualified
126 domain name; use
\code{gethostbyaddr(gethostname())
}
130 \begin{funcdesc
}{gethostbyaddr
}{ip_address
}
131 Return a triple
\code{(
\var{hostname
},
\var{aliaslist
},
132 \var{ipaddrlist
})
} where
\var{hostname
} is the primary host name
133 responding to the given
\var{ip_address
},
\var{aliaslist
} is a
134 (possibly empty) list of alternative host names for the same address,
135 and
\var{ipaddrlist
} is a list of IP addresses for the same interface
136 on the same host (most likely containing only a single address).
137 To find the fully qualified domain name, check
\var{hostname
} and the
138 items of
\var{aliaslist
} for an entry containing at least one period.
141 \begin{funcdesc
}{getprotobyname
}{protocolname
}
142 Translate an Internet protocol name (e.g.\
\code{'icmp'
}) to a constant
143 suitable for passing as the (optional) third argument to the
144 \function{socket()
} function. This is usually only needed for sockets
145 opened in ``raw'' mode (
\constant{SOCK_RAW
}); for the normal socket
146 modes, the correct protocol is chosen automatically if the protocol is
150 \begin{funcdesc
}{getservbyname
}{servicename, protocolname
}
151 Translate an Internet service name and protocol name to a port number
152 for that service. The protocol name should be
\code{'tcp'
} or
156 \begin{funcdesc
}{socket
}{family, type
\optional{, proto
}}
157 Create a new socket using the given address family, socket type and
158 protocol number. The address family should be
\constant{AF_INET
} or
159 \constant{AF_UNIX
}. The socket type should be
\constant{SOCK_STREAM
},
160 \constant{SOCK_DGRAM
} or perhaps one of the other
\samp{SOCK_
} constants.
161 The protocol number is usually zero and may be omitted in that case.
164 \begin{funcdesc
}{fromfd
}{fd, family, type
\optional{, proto
}}
165 Build a socket object from an existing file descriptor (an integer as
166 returned by a file object's
\method{fileno()
} method). Address family,
167 socket type and protocol number are as for the
\function{socket()
} function
168 above. The file descriptor should refer to a socket, but this is not
169 checked --- subsequent operations on the object may fail if the file
170 descriptor is invalid. This function is rarely needed, but can be
171 used to get or set socket options on a socket passed to a program as
172 standard input or output (e.g.\ a server started by the
\UNIX{} inet
176 \begin{funcdesc
}{ntohl
}{x
}
177 Convert
32-bit integers from network to host byte order. On machines
178 where the host byte order is the same as network byte order, this is a
179 no-op; otherwise, it performs a
4-byte swap operation.
182 \begin{funcdesc
}{ntohs
}{x
}
183 Convert
16-bit integers from network to host byte order. On machines
184 where the host byte order is the same as network byte order, this is a
185 no-op; otherwise, it performs a
2-byte swap operation.
188 \begin{funcdesc
}{htonl
}{x
}
189 Convert
32-bit integers from host to network byte order. On machines
190 where the host byte order is the same as network byte order, this is a
191 no-op; otherwise, it performs a
4-byte swap operation.
194 \begin{funcdesc
}{htons
}{x
}
195 Convert
16-bit integers from host to network byte order. On machines
196 where the host byte order is the same as network byte order, this is a
197 no-op; otherwise, it performs a
2-byte swap operation.
200 \begin{funcdesc
}{inet_aton
}{ip_string
}
201 Convert an IP address from dotted-quad string format
202 (e.g.\ '
123.45.67.89') to
32-bit packed binary format, as a string four
203 characters in length.
205 Useful when conversing with a program that uses the standard C library
206 and needs objects of type
\ctype{struct in_addr
}, which is the C type
207 for the
32-bit packed binary this function returns.
209 If the IP address string passed to this function is invalid,
210 \exception{socket.error
} will be raised. Note that exactly what is
211 valid depends on the underlying C implementation of
212 \cfunction{inet_aton()
}.
215 \begin{funcdesc
}{inet_ntoa
}{packed_ip
}
216 Convert a
32-bit packed IP address (a string four characters in
217 length) to its standard dotted-quad string representation
218 (e.g. '
123.45.67.89').
220 Useful when conversing with a program that uses the standard C library
221 and needs objects of type
\ctype{struct in_addr
}, which is the C type
222 for the
32-bit packed binary this function takes as an argument.
224 If the string passed to this function is not exactly
4 bytes in
225 length,
\exception{socket.error
} will be raised.
228 \begin{datadesc
}{SocketType
}
229 This is a Python type object that represents the socket object type.
230 It is the same as
\code{type(socket(...))
}.
235 \seemodule{SocketServer
}{Classes that simplify writing network servers.
}
239 \subsection{Socket Objects
\label{socket-objects
}}
241 Socket objects have the following methods. Except for
242 \method{makefile()
} these correspond to
\UNIX{} system calls
243 applicable to sockets.
245 \begin{methoddesc
}[socket
]{accept
}{}
247 The socket must be bound to an address and listening for connections.
248 The return value is a pair
\code{(
\var{conn
},
\var{address
})
}
249 where
\var{conn
} is a
\emph{new
} socket object usable to send and
250 receive data on the connection, and
\var{address
} is the address bound
251 to the socket on the other end of the connection.
254 \begin{methoddesc
}[socket
]{bind
}{address
}
255 Bind the socket to
\var{address
}. The socket must not already be bound.
256 (The format of
\var{address
} depends on the address family --- see
257 above.)
\strong{Note:
} This method has historically accepted a pair
258 of parameters for
\constant{AF_INET
} addresses instead of only a
259 tuple. This was never intentional and will no longer be available in
263 \begin{methoddesc
}[socket
]{close
}{}
264 Close the socket. All future operations on the socket object will fail.
265 The remote end will receive no more data (after queued data is flushed).
266 Sockets are automatically closed when they are garbage-collected.
269 \begin{methoddesc
}[socket
]{connect
}{address
}
270 Connect to a remote socket at
\var{address
}.
271 (The format of
\var{address
} depends on the address family --- see
272 above.)
\strong{Note:
} This method has historically accepted a pair
273 of parameters for
\constant{AF_INET
} addresses instead of only a
274 tuple. This was never intentional and will no longer be available in
278 \begin{methoddesc
}[socket
]{connect_ex
}{address
}
279 Like
\code{connect(
\var{address
})
}, but return an error indicator
280 instead of raising an exception for errors returned by the C-level
281 \cfunction{connect()
} call (other problems, such as ``host not found,''
282 can still raise exceptions). The error indicator is
\code{0} if the
283 operation succeeded, otherwise the value of the
\cdata{errno
}
284 variable. This is useful, e.g., for asynchronous connects.
285 \strong{Note:
} This method has historically accepted a pair of
286 parameters for
\constant{AF_INET
} addresses instead of only a tuple.
287 This was never intentional and will no longer be available in Python
291 \begin{methoddesc
}[socket
]{fileno
}{}
292 Return the socket's file descriptor (a small integer). This is useful
293 with
\function{select.select()
}.
296 \begin{methoddesc
}[socket
]{getpeername
}{}
297 Return the remote address to which the socket is connected. This is
298 useful to find out the port number of a remote IP socket, for instance.
299 (The format of the address returned depends on the address family ---
300 see above.) On some systems this function is not supported.
303 \begin{methoddesc
}[socket
]{getsockname
}{}
304 Return the socket's own address. This is useful to find out the port
305 number of an IP socket, for instance.
306 (The format of the address returned depends on the address family ---
310 \begin{methoddesc
}[socket
]{getsockopt
}{level, optname
\optional{, buflen
}}
311 Return the value of the given socket option (see the
\UNIX{} man page
312 \manpage{getsockopt
}{2}). The needed symbolic constants
313 (
\constant{SO_*
} etc.) are defined in this module. If
\var{buflen
}
314 is absent, an integer option is assumed and its integer value
315 is returned by the function. If
\var{buflen
} is present, it specifies
316 the maximum length of the buffer used to receive the option in, and
317 this buffer is returned as a string. It is up to the caller to decode
318 the contents of the buffer (see the optional built-in module
319 \refmodule{struct
} for a way to decode C structures encoded as strings).
322 \begin{methoddesc
}[socket
]{listen
}{backlog
}
323 Listen for connections made to the socket. The
\var{backlog
} argument
324 specifies the maximum number of queued connections and should be at
325 least
1; the maximum value is system-dependent (usually
5).
328 \begin{methoddesc
}[socket
]{makefile
}{\optional{mode
\optional{, bufsize
}}}
329 Return a
\dfn{file object
} associated with the socket. (File objects
330 are described in
\ref{bltin-file-objects
}, ``File Objects.'')
331 The file object references a
\cfunction{dup()
}ped version of the
332 socket file descriptor, so the file object and socket object may be
333 closed or garbage-collected independently.
334 \index{I/O control!buffering
}The optional
\var{mode
}
335 and
\var{bufsize
} arguments are interpreted the same way as by the
336 built-in
\function{open()
} function.
339 \begin{methoddesc
}[socket
]{recv
}{bufsize
\optional{, flags
}}
340 Receive data from the socket. The return value is a string representing
341 the data received. The maximum amount of data to be received
342 at once is specified by
\var{bufsize
}. See the
\UNIX{} manual page
343 \manpage{recv
}{2} for the meaning of the optional argument
344 \var{flags
}; it defaults to zero.
347 \begin{methoddesc
}[socket
]{recvfrom
}{bufsize
\optional{, flags
}}
348 Receive data from the socket. The return value is a pair
349 \code{(
\var{string
},
\var{address
})
} where
\var{string
} is a string
350 representing the data received and
\var{address
} is the address of the
351 socket sending the data. The optional
\var{flags
} argument has the
352 same meaning as for
\method{recv()
} above.
353 (The format of
\var{address
} depends on the address family --- see above.)
356 \begin{methoddesc
}[socket
]{send
}{string
\optional{, flags
}}
357 Send data to the socket. The socket must be connected to a remote
358 socket. The optional
\var{flags
} argument has the same meaning as for
359 \method{recv()
} above. Returns the number of bytes sent.
362 \begin{methoddesc
}[socket
]{sendto
}{string
\optional{, flags
}, address
}
363 Send data to the socket. The socket should not be connected to a
364 remote socket, since the destination socket is specified by
365 \var{address
}. The optional
\var{flags
} argument has the same
366 meaning as for
\method{recv()
} above. Return the number of bytes sent.
367 (The format of
\var{address
} depends on the address family --- see above.)
370 \begin{methoddesc
}[socket
]{setblocking
}{flag
}
371 Set blocking or non-blocking mode of the socket: if
\var{flag
} is
0,
372 the socket is set to non-blocking, else to blocking mode. Initially
373 all sockets are in blocking mode. In non-blocking mode, if a
374 \method{recv()
} call doesn't find any data, or if a
375 \method{send()
} call can't immediately dispose of the data, a
376 \exception{error
} exception is raised; in blocking mode, the calls
377 block until they can proceed.
380 \begin{methoddesc
}[socket
]{setsockopt
}{level, optname, value
}
381 Set the value of the given socket option (see the
\UNIX{} manual page
382 \manpage{setsockopt
}{2}). The needed symbolic constants are defined in
383 the
\module{socket
} module (
\code{SO_*
} etc.). The value can be an
384 integer or a string representing a buffer. In the latter case it is
385 up to the caller to ensure that the string contains the proper bits
386 (see the optional built-in module
387 \refmodule{struct
}\refbimodindex{struct
} for a way to encode C
388 structures as strings).
391 \begin{methoddesc
}[socket
]{shutdown
}{how
}
392 Shut down one or both halves of the connection. If
\var{how
} is
393 \code{0}, further receives are disallowed. If
\var{how
} is
\code{1},
394 further sends are disallowed. If
\var{how
} is
\code{2}, further sends
395 and receives are disallowed.
398 Note that there are no methods
\method{read()
} or
\method{write()
};
399 use
\method{recv()
} and
\method{send()
} without
\var{flags
} argument
403 \subsection{Example
\label{socket-example
}}
405 Here are two minimal example programs using the TCP/IP protocol:\ a
406 server that echoes all data that it receives back (servicing only one
407 client), and a client using it. Note that a server must perform the
408 sequence
\function{socket()
},
\method{bind()
},
\method{listen()
},
409 \method{accept()
} (possibly repeating the
\method{accept()
} to service
410 more than one client), while a client only needs the sequence
411 \function{socket()
},
\method{connect()
}. Also note that the server
412 does not
\method{send()
}/
\method{recv()
} on the
413 socket it is listening on but on the new socket returned by
417 # Echo server program
419 HOST = '' # Symbolic name meaning the local host
420 PORT =
50007 # Arbitrary non-privileged server
421 s = socket(AF_INET, SOCK_STREAM)
424 conn, addr = s.accept()
425 print 'Connected by', addr
427 data = conn.recv(
1024)
434 # Echo client program
436 HOST = 'daring.cwi.nl' # The remote host
437 PORT =
50007 # The same port as used by the server
438 s = socket(AF_INET, SOCK_STREAM)
439 s.connect((HOST, PORT))
440 s.send('Hello, world')
443 print 'Received', `data`