PageRenderTime 67ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/Doc/lib/libsocket.tex

https://bitbucket.org/mirror/python-release25-maint
LaTeX | 910 lines | 785 code | 125 blank | 0 comment | 0 complexity | 2a14cbf861dad04fa0f8aba1be28ee43 MD5 | raw file
Possible License(s): 0BSD
  1. \section{\module{socket} ---
  2. Low-level networking interface}
  3. \declaremodule{builtin}{socket}
  4. \modulesynopsis{Low-level networking interface.}
  5. This module provides access to the BSD \emph{socket} interface.
  6. It is available on all modern \UNIX{} systems, Windows, MacOS, BeOS,
  7. OS/2, and probably additional platforms. \note{Some behavior may be
  8. platform dependent, since calls are made to the operating system socket APIs.}
  9. For an introduction to socket programming (in C), see the following
  10. papers: \citetitle{An Introductory 4.3BSD Interprocess Communication
  11. Tutorial}, by Stuart Sechrest and \citetitle{An Advanced 4.3BSD
  12. Interprocess Communication Tutorial}, by Samuel J. Leffler et al,
  13. both in the \citetitle{\UNIX{} Programmer's Manual, Supplementary Documents 1}
  14. (sections PS1:7 and PS1:8). The platform-specific reference material
  15. for the various socket-related system calls are also a valuable source
  16. of information on the details of socket semantics. For \UNIX, refer
  17. to the manual pages; for Windows, see the WinSock (or Winsock 2)
  18. specification.
  19. For IPv6-ready APIs, readers may want to refer to \rfc{2553} titled
  20. \citetitle{Basic Socket Interface Extensions for IPv6}.
  21. The Python interface is a straightforward transliteration of the
  22. \UNIX{} system call and library interface for sockets to Python's
  23. object-oriented style: the \function{socket()} function returns a
  24. \dfn{socket object}\obindex{socket} whose methods implement the
  25. various socket system calls. Parameter types are somewhat
  26. higher-level than in the C interface: as with \method{read()} and
  27. \method{write()} operations on Python files, buffer allocation on
  28. receive operations is automatic, and buffer length is implicit on send
  29. operations.
  30. Socket addresses are represented as follows:
  31. A single string is used for the \constant{AF_UNIX} address family.
  32. A pair \code{(\var{host}, \var{port})} is used for the
  33. \constant{AF_INET} address family, where \var{host} is a string
  34. representing either a hostname in Internet domain notation like
  35. \code{'daring.cwi.nl'} or an IPv4 address like \code{'100.50.200.5'},
  36. and \var{port} is an integral port number.
  37. For \constant{AF_INET6} address family, a four-tuple
  38. \code{(\var{host}, \var{port}, \var{flowinfo}, \var{scopeid})} is
  39. used, where \var{flowinfo} and \var{scopeid} represents
  40. \code{sin6_flowinfo} and \code{sin6_scope_id} member in
  41. \constant{struct sockaddr_in6} in C.
  42. For \module{socket} module methods, \var{flowinfo} and \var{scopeid}
  43. can be omitted just for backward compatibility. Note, however,
  44. omission of \var{scopeid} can cause problems in manipulating scoped
  45. IPv6 addresses. Other address families are currently not supported.
  46. The address format required by a particular socket object is
  47. automatically selected based on the address family specified when the
  48. socket object was created.
  49. For IPv4 addresses, two special forms are accepted instead of a host
  50. address: the empty string represents \constant{INADDR_ANY}, and the string
  51. \code{'<broadcast>'} represents \constant{INADDR_BROADCAST}.
  52. The behavior is not available for IPv6 for backward compatibility,
  53. therefore, you may want to avoid these if you intend to support IPv6 with
  54. your Python programs.
  55. If you use a hostname in the \var{host} portion of IPv4/v6 socket
  56. address, the program may show a nondeterministic behavior, as Python
  57. uses the first address returned from the DNS resolution. The socket
  58. address will be resolved differently into an actual IPv4/v6 address,
  59. depending on the results from DNS resolution and/or the host
  60. configuration. For deterministic behavior use a numeric address in
  61. \var{host} portion.
  62. \versionadded[AF_NETLINK sockets are represented as
  63. pairs \code{\var{pid}, \var{groups}}]{2.5}
  64. All errors raise exceptions. The normal exceptions for invalid
  65. argument types and out-of-memory conditions can be raised; errors
  66. related to socket or address semantics raise the error
  67. \exception{socket.error}.
  68. Non-blocking mode is supported through
  69. \method{setblocking()}. A generalization of this based on timeouts
  70. is supported through \method{settimeout()}.
  71. The module \module{socket} exports the following constants and functions:
  72. \begin{excdesc}{error}
  73. This exception is raised for socket-related errors.
  74. The accompanying value is either a string telling what went wrong or a
  75. pair \code{(\var{errno}, \var{string})}
  76. representing an error returned by a system
  77. call, similar to the value accompanying \exception{os.error}.
  78. See the module \refmodule{errno}\refbimodindex{errno}, which contains
  79. names for the error codes defined by the underlying operating system.
  80. \end{excdesc}
  81. \begin{excdesc}{herror}
  82. This exception is raised for address-related errors, i.e. for
  83. functions that use \var{h_errno} in the C API, including
  84. \function{gethostbyname_ex()} and \function{gethostbyaddr()}.
  85. The accompanying value is a pair \code{(\var{h_errno}, \var{string})}
  86. representing an error returned by a library call. \var{string}
  87. represents the description of \var{h_errno}, as returned by
  88. the \cfunction{hstrerror()} C function.
  89. \end{excdesc}
  90. \begin{excdesc}{gaierror}
  91. This exception is raised for address-related errors, for
  92. \function{getaddrinfo()} and \function{getnameinfo()}.
  93. The accompanying value is a pair \code{(\var{error}, \var{string})}
  94. representing an error returned by a library call.
  95. \var{string} represents the description of \var{error}, as returned
  96. by the \cfunction{gai_strerror()} C function.
  97. The \var{error} value will match one of the \constant{EAI_*} constants
  98. defined in this module.
  99. \end{excdesc}
  100. \begin{excdesc}{timeout}
  101. This exception is raised when a timeout occurs on a socket which has
  102. had timeouts enabled via a prior call to \method{settimeout()}. The
  103. accompanying value is a string whose value is currently always ``timed
  104. out''.
  105. \versionadded{2.3}
  106. \end{excdesc}
  107. \begin{datadesc}{AF_UNIX}
  108. \dataline{AF_INET}
  109. \dataline{AF_INET6}
  110. These constants represent the address (and protocol) families,
  111. used for the first argument to \function{socket()}. If the
  112. \constant{AF_UNIX} constant is not defined then this protocol is
  113. unsupported.
  114. \end{datadesc}
  115. \begin{datadesc}{SOCK_STREAM}
  116. \dataline{SOCK_DGRAM}
  117. \dataline{SOCK_RAW}
  118. \dataline{SOCK_RDM}
  119. \dataline{SOCK_SEQPACKET}
  120. These constants represent the socket types,
  121. used for the second argument to \function{socket()}.
  122. (Only \constant{SOCK_STREAM} and
  123. \constant{SOCK_DGRAM} appear to be generally useful.)
  124. \end{datadesc}
  125. \begin{datadesc}{SO_*}
  126. \dataline{SOMAXCONN}
  127. \dataline{MSG_*}
  128. \dataline{SOL_*}
  129. \dataline{IPPROTO_*}
  130. \dataline{IPPORT_*}
  131. \dataline{INADDR_*}
  132. \dataline{IP_*}
  133. \dataline{IPV6_*}
  134. \dataline{EAI_*}
  135. \dataline{AI_*}
  136. \dataline{NI_*}
  137. \dataline{TCP_*}
  138. Many constants of these forms, documented in the \UNIX{} documentation on
  139. sockets and/or the IP protocol, are also defined in the socket module.
  140. They are generally used in arguments to the \method{setsockopt()} and
  141. \method{getsockopt()} methods of socket objects. In most cases, only
  142. those symbols that are defined in the \UNIX{} header files are defined;
  143. for a few symbols, default values are provided.
  144. \end{datadesc}
  145. \begin{datadesc}{has_ipv6}
  146. This constant contains a boolean value which indicates if IPv6 is
  147. supported on this platform.
  148. \versionadded{2.3}
  149. \end{datadesc}
  150. \begin{funcdesc}{getaddrinfo}{host, port\optional{, family\optional{,
  151. socktype\optional{, proto\optional{,
  152. flags}}}}}
  153. Resolves the \var{host}/\var{port} argument, into a sequence of
  154. 5-tuples that contain all the necessary argument for the sockets
  155. manipulation. \var{host} is a domain name, a string representation of
  156. IPv4/v6 address or \code{None}.
  157. \var{port} is a string service name (like \code{'http'}), a numeric
  158. port number or \code{None}.
  159. The rest of the arguments are optional and must be numeric if
  160. specified. For \var{host} and \var{port}, by passing either an empty
  161. string or \code{None}, you can pass \code{NULL} to the C API. The
  162. \function{getaddrinfo()} function returns a list of 5-tuples with
  163. the following structure:
  164. \code{(\var{family}, \var{socktype}, \var{proto}, \var{canonname},
  165. \var{sockaddr})}
  166. \var{family}, \var{socktype}, \var{proto} are all integer and are meant to
  167. be passed to the \function{socket()} function.
  168. \var{canonname} is a string representing the canonical name of the \var{host}.
  169. It can be a numeric IPv4/v6 address when \constant{AI_CANONNAME} is specified
  170. for a numeric \var{host}.
  171. \var{sockaddr} is a tuple describing a socket address, as described above.
  172. See the source for the \refmodule{httplib} and other library modules
  173. for a typical usage of the function.
  174. \versionadded{2.2}
  175. \end{funcdesc}
  176. \begin{funcdesc}{getfqdn}{\optional{name}}
  177. Return a fully qualified domain name for \var{name}.
  178. If \var{name} is omitted or empty, it is interpreted as the local
  179. host. To find the fully qualified name, the hostname returned by
  180. \function{gethostbyaddr()} is checked, then aliases for the host, if
  181. available. The first name which includes a period is selected. In
  182. case no fully qualified domain name is available, the hostname as
  183. returned by \function{gethostname()} is returned.
  184. \versionadded{2.0}
  185. \end{funcdesc}
  186. \begin{funcdesc}{gethostbyname}{hostname}
  187. Translate a host name to IPv4 address format. The IPv4 address is
  188. returned as a string, such as \code{'100.50.200.5'}. If the host name
  189. is an IPv4 address itself it is returned unchanged. See
  190. \function{gethostbyname_ex()} for a more complete interface.
  191. \function{gethostbyname()} does not support IPv6 name resolution, and
  192. \function{getaddrinfo()} should be used instead for IPv4/v6 dual stack support.
  193. \end{funcdesc}
  194. \begin{funcdesc}{gethostbyname_ex}{hostname}
  195. Translate a host name to IPv4 address format, extended interface.
  196. Return a triple \code{(\var{hostname}, \var{aliaslist},
  197. \var{ipaddrlist})} where
  198. \var{hostname} is the primary host name responding to the given
  199. \var{ip_address}, \var{aliaslist} is a (possibly empty) list of
  200. alternative host names for the same address, and \var{ipaddrlist} is
  201. a list of IPv4 addresses for the same interface on the same
  202. host (often but not always a single address).
  203. \function{gethostbyname_ex()} does not support IPv6 name resolution, and
  204. \function{getaddrinfo()} should be used instead for IPv4/v6 dual stack support.
  205. \end{funcdesc}
  206. \begin{funcdesc}{gethostname}{}
  207. Return a string containing the hostname of the machine where
  208. the Python interpreter is currently executing.
  209. If you want to know the current machine's IP address, you may want to use
  210. \code{gethostbyname(gethostname())}.
  211. This operation assumes that there is a valid address-to-host mapping for
  212. the host, and the assumption does not always hold.
  213. Note: \function{gethostname()} doesn't always return the fully qualified
  214. domain name; use \code{getfqdn()}
  215. (see above).
  216. \end{funcdesc}
  217. \begin{funcdesc}{gethostbyaddr}{ip_address}
  218. Return a triple \code{(\var{hostname}, \var{aliaslist},
  219. \var{ipaddrlist})} where \var{hostname} is the primary host name
  220. responding to the given \var{ip_address}, \var{aliaslist} is a
  221. (possibly empty) list of alternative host names for the same address,
  222. and \var{ipaddrlist} is a list of IPv4/v6 addresses for the same interface
  223. on the same host (most likely containing only a single address).
  224. To find the fully qualified domain name, use the function
  225. \function{getfqdn()}.
  226. \function{gethostbyaddr} supports both IPv4 and IPv6.
  227. \end{funcdesc}
  228. \begin{funcdesc}{getnameinfo}{sockaddr, flags}
  229. Translate a socket address \var{sockaddr} into a 2-tuple
  230. \code{(\var{host}, \var{port})}.
  231. Depending on the settings of \var{flags}, the result can contain a
  232. fully-qualified domain name or numeric address representation in
  233. \var{host}. Similarly, \var{port} can contain a string port name or a
  234. numeric port number.
  235. \versionadded{2.2}
  236. \end{funcdesc}
  237. \begin{funcdesc}{getprotobyname}{protocolname}
  238. Translate an Internet protocol name (for example, \code{'icmp'}) to a constant
  239. suitable for passing as the (optional) third argument to the
  240. \function{socket()} function. This is usually only needed for sockets
  241. opened in ``raw'' mode (\constant{SOCK_RAW}); for the normal socket
  242. modes, the correct protocol is chosen automatically if the protocol is
  243. omitted or zero.
  244. \end{funcdesc}
  245. \begin{funcdesc}{getservbyname}{servicename\optional{, protocolname}}
  246. Translate an Internet service name and protocol name to a port number
  247. for that service. The optional protocol name, if given, should be
  248. \code{'tcp'} or \code{'udp'}, otherwise any protocol will match.
  249. \end{funcdesc}
  250. \begin{funcdesc}{getservbyport}{port\optional{, protocolname}}
  251. Translate an Internet port number and protocol name to a service name
  252. for that service. The optional protocol name, if given, should be
  253. \code{'tcp'} or \code{'udp'}, otherwise any protocol will match.
  254. \end{funcdesc}
  255. \begin{funcdesc}{socket}{\optional{family\optional{,
  256. type\optional{, proto}}}}
  257. Create a new socket using the given address family, socket type and
  258. protocol number. The address family should be \constant{AF_INET} (the
  259. default), \constant{AF_INET6} or \constant{AF_UNIX}. The socket type
  260. should be \constant{SOCK_STREAM} (the default), \constant{SOCK_DGRAM}
  261. or perhaps one of the other \samp{SOCK_} constants. The protocol
  262. number is usually zero and may be omitted in that case.
  263. \end{funcdesc}
  264. \begin{funcdesc}{ssl}{sock\optional{, keyfile, certfile}}
  265. Initiate a SSL connection over the socket \var{sock}. \var{keyfile} is
  266. the name of a PEM formatted file that contains your private
  267. key. \var{certfile} is a PEM formatted certificate chain file. On
  268. success, a new \class{SSLObject} is returned.
  269. \warning{This does not do any certificate verification!}
  270. \end{funcdesc}
  271. \begin{funcdesc}{socketpair}{\optional{family\optional{, type\optional{, proto}}}}
  272. Build a pair of connected socket objects using the given address
  273. family, socket type, and protocol number. Address family, socket type,
  274. and protocol number are as for the \function{socket()} function above.
  275. The default family is \constant{AF_UNIX} if defined on the platform;
  276. otherwise, the default is \constant{AF_INET}.
  277. Availability: \UNIX. \versionadded{2.4}
  278. \end{funcdesc}
  279. \begin{funcdesc}{fromfd}{fd, family, type\optional{, proto}}
  280. Duplicate the file descriptor \var{fd} (an integer as returned by a file
  281. object's \method{fileno()} method) and build a socket object from the
  282. result. Address family, socket type and protocol number are as for the
  283. \function{socket()} function above.
  284. The file descriptor should refer to a socket, but this is not
  285. checked --- subsequent operations on the object may fail if the file
  286. descriptor is invalid. This function is rarely needed, but can be
  287. used to get or set socket options on a socket passed to a program as
  288. standard input or output (such as a server started by the \UNIX{} inet
  289. daemon). The socket is assumed to be in blocking mode.
  290. Availability: \UNIX.
  291. \end{funcdesc}
  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.
  296. \end{funcdesc}
  297. \begin{funcdesc}{ntohs}{x}
  298. Convert 16-bit integers from network to host byte order. On machines
  299. where the host byte order is the same as network byte order, this is a
  300. no-op; otherwise, it performs a 2-byte swap operation.
  301. \end{funcdesc}
  302. \begin{funcdesc}{htonl}{x}
  303. Convert 32-bit integers from host to network byte order. On machines
  304. where the host byte order is the same as network byte order, this is a
  305. no-op; otherwise, it performs a 4-byte swap operation.
  306. \end{funcdesc}
  307. \begin{funcdesc}{htons}{x}
  308. Convert 16-bit integers from host to network byte order. On machines
  309. where the host byte order is the same as network byte order, this is a
  310. no-op; otherwise, it performs a 2-byte swap operation.
  311. \end{funcdesc}
  312. \begin{funcdesc}{inet_aton}{ip_string}
  313. Convert an IPv4 address from dotted-quad string format (for example,
  314. '123.45.67.89') to 32-bit packed binary format, as a string four
  315. characters in length. This is useful when conversing with a program
  316. that uses the standard C library and needs objects of type
  317. \ctype{struct in_addr}, which is the C type for the 32-bit packed
  318. binary this function returns.
  319. If the IPv4 address string passed to this function is invalid,
  320. \exception{socket.error} will be raised. Note that exactly what is
  321. valid depends on the underlying C implementation of
  322. \cfunction{inet_aton()}.
  323. \function{inet_aton()} does not support IPv6, and
  324. \function{getnameinfo()} should be used instead for IPv4/v6 dual stack
  325. support.
  326. \end{funcdesc}
  327. \begin{funcdesc}{inet_ntoa}{packed_ip}
  328. Convert a 32-bit packed IPv4 address (a string four characters in
  329. length) to its standard dotted-quad string representation (for
  330. example, '123.45.67.89'). This is useful when conversing with a
  331. program that uses the standard C library and needs objects of type
  332. \ctype{struct in_addr}, which is the C type for the 32-bit packed
  333. binary data this function takes as an argument.
  334. If the string passed to this function is not exactly 4 bytes in
  335. length, \exception{socket.error} will be raised.
  336. \function{inet_ntoa()} does not support IPv6, and
  337. \function{getnameinfo()} should be used instead for IPv4/v6 dual stack
  338. support.
  339. \end{funcdesc}
  340. \begin{funcdesc}{inet_pton}{address_family, ip_string}
  341. Convert an IP address from its family-specific string format to a packed,
  342. binary format.
  343. \function{inet_pton()} is useful when a library or network protocol calls for
  344. an object of type \ctype{struct in_addr} (similar to \function{inet_aton()})
  345. or \ctype{struct in6_addr}.
  346. Supported values for \var{address_family} are currently
  347. \constant{AF_INET} and \constant{AF_INET6}.
  348. If the IP address string \var{ip_string} is invalid,
  349. \exception{socket.error} will be raised. Note that exactly what is valid
  350. depends on both the value of \var{address_family} and the underlying
  351. implementation of \cfunction{inet_pton()}.
  352. Availability: \UNIX{} (maybe not all platforms).
  353. \versionadded{2.3}
  354. \end{funcdesc}
  355. \begin{funcdesc}{inet_ntop}{address_family, packed_ip}
  356. Convert a packed IP address (a string of some number of characters) to
  357. its standard, family-specific string representation (for example,
  358. \code{'7.10.0.5'} or \code{'5aef:2b::8'})
  359. \function{inet_ntop()} is useful when a library or network protocol returns
  360. an object of type \ctype{struct in_addr} (similar to \function{inet_ntoa()})
  361. or \ctype{struct in6_addr}.
  362. Supported values for \var{address_family} are currently
  363. \constant{AF_INET} and \constant{AF_INET6}.
  364. If the string \var{packed_ip} is not the correct length for the
  365. specified address family, \exception{ValueError} will be raised. A
  366. \exception{socket.error} is raised for errors from the call to
  367. \function{inet_ntop()}.
  368. Availability: \UNIX{} (maybe not all platforms).
  369. \versionadded{2.3}
  370. \end{funcdesc}
  371. \begin{funcdesc}{getdefaulttimeout}{}
  372. Return the default timeout in floating seconds for new socket objects.
  373. A value of \code{None} indicates that new socket objects have no timeout.
  374. When the socket module is first imported, the default is \code{None}.
  375. \versionadded{2.3}
  376. \end{funcdesc}
  377. \begin{funcdesc}{setdefaulttimeout}{timeout}
  378. Set the default timeout in floating seconds for new socket objects.
  379. A value of \code{None} indicates that new socket objects have no timeout.
  380. When the socket module is first imported, the default is \code{None}.
  381. \versionadded{2.3}
  382. \end{funcdesc}
  383. \begin{datadesc}{SocketType}
  384. This is a Python type object that represents the socket object type.
  385. It is the same as \code{type(socket(...))}.
  386. \end{datadesc}
  387. \begin{seealso}
  388. \seemodule{SocketServer}{Classes that simplify writing network servers.}
  389. \end{seealso}
  390. \subsection{Socket Objects \label{socket-objects}}
  391. Socket objects have the following methods. Except for
  392. \method{makefile()} these correspond to \UNIX{} system calls
  393. applicable to sockets.
  394. \begin{methoddesc}[socket]{accept}{}
  395. Accept a connection.
  396. The socket must be bound to an address and listening for connections.
  397. The return value is a pair \code{(\var{conn}, \var{address})}
  398. where \var{conn} is a \emph{new} socket object usable to send and
  399. receive data on the connection, and \var{address} is the address bound
  400. to the socket on the other end of the connection.
  401. \end{methoddesc}
  402. \begin{methoddesc}[socket]{bind}{address}
  403. Bind the socket to \var{address}. The socket must not already be bound.
  404. (The format of \var{address} depends on the address family --- see
  405. above.) \note{This method has historically accepted a pair
  406. of parameters for \constant{AF_INET} addresses instead of only a
  407. tuple. This was never intentional and is no longer available in
  408. Python 2.0 and later.}
  409. \end{methoddesc}
  410. \begin{methoddesc}[socket]{close}{}
  411. Close the socket. All future operations on the socket object will fail.
  412. The remote end will receive no more data (after queued data is flushed).
  413. Sockets are automatically closed when they are garbage-collected.
  414. \end{methoddesc}
  415. \begin{methoddesc}[socket]{connect}{address}
  416. Connect to a remote socket at \var{address}.
  417. (The format of \var{address} depends on the address family --- see
  418. above.) \note{This method has historically accepted a pair
  419. of parameters for \constant{AF_INET} addresses instead of only a
  420. tuple. This was never intentional and is no longer available in
  421. Python 2.0 and later.}
  422. \end{methoddesc}
  423. \begin{methoddesc}[socket]{connect_ex}{address}
  424. Like \code{connect(\var{address})}, but return an error indicator
  425. instead of raising an exception for errors returned by the C-level
  426. \cfunction{connect()} call (other problems, such as ``host not found,''
  427. can still raise exceptions). The error indicator is \code{0} if the
  428. operation succeeded, otherwise the value of the \cdata{errno}
  429. variable. This is useful to support, for example, asynchronous connects.
  430. \note{This method has historically accepted a pair of
  431. parameters for \constant{AF_INET} addresses instead of only a tuple.
  432. This was never intentional and is no longer available in Python
  433. 2.0 and later.}
  434. \end{methoddesc}
  435. \begin{methoddesc}[socket]{fileno}{}
  436. Return the socket's file descriptor (a small integer). This is useful
  437. with \function{select.select()}.
  438. Under Windows the small integer returned by this method cannot be used where
  439. a file descriptor can be used (such as \function{os.fdopen()}). \UNIX{} does
  440. not have this limitation.
  441. \end{methoddesc}
  442. \begin{methoddesc}[socket]{getpeername}{}
  443. Return the remote address to which the socket is connected. This is
  444. useful to find out the port number of a remote IPv4/v6 socket, for instance.
  445. (The format of the address returned depends on the address family ---
  446. see above.) On some systems this function is not supported.
  447. \end{methoddesc}
  448. \begin{methoddesc}[socket]{getsockname}{}
  449. Return the socket's own address. This is useful to find out the port
  450. number of an IPv4/v6 socket, for instance.
  451. (The format of the address returned depends on the address family ---
  452. see above.)
  453. \end{methoddesc}
  454. \begin{methoddesc}[socket]{getsockopt}{level, optname\optional{, buflen}}
  455. Return the value of the given socket option (see the \UNIX{} man page
  456. \manpage{getsockopt}{2}). The needed symbolic constants
  457. (\constant{SO_*} etc.) are defined in this module. If \var{buflen}
  458. is absent, an integer option is assumed and its integer value
  459. is returned by the function. If \var{buflen} is present, it specifies
  460. the maximum length of the buffer used to receive the option in, and
  461. this buffer is returned as a string. It is up to the caller to decode
  462. the contents of the buffer (see the optional built-in module
  463. \refmodule{struct} for a way to decode C structures encoded as strings).
  464. \end{methoddesc}
  465. \begin{methoddesc}[socket]{listen}{backlog}
  466. Listen for connections made to the socket. The \var{backlog} argument
  467. specifies the maximum number of queued connections and should be at
  468. least 1; the maximum value is system-dependent (usually 5).
  469. \end{methoddesc}
  470. \begin{methoddesc}[socket]{makefile}{\optional{mode\optional{, bufsize}}}
  471. Return a \dfn{file object} associated with the socket. (File objects
  472. are described in \ref{bltin-file-objects}, ``File Objects.'')
  473. The file object references a \cfunction{dup()}ped version of the
  474. socket file descriptor, so the file object and socket object may be
  475. closed or garbage-collected independently.
  476. The socket must be in blocking mode.
  477. \index{I/O control!buffering}The optional \var{mode}
  478. and \var{bufsize} arguments are interpreted the same way as by the
  479. built-in \function{file()} function; see ``Built-in Functions''
  480. (section \ref{built-in-funcs}) for more information.
  481. \end{methoddesc}
  482. \begin{methoddesc}[socket]{recv}{bufsize\optional{, flags}}
  483. Receive data from the socket. The return value is a string representing
  484. the data received. The maximum amount of data to be received
  485. at once is specified by \var{bufsize}. See the \UNIX{} manual page
  486. \manpage{recv}{2} for the meaning of the optional argument
  487. \var{flags}; it defaults to zero.
  488. \note{For best match with hardware and network realities, the value of
  489. \var{bufsize} should be a relatively small power of 2, for example, 4096.}
  490. \end{methoddesc}
  491. \begin{methoddesc}[socket]{recvfrom}{bufsize\optional{, flags}}
  492. Receive data from the socket. The return value is a pair
  493. \code{(\var{string}, \var{address})} where \var{string} is a string
  494. representing the data received and \var{address} is the address of the
  495. socket sending the data. The optional \var{flags} argument has the
  496. same meaning as for \method{recv()} above.
  497. (The format of \var{address} depends on the address family --- see above.)
  498. \end{methoddesc}
  499. \begin{methoddesc}[socket]{recvfrom_into}{buffer\optional{, nbytes\optional{, flags}}}
  500. Receive data from the socket, writing it into \var{buffer} instead of
  501. creating a new string. The return value is a pair
  502. \code{(\var{nbytes}, \var{address})} where \var{nbytes} is the number
  503. of bytes received and \var{address} is the address of the socket
  504. sending the data. See the \UNIX{} manual page
  505. \manpage{recv}{2} for the meaning of the optional argument
  506. \var{flags}; it defaults to zero. (The format of \var{address}
  507. depends on the address family --- see above.)
  508. \versionadded{2.5}
  509. \end{methoddesc}
  510. \begin{methoddesc}[socket]{recv_into}{buffer\optional{, nbytes\optional{, flags}}}
  511. Receive up to \var{nbytes} bytes from the socket,
  512. storing the data into a buffer rather than creating a new string.
  513. If \var{nbytes} is not specified (or 0),
  514. receive up to the size available in the given buffer.
  515. See the \UNIX{} manual page \manpage{recv}{2} for the meaning of the
  516. optional argument \var{flags}; it defaults to zero.
  517. \versionadded{2.5}
  518. \end{methoddesc}
  519. \begin{methoddesc}[socket]{send}{string\optional{, flags}}
  520. Send data to the socket. The socket must be connected to a remote
  521. socket. The optional \var{flags} argument has the same meaning as for
  522. \method{recv()} above. Returns the number of bytes sent.
  523. Applications are responsible for checking that all data has been sent;
  524. if only some of the data was transmitted, the application needs to
  525. attempt delivery of the remaining data.
  526. \end{methoddesc}
  527. \begin{methoddesc}[socket]{sendall}{string\optional{, flags}}
  528. Send data to the socket. The socket must be connected to a remote
  529. socket. The optional \var{flags} argument has the same meaning as for
  530. \method{recv()} above. Unlike \method{send()}, this method continues
  531. to send data from \var{string} until either all data has been sent or
  532. an error occurs. \code{None} is returned on success. On error, an
  533. exception is raised, and there is no way to determine how much data,
  534. if any, was successfully sent.
  535. \end{methoddesc}
  536. \begin{methoddesc}[socket]{sendto}{string\optional{, flags}, address}
  537. Send data to the socket. The socket should not be connected to a
  538. remote socket, since the destination socket is specified by
  539. \var{address}. The optional \var{flags} argument has the same
  540. meaning as for \method{recv()} above. Return the number of bytes sent.
  541. (The format of \var{address} depends on the address family --- see above.)
  542. \end{methoddesc}
  543. \begin{methoddesc}[socket]{setblocking}{flag}
  544. Set blocking or non-blocking mode of the socket: if \var{flag} is 0,
  545. the socket is set to non-blocking, else to blocking mode. Initially
  546. all sockets are in blocking mode. In non-blocking mode, if a
  547. \method{recv()} call doesn't find any data, or if a
  548. \method{send()} call can't immediately dispose of the data, a
  549. \exception{error} exception is raised; in blocking mode, the calls
  550. block until they can proceed.
  551. \code{s.setblocking(0)} is equivalent to \code{s.settimeout(0)};
  552. \code{s.setblocking(1)} is equivalent to \code{s.settimeout(None)}.
  553. \end{methoddesc}
  554. \begin{methoddesc}[socket]{settimeout}{value}
  555. Set a timeout on blocking socket operations. The \var{value} argument
  556. can be a nonnegative float expressing seconds, or \code{None}.
  557. If a float is
  558. given, subsequent socket operations will raise an \exception{timeout}
  559. exception if the timeout period \var{value} has elapsed before the
  560. operation has completed. Setting a timeout of \code{None} disables
  561. timeouts on socket operations.
  562. \code{s.settimeout(0.0)} is equivalent to \code{s.setblocking(0)};
  563. \code{s.settimeout(None)} is equivalent to \code{s.setblocking(1)}.
  564. \versionadded{2.3}
  565. \end{methoddesc}
  566. \begin{methoddesc}[socket]{gettimeout}{}
  567. Return the timeout in floating seconds associated with socket
  568. operations, or \code{None} if no timeout is set. This reflects
  569. the last call to \method{setblocking()} or \method{settimeout()}.
  570. \versionadded{2.3}
  571. \end{methoddesc}
  572. Some notes on socket blocking and timeouts: A socket object can be in
  573. one of three modes: blocking, non-blocking, or timeout. Sockets are
  574. always created in blocking mode. In blocking mode, operations block
  575. until complete. In non-blocking mode, operations fail (with an error
  576. that is unfortunately system-dependent) if they cannot be completed
  577. immediately. In timeout mode, operations fail if they cannot be
  578. completed within the timeout specified for the socket. The
  579. \method{setblocking()} method is simply a shorthand for certain
  580. \method{settimeout()} calls.
  581. Timeout mode internally sets the socket in non-blocking mode. The
  582. blocking and timeout modes are shared between file descriptors and
  583. socket objects that refer to the same network endpoint. A consequence
  584. of this is that file objects returned by the \method{makefile()}
  585. method must only be used when the socket is in blocking mode; in
  586. timeout or non-blocking mode file operations that cannot be completed
  587. immediately will fail.
  588. Note that the \method{connect()} operation is subject to the timeout
  589. setting, and in general it is recommended to call
  590. \method{settimeout()} before calling \method{connect()}.
  591. \begin{methoddesc}[socket]{setsockopt}{level, optname, value}
  592. Set the value of the given socket option (see the \UNIX{} manual page
  593. \manpage{setsockopt}{2}). The needed symbolic constants are defined in
  594. the \module{socket} module (\constant{SO_*} etc.). The value can be an
  595. integer or a string representing a buffer. In the latter case it is
  596. up to the caller to ensure that the string contains the proper bits
  597. (see the optional built-in module
  598. \refmodule{struct}\refbimodindex{struct} for a way to encode C
  599. structures as strings).
  600. \end{methoddesc}
  601. \begin{methoddesc}[socket]{shutdown}{how}
  602. Shut down one or both halves of the connection. If \var{how} is
  603. \constant{SHUT_RD}, further receives are disallowed. If \var{how} is \constant{SHUT_WR},
  604. further sends are disallowed. If \var{how} is \constant{SHUT_RDWR}, further sends
  605. and receives are disallowed.
  606. \end{methoddesc}
  607. Note that there are no methods \method{read()} or \method{write()};
  608. use \method{recv()} and \method{send()} without \var{flags} argument
  609. instead.
  610. Socket objects also have these (read-only) attributes that correspond
  611. to the values given to the \class{socket} constructor.
  612. \begin{memberdesc}[socket]{family}
  613. The socket family.
  614. \versionadded{2.5}
  615. \end{memberdesc}
  616. \begin{memberdesc}[socket]{type}
  617. The socket type.
  618. \versionadded{2.5}
  619. \end{memberdesc}
  620. \begin{memberdesc}[socket]{proto}
  621. The socket protocol.
  622. \versionadded{2.5}
  623. \end{memberdesc}
  624. \subsection{SSL Objects \label{ssl-objects}}
  625. SSL objects have the following methods.
  626. \begin{methoddesc}{write}{s}
  627. Writes the string \var{s} to the on the object's SSL connection.
  628. The return value is the number of bytes written.
  629. \end{methoddesc}
  630. \begin{methoddesc}{read}{\optional{n}}
  631. If \var{n} is provided, read \var{n} bytes from the SSL connection, otherwise
  632. read until EOF. The return value is a string of the bytes read.
  633. \end{methoddesc}
  634. \begin{methoddesc}{server}{}
  635. Returns a string describing the server's certificate.
  636. Useful for debugging purposes; do not parse the content of this string
  637. because its format can't be parsed unambiguously.
  638. \end{methoddesc}
  639. \begin{methoddesc}{issuer}{}
  640. Returns a string describing the issuer of the server's certificate.
  641. Useful for debugging purposes; do not parse the content of this string
  642. because its format can't be parsed unambiguously.
  643. \end{methoddesc}
  644. \subsection{Example \label{socket-example}}
  645. Here are four minimal example programs using the TCP/IP protocol:\ a
  646. server that echoes all data that it receives back (servicing only one
  647. client), and a client using it. Note that a server must perform the
  648. sequence \function{socket()}, \method{bind()}, \method{listen()},
  649. \method{accept()} (possibly repeating the \method{accept()} to service
  650. more than one client), while a client only needs the sequence
  651. \function{socket()}, \method{connect()}. Also note that the server
  652. does not \method{send()}/\method{recv()} on the
  653. socket it is listening on but on the new socket returned by
  654. \method{accept()}.
  655. The first two examples support IPv4 only.
  656. \begin{verbatim}
  657. # Echo server program
  658. import socket
  659. HOST = '' # Symbolic name meaning the local host
  660. PORT = 50007 # Arbitrary non-privileged port
  661. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  662. s.bind((HOST, PORT))
  663. s.listen(1)
  664. conn, addr = s.accept()
  665. print 'Connected by', addr
  666. while 1:
  667. data = conn.recv(1024)
  668. if not data: break
  669. conn.send(data)
  670. conn.close()
  671. \end{verbatim}
  672. \begin{verbatim}
  673. # Echo client program
  674. import socket
  675. HOST = 'daring.cwi.nl' # The remote host
  676. PORT = 50007 # The same port as used by the server
  677. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  678. s.connect((HOST, PORT))
  679. s.send('Hello, world')
  680. data = s.recv(1024)
  681. s.close()
  682. print 'Received', repr(data)
  683. \end{verbatim}
  684. The next two examples are identical to the above two, but support both
  685. IPv4 and IPv6.
  686. The server side will listen to the first address family available
  687. (it should listen to both instead).
  688. On most of IPv6-ready systems, IPv6 will take precedence
  689. and the server may not accept IPv4 traffic.
  690. The client side will try to connect to the all addresses returned as a result
  691. of the name resolution, and sends traffic to the first one connected
  692. successfully.
  693. \begin{verbatim}
  694. # Echo server program
  695. import socket
  696. import sys
  697. HOST = '' # Symbolic name meaning the local host
  698. PORT = 50007 # Arbitrary non-privileged port
  699. s = None
  700. for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
  701. af, socktype, proto, canonname, sa = res
  702. try:
  703. s = socket.socket(af, socktype, proto)
  704. except socket.error, msg:
  705. s = None
  706. continue
  707. try:
  708. s.bind(sa)
  709. s.listen(1)
  710. except socket.error, msg:
  711. s.close()
  712. s = None
  713. continue
  714. break
  715. if s is None:
  716. print 'could not open socket'
  717. sys.exit(1)
  718. conn, addr = s.accept()
  719. print 'Connected by', addr
  720. while 1:
  721. data = conn.recv(1024)
  722. if not data: break
  723. conn.send(data)
  724. conn.close()
  725. \end{verbatim}
  726. \begin{verbatim}
  727. # Echo client program
  728. import socket
  729. import sys
  730. HOST = 'daring.cwi.nl' # The remote host
  731. PORT = 50007 # The same port as used by the server
  732. s = None
  733. for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM):
  734. af, socktype, proto, canonname, sa = res
  735. try:
  736. s = socket.socket(af, socktype, proto)
  737. except socket.error, msg:
  738. s = None
  739. continue
  740. try:
  741. s.connect(sa)
  742. except socket.error, msg:
  743. s.close()
  744. s = None
  745. continue
  746. break
  747. if s is None:
  748. print 'could not open socket'
  749. sys.exit(1)
  750. s.send('Hello, world')
  751. data = s.recv(1024)
  752. s.close()
  753. print 'Received', repr(data)
  754. \end{verbatim}
  755. This example connects to an SSL server, prints the
  756. server and issuer's distinguished names, sends some bytes,
  757. and reads part of the response:
  758. \begin{verbatim}
  759. import socket
  760. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  761. s.connect(('www.verisign.com', 443))
  762. ssl_sock = socket.ssl(s)
  763. print repr(ssl_sock.server())
  764. print repr(ssl_sock.issuer())
  765. # Set a simple HTTP request -- use httplib in actual code.
  766. ssl_sock.write("""GET / HTTP/1.0\r
  767. Host: www.verisign.com\r\n\r\n""")
  768. # Read a chunk of data. Will not necessarily
  769. # read all the data returned by the server.
  770. data = ssl_sock.read()
  771. # Note that you need to close the underlying socket, not the SSL object.
  772. del ssl_sock
  773. s.close()
  774. \end{verbatim}
  775. At this writing, this SSL example prints the following output (line
  776. breaks inserted for readability):
  777. \begin{verbatim}
  778. '/C=US/ST=California/L=Mountain View/
  779. O=VeriSign, Inc./OU=Production Services/
  780. OU=Terms of use at www.verisign.com/rpa (c)00/
  781. CN=www.verisign.com'
  782. '/O=VeriSign Trust Network/OU=VeriSign, Inc./
  783. OU=VeriSign International Server CA - Class 3/
  784. OU=www.verisign.com/CPS Incorp.by Ref. LIABILITY LTD.(c)97 VeriSign'
  785. \end{verbatim}