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)
22 For IPv6-ready APIs, readers may want to refer to
\rfc{2553} titled
23 \citetitle{Basic Socket Interface Extensions for IPv6
}.
25 The Python interface is a straightforward transliteration of the
26 \UNIX{} system call and library interface for sockets to Python's
27 object-oriented style: the
\function{socket()
} function returns a
28 \dfn{socket object
}\obindex{socket
} whose methods implement the
29 various socket system calls. Parameter types are somewhat
30 higher-level than in the C interface: as with
\method{read()
} and
31 \method{write()
} operations on Python files, buffer allocation on
32 receive operations is automatic, and buffer length is implicit on send
35 Socket addresses are represented as follows:
36 A single string is used for the
\constant{AF_UNIX
} address family.
37 A pair
\code{(
\var{host
},
\var{port
})
} is used for the
38 \constant{AF_INET
} address family, where
\var{host
} is a string
39 representing either a hostname in Internet domain notation like
40 \code{'daring.cwi.nl'
} or an IPv4 address like
\code{'
100.50.200.5'
},
41 and
\var{port
} is an integral port number.
42 For
\constant{AF_INET6
} address family, a four-tuple
43 \code{(
\var{host
},
\var{port
},
\var{flowinfo
},
\var{scopeid
})
} is
44 used, where
\var{flowinfo
} and
\var{scopeid
} represents
45 \code{sin6_flowinfo
} and
\code{sin6_scope_id
} member in
46 \constant{struct sockaddr_in6
} in C.
47 For
\module{socket
} module methods,
\var{flowinfo
} and
\var{scopeid
}
48 can be omitted just for backward compatibility. Note, however,
49 omission of
\var{scopeid
} can cause problems in manipulating scoped
50 IPv6 addresses. Other address families are currently not supported.
51 The address format required by a particular socket object is
52 automatically selected based on the address family specified when the
53 socket object was created.
55 For IPv4 addresses, two special forms are accepted instead of a host
56 address: the empty string represents
\constant{INADDR_ANY
}, and the string
57 \code{'<broadcast>'
} represents
\constant{INADDR_BROADCAST
}.
58 The behavior is not available for IPv6 for backward compatibility,
59 therefore, you may want to avoid these if you intend to support IPv6 with
62 If you use a hostname in the
\var{host
} portion of IPv4/v6 socket
63 address, the program may show a nondeterministic behavior, as Python
64 uses the first address returned from the DNS resolution. The socket
65 address will be resolved differently into an actual IPv4/v6 address,
66 depending on the results from DNS resolution and/or the host
67 configuration. For deterministic behavior use a numeric address in
70 All errors raise exceptions. The normal exceptions for invalid
71 argument types and out-of-memory conditions can be raised; errors
72 related to socket or address semantics raise the error
73 \exception{socket.error
}.
75 Non-blocking mode is supported through
76 \method{setblocking()
}. A generalization of this based on timeouts
77 is supported through
\method{settimeout()
}.
79 The module
\module{socket
} exports the following constants and functions:
82 \begin{excdesc
}{error
}
83 This exception is raised for socket-related errors.
84 The accompanying value is either a string telling what went wrong or a
85 pair
\code{(
\var{errno
},
\var{string
})
}
86 representing an error returned by a system
87 call, similar to the value accompanying
\exception{os.error
}.
88 See the module
\refmodule{errno
}\refbimodindex{errno
}, which contains
89 names for the error codes defined by the underlying operating system.
92 \begin{excdesc
}{herror
}
93 This exception is raised for address-related errors, i.e. for
94 functions that use
\var{h_errno
} in the C API, including
95 \function{gethostbyname_ex()
} and
\function{gethostbyaddr()
}.
97 The accompanying value is a pair
\code{(
\var{h_errno
},
\var{string
})
}
98 representing an error returned by a library call.
\var{string
}
99 represents the description of
\var{h_errno
}, as returned by
100 the
\cfunction{hstrerror()
} C function.
103 \begin{excdesc
}{gaierror
}
104 This exception is raised for address-related errors, for
105 \function{getaddrinfo()
} and
\function{getnameinfo()
}.
106 The accompanying value is a pair
\code{(
\var{error
},
\var{string
})
}
107 representing an error returned by a library call.
108 \var{string
} represents the description of
\var{error
}, as returned
109 by the
\cfunction{gai_strerror()
} C function.
112 \begin{datadesc
}{AF_UNIX
}
115 These constants represent the address (and protocol) families,
116 used for the first argument to
\function{socket()
}. If the
117 \constant{AF_UNIX
} constant is not defined then this protocol is
121 \begin{datadesc
}{SOCK_STREAM
}
122 \dataline{SOCK_DGRAM
}
125 \dataline{SOCK_SEQPACKET
}
126 These constants represent the socket types,
127 used for the second argument to
\function{socket()
}.
128 (Only
\constant{SOCK_STREAM
} and
129 \constant{SOCK_DGRAM
} appear to be generally useful.)
132 \begin{datadesc
}{SO_*
}
145 Many constants of these forms, documented in the
\UNIX{} documentation on
146 sockets and/or the IP protocol, are also defined in the socket module.
147 They are generally used in arguments to the
\method{setsockopt()
} and
148 \method{getsockopt()
} methods of socket objects. In most cases, only
149 those symbols that are defined in the
\UNIX{} header files are defined;
150 for a few symbols, default values are provided.
153 \begin{funcdesc
}{getaddrinfo
}{host, port
\optional{, family, socktype, proto, flags
}}
155 Resolves the
\var{host
}/
\var{port
} argument, into a sequence of
156 5-tuples that contain all the necessary argument for the sockets
157 manipulation.
\var{host
} is a domain name, a string representation of
158 IPv4/v6 address or
\code{None
}.
159 \var{port
} is a string service name (like
\code{``http''
}), a numeric
160 port number or
\code{None
}.
162 The rest of the arguments are optional and must be numeric if
163 specified. For
\var{host
} and
\var{port
}, by passing either an empty
164 string or
\code{None
}, you can pass
\code{NULL
} to the C API. The
165 \function{getaddrinfo()
} function returns a list of
5-tuples with
166 the following structure:
168 \code{(
\var{family
},
\var{socktype
},
\var{proto
},
\var{canonname
},
\var{sockaddr
})
}.
170 \var{family
},
\var{socktype
},
\var{proto
} are all integer and are meant to
171 be passed to the
\function{socket()
} function.
172 \var{canonname
} is a string representing the canonical name of the
\var{host
}.
173 It can be a numeric IPv4/v6 address when
\code{AI_CANONNAME
} is specified
174 for a numeric
\var{host
}.
175 \var{sockaddr
} is a tuple describing a socket address, as described above.
176 See
\code{Lib/httplib.py
} and other library files
177 for a typical usage of the function.
181 \begin{funcdesc
}{getfqdn
}{\optional{name
}}
182 Return a fully qualified domain name for
\var{name
}.
183 If
\var{name
} is omitted or empty, it is interpreted as the local
184 host. To find the fully qualified name, the hostname returned by
185 \function{gethostbyaddr()
} is checked, then aliases for the host, if
186 available. The first name which includes a period is selected. In
187 case no fully qualified domain name is available, the hostname is
192 \begin{funcdesc
}{gethostbyname
}{hostname
}
193 Translate a host name to IPv4 address format. The IPv4 address is
194 returned as a string, such as
\code{'
100.50.200.5'
}. If the host name
195 is an IPv4 address itself it is returned unchanged. See
196 \function{gethostbyname_ex()
} for a more complete interface.
197 \function{gethostbyname()
} does not support IPv6 name resolution, and
198 \function{getaddrinfo()
} should be used instead for IPv4/v6 dual stack support.
201 \begin{funcdesc
}{gethostbyname_ex
}{hostname
}
202 Translate a host name to IPv4 address format, extended interface.
203 Return a triple
\code{(hostname, aliaslist, ipaddrlist)
} where
204 \code{hostname
} is the primary host name responding to the given
205 \var{ip_address
},
\code{aliaslist
} is a (possibly empty) list of
206 alternative host names for the same address, and
\code{ipaddrlist
} is
207 a list of IPv4 addresses for the same interface on the same
208 host (often but not always a single address).
209 \function{gethostbyname_ex()
} does not support IPv6 name resolution, and
210 \function{getaddrinfo()
} should be used instead for IPv4/v6 dual stack support.
213 \begin{funcdesc
}{gethostname
}{}
214 Return a string containing the hostname of the machine where
215 the Python interpreter is currently executing.
216 If you want to know the current machine's IP address, you may want to use
217 \code{gethostbyname(gethostname())
}.
218 This operation assumes that there is a valid address-to-host mapping for
219 the host, and the assumption does not always hold.
220 Note:
\function{gethostname()
} doesn't always return the fully qualified
221 domain name; use
\code{gethostbyaddr(gethostname())
}
225 \begin{funcdesc
}{gethostbyaddr
}{ip_address
}
226 Return a triple
\code{(
\var{hostname
},
\var{aliaslist
},
227 \var{ipaddrlist
})
} where
\var{hostname
} is the primary host name
228 responding to the given
\var{ip_address
},
\var{aliaslist
} is a
229 (possibly empty) list of alternative host names for the same address,
230 and
\var{ipaddrlist
} is a list of IPv4/v6 addresses for the same interface
231 on the same host (most likely containing only a single address).
232 To find the fully qualified domain name, use the function
233 \function{getfqdn()
}.
234 \function{gethostbyaddr
} supports both IPv4 and IPv6.
237 \begin{funcdesc
}{getnameinfo
}{sockaddr, flags
}
238 Translate a socket address
\var{sockaddr
} into a
2-tuple
239 \code{(
\var{host
},
\var{port
})
}.
240 Depending on the settings of
\var{flags
}, the result can contain a
241 fully-qualified domain name or numeric address representation in
242 \var{host
}. Similarly,
\var{port
} can contain a string port name or a
247 \begin{funcdesc
}{getprotobyname
}{protocolname
}
248 Translate an Internet protocol name (for example,
\code{'icmp'
}) to a constant
249 suitable for passing as the (optional) third argument to the
250 \function{socket()
} function. This is usually only needed for sockets
251 opened in ``raw'' mode (
\constant{SOCK_RAW
}); for the normal socket
252 modes, the correct protocol is chosen automatically if the protocol is
256 \begin{funcdesc
}{getservbyname
}{servicename, protocolname
}
257 Translate an Internet service name and protocol name to a port number
258 for that service. The protocol name should be
\code{'tcp'
} or
262 \begin{funcdesc
}{socket
}{family, type
\optional{, proto
}}
263 Create a new socket using the given address family, socket type and
264 protocol number. The address family should be
\constant{AF_INET
},
\constant{AF_INET6
} or
265 \constant{AF_UNIX
}. The socket type should be
\constant{SOCK_STREAM
},
266 \constant{SOCK_DGRAM
} or perhaps one of the other
\samp{SOCK_
} constants.
267 The protocol number is usually zero and may be omitted in that case.
270 \begin{funcdesc
}{ssl
}{sock
\optional{, keyfile, certfile
}}
271 Initiate a SSL connection over the socket
\var{sock
}.
\var{keyfile
} is
272 the name of a PEM formatted file that contains your private
273 key.
\var{certfile
} is a PEM formatted certificate chain file. On
274 success, a new
\class{SSLObject
} is returned.
276 \warning{This does not do any certificate verification!
}
279 \begin{funcdesc
}{fromfd
}{fd, family, type
\optional{, proto
}}
280 Build a socket object from an existing file descriptor (an integer as
281 returned by a file object's
\method{fileno()
} method). Address family,
282 socket type and protocol number are as for the
\function{socket()
} function
283 above. The file descriptor should refer to a socket, but this is not
284 checked --- subsequent operations on the object may fail if the file
285 descriptor is invalid. This function is rarely needed, but can be
286 used to get or set socket options on a socket passed to a program as
287 standard input or output (such as a server started by the
\UNIX{} inet
288 daemon). The socket is assumed to be in blocking mode.
292 \begin{funcdesc
}{ntohl
}{x
}
293 Convert
32-bit integers from network to host byte order. On machines
294 where the host byte order is the same as network byte order, this is a
295 no-op; otherwise, it performs a
4-byte swap operation.
298 \begin{funcdesc
}{ntohs
}{x
}
299 Convert
16-bit integers from network to host byte order. On machines
300 where the host byte order is the same as network byte order, this is a
301 no-op; otherwise, it performs a
2-byte swap operation.
304 \begin{funcdesc
}{htonl
}{x
}
305 Convert
32-bit integers from host to network byte order. On machines
306 where the host byte order is the same as network byte order, this is a
307 no-op; otherwise, it performs a
4-byte swap operation.
310 \begin{funcdesc
}{htons
}{x
}
311 Convert
16-bit integers from host to network byte order. On machines
312 where the host byte order is the same as network byte order, this is a
313 no-op; otherwise, it performs a
2-byte swap operation.
316 \begin{funcdesc
}{inet_aton
}{ip_string
}
317 Convert an IPv4 address from dotted-quad string format (for example,
318 '
123.45.67.89') to
32-bit packed binary format, as a string four
319 characters in length.
321 Useful when conversing with a program that uses the standard C library
322 and needs objects of type
\ctype{struct in_addr
}, which is the C type
323 for the
32-bit packed binary this function returns.
325 If the IPv4 address string passed to this function is invalid,
326 \exception{socket.error
} will be raised. Note that exactly what is
327 valid depends on the underlying C implementation of
328 \cfunction{inet_aton()
}.
330 \function{inet_aton()
} does not support IPv6, and
331 \function{getnameinfo()
} should be used instead for IPv4/v6 dual stack
335 \begin{funcdesc
}{inet_ntoa
}{packed_ip
}
336 Convert a
32-bit packed IPv4 address (a string four characters in
337 length) to its standard dotted-quad string representation
338 (for example, '
123.45.67.89').
340 Useful when conversing with a program that uses the standard C library
341 and needs objects of type
\ctype{struct in_addr
}, which is the C type
342 for the
32-bit packed binary this function takes as an argument.
344 If the string passed to this function is not exactly
4 bytes in
345 length,
\exception{socket.error
} will be raised.
347 \function{inet_ntoa()
} does not support IPv6, and
348 \function{getnameinfo()
} should be used instead for IPv4/v6 dual stack
352 \begin{datadesc
}{SocketType
}
353 This is a Python type object that represents the socket object type.
354 It is the same as
\code{type(socket(...))
}.
359 \seemodule{SocketServer
}{Classes that simplify writing network servers.
}
363 \subsection{Socket Objects
\label{socket-objects
}}
365 Socket objects have the following methods. Except for
366 \method{makefile()
} these correspond to
\UNIX{} system calls
367 applicable to sockets.
369 \begin{methoddesc
}[socket
]{accept
}{}
371 The socket must be bound to an address and listening for connections.
372 The return value is a pair
\code{(
\var{conn
},
\var{address
})
}
373 where
\var{conn
} is a
\emph{new
} socket object usable to send and
374 receive data on the connection, and
\var{address
} is the address bound
375 to the socket on the other end of the connection.
378 \begin{methoddesc
}[socket
]{bind
}{address
}
379 Bind the socket to
\var{address
}. The socket must not already be bound.
380 (The format of
\var{address
} depends on the address family --- see
381 above.)
\note{This method has historically accepted a pair
382 of parameters for
\constant{AF_INET
} addresses instead of only a
383 tuple. This was never intentional and is no longer be available in
387 \begin{methoddesc
}[socket
]{close
}{}
388 Close the socket. All future operations on the socket object will fail.
389 The remote end will receive no more data (after queued data is flushed).
390 Sockets are automatically closed when they are garbage-collected.
393 \begin{methoddesc
}[socket
]{connect
}{address
}
394 Connect to a remote socket at
\var{address
}.
395 (The format of
\var{address
} depends on the address family --- see
396 above.)
\note{This method has historically accepted a pair
397 of parameters for
\constant{AF_INET
} addresses instead of only a
398 tuple. This was never intentional and is no longer available in
399 Python
2.0 and later.
}
402 \begin{methoddesc
}[socket
]{connect_ex
}{address
}
403 Like
\code{connect(
\var{address
})
}, but return an error indicator
404 instead of raising an exception for errors returned by the C-level
405 \cfunction{connect()
} call (other problems, such as ``host not found,''
406 can still raise exceptions). The error indicator is
\code{0} if the
407 operation succeeded, otherwise the value of the
\cdata{errno
}
408 variable. This is useful to support, for example, asynchronous connects.
409 \note{This method has historically accepted a pair of
410 parameters for
\constant{AF_INET
} addresses instead of only a tuple.
411 This was never intentional and is no longer be available in Python
415 \begin{methoddesc
}[socket
]{fileno
}{}
416 Return the socket's file descriptor (a small integer). This is useful
417 with
\function{select.select()
}.
420 \begin{methoddesc
}[socket
]{getpeername
}{}
421 Return the remote address to which the socket is connected. This is
422 useful to find out the port number of a remote IPv4/v6 socket, for instance.
423 (The format of the address returned depends on the address family ---
424 see above.) On some systems this function is not supported.
427 \begin{methoddesc
}[socket
]{getsockname
}{}
428 Return the socket's own address. This is useful to find out the port
429 number of an IPv4/v6 socket, for instance.
430 (The format of the address returned depends on the address family ---
434 \begin{methoddesc
}[socket
]{getsockopt
}{level, optname
\optional{, buflen
}}
435 Return the value of the given socket option (see the
\UNIX{} man page
436 \manpage{getsockopt
}{2}). The needed symbolic constants
437 (
\constant{SO_*
} etc.) are defined in this module. If
\var{buflen
}
438 is absent, an integer option is assumed and its integer value
439 is returned by the function. If
\var{buflen
} is present, it specifies
440 the maximum length of the buffer used to receive the option in, and
441 this buffer is returned as a string. It is up to the caller to decode
442 the contents of the buffer (see the optional built-in module
443 \refmodule{struct
} for a way to decode C structures encoded as strings).
446 \begin{methoddesc
}[socket
]{listen
}{backlog
}
447 Listen for connections made to the socket. The
\var{backlog
} argument
448 specifies the maximum number of queued connections and should be at
449 least
1; the maximum value is system-dependent (usually
5).
452 \begin{methoddesc
}[socket
]{makefile
}{\optional{mode
\optional{, bufsize
}}}
453 Return a
\dfn{file object
} associated with the socket. (File objects
454 are described in
\ref{bltin-file-objects
}, ``File Objects.'')
455 The file object references a
\cfunction{dup()
}ped version of the
456 socket file descriptor, so the file object and socket object may be
457 closed or garbage-collected independently.
458 The socket should be in blocking mode.
459 \index{I/O control!buffering
}The optional
\var{mode
}
460 and
\var{bufsize
} arguments are interpreted the same way as by the
461 built-in
\function{file()
} function; see ``Built-in Functions''
462 (section
\ref{built-in-funcs
}) for more information.
465 \begin{methoddesc
}[socket
]{recv
}{bufsize
\optional{, flags
}}
466 Receive data from the socket. The return value is a string representing
467 the data received. The maximum amount of data to be received
468 at once is specified by
\var{bufsize
}. See the
\UNIX{} manual page
469 \manpage{recv
}{2} for the meaning of the optional argument
470 \var{flags
}; it defaults to zero.
473 \begin{methoddesc
}[socket
]{recvfrom
}{bufsize
\optional{, flags
}}
474 Receive data from the socket. The return value is a pair
475 \code{(
\var{string
},
\var{address
})
} where
\var{string
} is a string
476 representing the data received and
\var{address
} is the address of the
477 socket sending the data. The optional
\var{flags
} argument has the
478 same meaning as for
\method{recv()
} above.
479 (The format of
\var{address
} depends on the address family --- see above.)
482 \begin{methoddesc
}[socket
]{send
}{string
\optional{, flags
}}
483 Send data to the socket. The socket must be connected to a remote
484 socket. The optional
\var{flags
} argument has the same meaning as for
485 \method{recv()
} above. Returns the number of bytes sent.
486 Applications are responsible for checking that all data has been sent;
487 if only some of the data was transmitted, the application needs to
488 attempt delivery of the remaining data.
491 \begin{methoddesc
}[socket
]{sendall
}{string
\optional{, flags
}}
492 Send data to the socket. The socket must be connected to a remote
493 socket. The optional
\var{flags
} argument has the same meaning as for
494 \method{recv()
} above. Unlike
\method{send()
}, this method continues
495 to send data from
\var{string
} until either all data has been sent or
496 an error occurs.
\code{None
} is returned on success. On error, an
497 exception is raised, and there is no way to determine how much data,
498 if any, was successfully sent.
501 \begin{methoddesc
}[socket
]{sendto
}{string
\optional{, flags
}, address
}
502 Send data to the socket. The socket should not be connected to a
503 remote socket, since the destination socket is specified by
504 \var{address
}. The optional
\var{flags
} argument has the same
505 meaning as for
\method{recv()
} above. Return the number of bytes sent.
506 (The format of
\var{address
} depends on the address family --- see above.)
509 \begin{methoddesc
}[socket
]{setblocking
}{flag
}
510 Set blocking or non-blocking mode of the socket: if
\var{flag
} is
0,
511 the socket is set to non-blocking, else to blocking mode. Initially
512 all sockets are in blocking mode. In non-blocking mode, if a
513 \method{recv()
} call doesn't find any data, or if a
514 \method{send()
} call can't immediately dispose of the data, a
515 \exception{error
} exception is raised; in blocking mode, the calls
516 block until they can proceed.
517 \code{s.setblocking(
0)
} is equivalent to
\code{s.settimeout(
0)
};
518 \code{s.setblocking(
1)
} is equivalent to
\code{s.settimeout(None)
}.
521 \begin{methoddesc
}[socket
]{settimeout
}{value
}
522 Set a timeout on blocking socket operations. The
\var{value
} argument
523 can be a nonnegative float expressing seconds, or
\code{None
}.
525 given, subsequent socket operations will raise an
\exception{error
}
526 exception if the timeout period
\var{value
} has elapsed before the
527 operation has completed. Setting a timeout of
\code{None
} disables
528 timeouts on socket operations.
529 \code{s.settimeout(
0.0)
} is equivalent to
\code{s.blocking(
0)
};
530 \code{s.settimeout(None)
} is equivalent to
\code{s.setblocking(
1)
}.
534 \begin{methoddesc
}[socket
]{gettimeout
}{}
535 Returns the timeout in floating seconds associated with socket
536 operations, or
\code{None
} if no timeout is set. This reflects
537 the last call to
\method{setblocking()
} or
\method{settimeout()
}.
541 Some notes on socket blocking and timeouts: A socket object can be in
542 one of three modes: blocking, non-blocking, or timout. Sockets are
543 always created in blocking mode. In blocking mode, operations block
544 until complete. In non-blocking mode, operations fail (with an error
545 that is unfortunately system-dependent) if they cannot be completed
546 immediately. In timeout mode, operations fail if they cannot be
547 completed within the timeout specified for the socket. The
548 \method{setblocking()
} method is simply a shorthand for certain
549 \method{settimeout()
} calls.
551 Timeout mode internally sets the socket in non-blocking mode. The
552 blocking and timeout modes are shared between file descriptors and
553 socket objects that refer to the same network endpoint. A consequence
554 of this is that file objects returned by the
\method{makefile()
}
555 method should only be used when the socket is in blocking mode; in
556 timeout or non-blocking mode file operations that cannot be completed
557 immediately will fail.
559 \begin{methoddesc
}[socket
]{setsockopt
}{level, optname, value
}
560 Set the value of the given socket option (see the
\UNIX{} manual page
561 \manpage{setsockopt
}{2}). The needed symbolic constants are defined in
562 the
\module{socket
} module (
\code{SO_*
} etc.). The value can be an
563 integer or a string representing a buffer. In the latter case it is
564 up to the caller to ensure that the string contains the proper bits
565 (see the optional built-in module
566 \refmodule{struct
}\refbimodindex{struct
} for a way to encode C
567 structures as strings).
570 \begin{methoddesc
}[socket
]{shutdown
}{how
}
571 Shut down one or both halves of the connection. If
\var{how
} is
572 \code{0}, further receives are disallowed. If
\var{how
} is
\code{1},
573 further sends are disallowed. If
\var{how
} is
\code{2}, further sends
574 and receives are disallowed.
577 Note that there are no methods
\method{read()
} or
\method{write()
};
578 use
\method{recv()
} and
\method{send()
} without
\var{flags
} argument
582 \subsection{SSL Objects
\label{ssl-objects
}}
584 SSL objects have the following methods.
586 \begin{methoddesc
}{write
}{s
}
587 Writes the string
\var{s
} to the on the object's SSL connection.
588 The return value is the number of bytes written.
591 \begin{methoddesc
}{read
}{\optional{n
}}
592 If
\var{n
} is provided, read
\var{n
} bytes from the SSL connection, otherwise
593 read until EOF. The return value is a string of the bytes read.
596 \subsection{Example
\label{socket-example
}}
598 Here are four minimal example programs using the TCP/IP protocol:\ a
599 server that echoes all data that it receives back (servicing only one
600 client), and a client using it. Note that a server must perform the
601 sequence
\function{socket()
},
\method{bind()
},
\method{listen()
},
602 \method{accept()
} (possibly repeating the
\method{accept()
} to service
603 more than one client), while a client only needs the sequence
604 \function{socket()
},
\method{connect()
}. Also note that the server
605 does not
\method{send()
}/
\method{recv()
} on the
606 socket it is listening on but on the new socket returned by
609 The first two examples support IPv4 only.
612 # Echo server program
615 HOST = '' # Symbolic name meaning the local host
616 PORT =
50007 # Arbitrary non-privileged port
617 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
620 conn, addr = s.accept()
621 print 'Connected by', addr
623 data = conn.recv(
1024)
630 # Echo client program
633 HOST = 'daring.cwi.nl' # The remote host
634 PORT =
50007 # The same port as used by the server
635 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
636 s.connect((HOST, PORT))
637 s.send('Hello, world')
640 print 'Received', `data`
643 The next two examples are identical to the above two, but support both
645 The server side will listen to the first address family available
646 (it should listen to both instead).
647 On most of IPv6-ready systems, IPv6 will take precedence
648 and the server may not accept IPv4 traffic.
649 The client side will try to connect to the all addresses returned as a result
650 of the name resolution, and sends traffic to the first one connected
654 # Echo server program
658 HOST = '' # Symbolic name meaning the local host
659 PORT =
50007 # Arbitrary non-privileged port
661 for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM,
0, socket.AI_PASSIVE):
662 af, socktype, proto, canonname, sa = res
664 s = socket.socket(af, socktype, proto)
665 except socket.error, msg:
671 except socket.error, msg:
677 print 'could not open socket'
679 conn, addr = s.accept()
680 print 'Connected by', addr
682 data = conn.recv(
1024)
689 # Echo client program
693 HOST = 'daring.cwi.nl' # The remote host
694 PORT =
50007 # The same port as used by the server
696 for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM):
697 af, socktype, proto, canonname, sa = res
699 s = socket.socket(af, socktype, proto)
700 except socket.error, msg:
705 except socket.error, msg:
711 print 'could not open socket'
713 s.send('Hello, world')
716 print 'Received', `data`