PageRenderTime 50ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/Doc/library/socket.rst

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