PageRenderTime 51ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/Doc/library/socket.rst

https://bitbucket.org/rmtew/cpython-stackless2
ReStructuredText | 1276 lines | 894 code | 382 blank | 0 comment | 0 complexity | 0001ef5968351fb2b036d4c0c327eb9c MD5 | raw file
Possible License(s): BSD-3-Clause, 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, MacOS, 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. .. index:: object: socket
  12. The Python interface is a straightforward transliteration of the Unix system
  13. call and library interface for sockets to Python's object-oriented style: the
  14. :func:`socket` function returns a :dfn:`socket object` whose methods implement
  15. the various socket system calls. Parameter types are somewhat higher-level than
  16. in the C interface: as with :meth:`read` and :meth:`write` operations on Python
  17. files, buffer allocation on receive operations is automatic, and buffer length
  18. is implicit on send operations.
  19. .. seealso::
  20. Module :mod:`socketserver`
  21. Classes that simplify writing network servers.
  22. Module :mod:`ssl`
  23. A TLS/SSL wrapper for socket objects.
  24. Socket families
  25. ---------------
  26. Depending on the system and the build options, various socket families
  27. are supported by this module.
  28. Socket addresses are represented as follows:
  29. - A single string is used for the :const:`AF_UNIX` address family.
  30. - A pair ``(host, port)`` is used for the :const:`AF_INET` address family,
  31. where *host* is a string representing either a hostname in Internet domain
  32. notation like ``'daring.cwi.nl'`` or an IPv4 address like ``'100.50.200.5'``,
  33. and *port* is an integral port number.
  34. - For :const:`AF_INET6` address family, a four-tuple ``(host, port, flowinfo,
  35. scopeid)`` is used, where *flowinfo* and *scopeid* represent the ``sin6_flowinfo``
  36. and ``sin6_scope_id`` members in :const:`struct sockaddr_in6` in C. For
  37. :mod:`socket` module methods, *flowinfo* and *scopeid* can be omitted just for
  38. backward compatibility. Note, however, omission of *scopeid* can cause problems
  39. in manipulating scoped IPv6 addresses.
  40. - :const:`AF_NETLINK` sockets are represented as pairs ``(pid, groups)``.
  41. - Linux-only support for TIPC is available using the :const:`AF_TIPC`
  42. address family. TIPC is an open, non-IP based networked protocol designed
  43. for use in clustered computer environments. Addresses are represented by a
  44. tuple, and the fields depend on the address type. The general tuple form is
  45. ``(addr_type, v1, v2, v3 [, scope])``, where:
  46. - *addr_type* is one of TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME, or
  47. TIPC_ADDR_ID.
  48. - *scope* is one of TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, and
  49. TIPC_NODE_SCOPE.
  50. - If *addr_type* is TIPC_ADDR_NAME, then *v1* is the server type, *v2* is
  51. the port identifier, and *v3* should be 0.
  52. If *addr_type* is TIPC_ADDR_NAMESEQ, then *v1* is the server type, *v2*
  53. is the lower port number, and *v3* is the upper port number.
  54. If *addr_type* is TIPC_ADDR_ID, then *v1* is the node, *v2* is the
  55. reference, and *v3* should be set to 0.
  56. If *addr_type* is TIPC_ADDR_ID, then *v1* is the node, *v2* is the
  57. reference, and *v3* should be set to 0.
  58. - Certain other address families (:const:`AF_BLUETOOTH`, :const:`AF_PACKET`)
  59. support specific representations.
  60. .. XXX document them!
  61. For IPv4 addresses, two special forms are accepted instead of a host address:
  62. the empty string represents :const:`INADDR_ANY`, and the string
  63. ``'<broadcast>'`` represents :const:`INADDR_BROADCAST`. This behavior is not
  64. compatible with IPv6, therefore, you may want to avoid these if you intend
  65. to support IPv6 with your Python programs.
  66. If you use a hostname in the *host* portion of IPv4/v6 socket address, the
  67. program may show a nondeterministic behavior, as Python uses the first address
  68. returned from the DNS resolution. The socket address will be resolved
  69. differently into an actual IPv4/v6 address, depending on the results from DNS
  70. resolution and/or the host configuration. For deterministic behavior use a
  71. numeric address in *host* portion.
  72. All errors raise exceptions. The normal exceptions for invalid argument types
  73. and out-of-memory conditions can be raised; errors related to socket or address
  74. semantics raise :exc:`socket.error` or one of its subclasses.
  75. Non-blocking mode is supported through :meth:`~socket.setblocking`. A
  76. generalization of this based on timeouts is supported through
  77. :meth:`~socket.settimeout`.
  78. Module contents
  79. ---------------
  80. The module :mod:`socket` exports the following constants and functions:
  81. .. exception:: error
  82. .. index:: module: errno
  83. A subclass of :exc:`IOError`, this exception is raised for socket-related
  84. errors. It is recommended that you inspect its ``errno`` attribute to
  85. discriminate between different kinds of errors.
  86. .. seealso::
  87. The :mod:`errno` module contains symbolic names for the error codes
  88. defined by the underlying operating system.
  89. .. exception:: herror
  90. A subclass of :exc:`socket.error`, this exception is raised for
  91. address-related errors, i.e. for functions that use *h_errno* in the POSIX
  92. C API, including :func:`gethostbyname_ex` and :func:`gethostbyaddr`.
  93. The accompanying value is a pair ``(h_errno, string)`` representing an
  94. error returned by a library call. *h_errno* is a numeric value, while
  95. *string* represents the description of *h_errno*, as returned by the
  96. :c:func:`hstrerror` C function.
  97. .. exception:: gaierror
  98. A subclass of :exc:`socket.error`, this exception is raised for
  99. address-related errors by :func:`getaddrinfo` and :func:`getnameinfo`.
  100. The accompanying value is a pair ``(error, string)`` representing an error
  101. returned by a library call. *string* represents the description of
  102. *error*, as returned by the :c:func:`gai_strerror` C function. The
  103. numeric *error* value will match one of the :const:`EAI_\*` constants
  104. defined in this module.
  105. .. exception:: timeout
  106. A subclass of :exc:`socket.error`, this exception is raised when a timeout
  107. occurs on a socket which has had timeouts enabled via a prior call to
  108. :meth:`~socket.settimeout` (or implicitly through
  109. :func:`~socket.setdefaulttimeout`). The accompanying value is a string
  110. whose value is currently always "timed out".
  111. .. data:: AF_UNIX
  112. AF_INET
  113. AF_INET6
  114. These constants represent the address (and protocol) families, used for the
  115. first argument to :func:`socket`. If the :const:`AF_UNIX` constant is not
  116. defined then this protocol is unsupported. More constants may be available
  117. depending on the system.
  118. .. data:: SOCK_STREAM
  119. SOCK_DGRAM
  120. SOCK_RAW
  121. SOCK_RDM
  122. SOCK_SEQPACKET
  123. These constants represent the socket types, used for the second argument to
  124. :func:`socket`. More constants may be available depending on the system.
  125. (Only :const:`SOCK_STREAM` and :const:`SOCK_DGRAM` appear to be generally
  126. useful.)
  127. .. data:: SOCK_CLOEXEC
  128. SOCK_NONBLOCK
  129. These two constants, if defined, can be combined with the socket types and
  130. allow you to set some flags atomically (thus avoiding possible race
  131. conditions and the need for separate calls).
  132. .. seealso::
  133. `Secure File Descriptor Handling <http://udrepper.livejournal.com/20407.html>`_
  134. for a more thorough explanation.
  135. Availability: Linux >= 2.6.27.
  136. .. versionadded:: 3.2
  137. .. data:: SO_*
  138. SOMAXCONN
  139. MSG_*
  140. SOL_*
  141. SCM_*
  142. IPPROTO_*
  143. IPPORT_*
  144. INADDR_*
  145. IP_*
  146. IPV6_*
  147. EAI_*
  148. AI_*
  149. NI_*
  150. TCP_*
  151. Many constants of these forms, documented in the Unix documentation on sockets
  152. and/or the IP protocol, are also defined in the socket module. They are
  153. generally used in arguments to the :meth:`setsockopt` and :meth:`getsockopt`
  154. methods of socket objects. In most cases, only those symbols that are defined
  155. in the Unix header files are defined; for a few symbols, default values are
  156. provided.
  157. .. data:: SIO_*
  158. RCVALL_*
  159. Constants for Windows' WSAIoctl(). The constants are used as arguments to the
  160. :meth:`ioctl` method of socket objects.
  161. .. data:: TIPC_*
  162. TIPC related constants, matching the ones exported by the C socket API. See
  163. the TIPC documentation for more information.
  164. .. data:: has_ipv6
  165. This constant contains a boolean value which indicates if IPv6 is supported on
  166. this platform.
  167. .. function:: create_connection(address[, timeout[, source_address]])
  168. Convenience function. Connect to *address* (a 2-tuple ``(host, port)``),
  169. and return the socket object. Passing the optional *timeout* parameter will
  170. set the timeout on the socket instance before attempting to connect. If no
  171. *timeout* is supplied, the global default timeout setting returned by
  172. :func:`getdefaulttimeout` is used.
  173. If supplied, *source_address* must be a 2-tuple ``(host, port)`` for the
  174. socket to bind to as its source address before connecting. If host or port
  175. are '' or 0 respectively the OS default behavior will be used.
  176. .. versionchanged:: 3.2
  177. *source_address* was added.
  178. .. versionchanged:: 3.2
  179. support for the :keyword:`with` statement was added.
  180. .. function:: getaddrinfo(host, port, family=0, type=0, proto=0, flags=0)
  181. Translate the *host*/*port* argument into a sequence of 5-tuples that contain
  182. all the necessary arguments for creating a socket connected to that service.
  183. *host* is a domain name, a string representation of an IPv4/v6 address
  184. or ``None``. *port* is a string service name such as ``'http'``, a numeric
  185. port number or ``None``. By passing ``None`` as the value of *host*
  186. and *port*, you can pass ``NULL`` to the underlying C API.
  187. The *family*, *type* and *proto* arguments can be optionally specified
  188. in order to narrow the list of addresses returned. Passing zero as a
  189. value for each of these arguments selects the full range of results.
  190. The *flags* argument can be one or several of the ``AI_*`` constants,
  191. and will influence how results are computed and returned.
  192. For example, :const:`AI_NUMERICHOST` will disable domain name resolution
  193. and will raise an error if *host* is a domain name.
  194. The function returns a list of 5-tuples with the following structure:
  195. ``(family, type, proto, canonname, sockaddr)``
  196. In these tuples, *family*, *type*, *proto* are all integers and are
  197. meant to be passed to the :func:`socket` function. *canonname* will be
  198. a string representing the canonical name of the *host* if
  199. :const:`AI_CANONNAME` is part of the *flags* argument; else *canonname*
  200. will be empty. *sockaddr* is a tuple describing a socket address, whose
  201. format depends on the returned *family* (a ``(address, port)`` 2-tuple for
  202. :const:`AF_INET`, a ``(address, port, flow info, scope id)`` 4-tuple for
  203. :const:`AF_INET6`), and is meant to be passed to the :meth:`socket.connect`
  204. method.
  205. The following example fetches address information for a hypothetical TCP
  206. connection to ``www.python.org`` on port 80 (results may differ on your
  207. system if IPv6 isn't enabled)::
  208. >>> socket.getaddrinfo("www.python.org", 80, proto=socket.SOL_TCP)
  209. [(2, 1, 6, '', ('82.94.164.162', 80)),
  210. (10, 1, 6, '', ('2001:888:2000:d::a2', 80, 0, 0))]
  211. .. versionchanged:: 3.2
  212. parameters can now be passed as single keyword arguments.
  213. .. function:: getfqdn([name])
  214. Return a fully qualified domain name for *name*. If *name* is omitted or empty,
  215. it is interpreted as the local host. To find the fully qualified name, the
  216. hostname returned by :func:`gethostbyaddr` is checked, followed by aliases for the
  217. host, if available. The first name which includes a period is selected. In
  218. case no fully qualified domain name is available, the hostname as returned by
  219. :func:`gethostname` is returned.
  220. .. function:: gethostbyname(hostname)
  221. Translate a host name to IPv4 address format. The IPv4 address is returned as a
  222. string, such as ``'100.50.200.5'``. If the host name is an IPv4 address itself
  223. it is returned unchanged. See :func:`gethostbyname_ex` for a more complete
  224. interface. :func:`gethostbyname` does not support IPv6 name resolution, and
  225. :func:`getaddrinfo` should be used instead for IPv4/v6 dual stack support.
  226. .. function:: gethostbyname_ex(hostname)
  227. Translate a host name to IPv4 address format, extended interface. Return a
  228. triple ``(hostname, aliaslist, ipaddrlist)`` where *hostname* is the primary
  229. host name responding to the given *ip_address*, *aliaslist* is a (possibly
  230. empty) list of alternative host names for the same address, and *ipaddrlist* is
  231. a list of IPv4 addresses for the same interface on the same host (often but not
  232. always a single address). :func:`gethostbyname_ex` does not support IPv6 name
  233. resolution, and :func:`getaddrinfo` should be used instead for IPv4/v6 dual
  234. stack support.
  235. .. function:: gethostname()
  236. Return a string containing the hostname of the machine where the Python
  237. interpreter is currently executing.
  238. If you want to know the current machine's IP address, you may want to use
  239. ``gethostbyname(gethostname())``. This operation assumes that there is a
  240. valid address-to-host mapping for the host, and the assumption does not
  241. always hold.
  242. Note: :func:`gethostname` doesn't always return the fully qualified domain
  243. name; use ``getfqdn()`` (see above).
  244. .. function:: gethostbyaddr(ip_address)
  245. Return a triple ``(hostname, aliaslist, ipaddrlist)`` where *hostname* is the
  246. primary host name responding to the given *ip_address*, *aliaslist* is a
  247. (possibly empty) list of alternative host names for the same address, and
  248. *ipaddrlist* is a list of IPv4/v6 addresses for the same interface on the same
  249. host (most likely containing only a single address). To find the fully qualified
  250. domain name, use the function :func:`getfqdn`. :func:`gethostbyaddr` supports
  251. both IPv4 and IPv6.
  252. .. function:: getnameinfo(sockaddr, flags)
  253. Translate a socket address *sockaddr* into a 2-tuple ``(host, port)``. Depending
  254. on the settings of *flags*, the result can contain a fully-qualified domain name
  255. or numeric address representation in *host*. Similarly, *port* can contain a
  256. string port name or a numeric port number.
  257. .. function:: getprotobyname(protocolname)
  258. Translate an Internet protocol name (for example, ``'icmp'``) to a constant
  259. suitable for passing as the (optional) third argument to the :func:`socket`
  260. function. This is usually only needed for sockets opened in "raw" mode
  261. (:const:`SOCK_RAW`); for the normal socket modes, the correct protocol is chosen
  262. automatically if the protocol is omitted or zero.
  263. .. function:: getservbyname(servicename[, protocolname])
  264. Translate an Internet service name and protocol name to a port number for that
  265. service. The optional protocol name, if given, should be ``'tcp'`` or
  266. ``'udp'``, otherwise any protocol will match.
  267. .. function:: getservbyport(port[, protocolname])
  268. Translate an Internet port number and protocol name to a service name for that
  269. service. The optional protocol name, if given, should be ``'tcp'`` or
  270. ``'udp'``, otherwise any protocol will match.
  271. .. function:: socket([family[, type[, proto]]])
  272. Create a new socket using the given address family, socket type and protocol
  273. number. The address family should be :const:`AF_INET` (the default),
  274. :const:`AF_INET6` or :const:`AF_UNIX`. The socket type should be
  275. :const:`SOCK_STREAM` (the default), :const:`SOCK_DGRAM` or perhaps one of the
  276. other ``SOCK_`` constants. The protocol number is usually zero and may be
  277. omitted in that case.
  278. .. function:: socketpair([family[, type[, proto]]])
  279. Build a pair of connected socket objects using the given address family, socket
  280. type, and protocol number. Address family, socket type, and protocol number are
  281. as for the :func:`socket` function above. The default family is :const:`AF_UNIX`
  282. if defined on the platform; otherwise, the default is :const:`AF_INET`.
  283. Availability: Unix.
  284. .. versionchanged:: 3.2
  285. The returned socket objects now support the whole socket API, rather
  286. than a subset.
  287. .. function:: fromfd(fd, family, type[, proto])
  288. Duplicate the file descriptor *fd* (an integer as returned by a file object's
  289. :meth:`fileno` method) and build a socket object from the result. Address
  290. family, socket type and protocol number are as for the :func:`socket` function
  291. above. The file descriptor should refer to a socket, but this is not checked ---
  292. subsequent operations on the object may fail if the file descriptor is invalid.
  293. This function is rarely needed, but can be used to get or set socket options on
  294. a socket passed to a program as standard input or output (such as a server
  295. started by the Unix inet daemon). The socket is assumed to be in blocking mode.
  296. .. function:: ntohl(x)
  297. Convert 32-bit positive integers from network to host byte order. On machines
  298. where the host byte order is the same as network byte order, this is a no-op;
  299. otherwise, it performs a 4-byte swap operation.
  300. .. function:: ntohs(x)
  301. Convert 16-bit positive integers from network to host byte order. On machines
  302. where the host byte order is the same as network byte order, this is a no-op;
  303. otherwise, it performs a 2-byte swap operation.
  304. .. function:: htonl(x)
  305. Convert 32-bit positive 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 no-op;
  307. otherwise, it performs a 4-byte swap operation.
  308. .. function:: htons(x)
  309. Convert 16-bit positive integers from host to network byte order. On machines
  310. where the host byte order is the same as network byte order, this is a no-op;
  311. otherwise, it performs a 2-byte swap operation.
  312. .. function:: 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 bytes object four characters in
  315. length. This is useful when conversing with a program that uses the standard C
  316. library and needs objects of type :c:type:`struct in_addr`, which is the C type
  317. for the 32-bit packed binary this function returns.
  318. :func:`inet_aton` also accepts strings with less than three dots; see the
  319. Unix manual page :manpage:`inet(3)` for details.
  320. If the IPv4 address string passed to this function is invalid,
  321. :exc:`socket.error` will be raised. Note that exactly what is valid depends on
  322. the underlying C implementation of :c:func:`inet_aton`.
  323. :func:`inet_aton` does not support IPv6, and :func:`inet_pton` should be used
  324. instead for IPv4/v6 dual stack support.
  325. .. function:: inet_ntoa(packed_ip)
  326. Convert a 32-bit packed IPv4 address (a bytes object four characters in
  327. length) to its standard dotted-quad string representation (for example,
  328. '123.45.67.89'). This is useful when conversing with a program that uses the
  329. standard C library and needs objects of type :c:type:`struct in_addr`, which
  330. is the C type for the 32-bit packed binary data this function takes as an
  331. argument.
  332. If the byte sequence passed to this function is not exactly 4 bytes in
  333. length, :exc:`socket.error` will be raised. :func:`inet_ntoa` does not
  334. support IPv6, and :func:`inet_ntop` should be used instead for IPv4/v6 dual
  335. stack support.
  336. .. function:: inet_pton(address_family, ip_string)
  337. Convert an IP address from its family-specific string format to a packed,
  338. binary format. :func:`inet_pton` is useful when a library or network protocol
  339. calls for an object of type :c:type:`struct in_addr` (similar to
  340. :func:`inet_aton`) or :c:type:`struct in6_addr`.
  341. Supported values for *address_family* are currently :const:`AF_INET` and
  342. :const:`AF_INET6`. If the IP address string *ip_string* is invalid,
  343. :exc:`socket.error` will be raised. Note that exactly what is valid depends on
  344. both the value of *address_family* and the underlying implementation of
  345. :c:func:`inet_pton`.
  346. Availability: Unix (maybe not all platforms).
  347. .. function:: inet_ntop(address_family, packed_ip)
  348. Convert a packed IP address (a bytes object of some number of characters) to its
  349. standard, family-specific string representation (for example, ``'7.10.0.5'`` or
  350. ``'5aef:2b::8'``). :func:`inet_ntop` is useful when a library or network protocol
  351. returns an object of type :c:type:`struct in_addr` (similar to :func:`inet_ntoa`)
  352. or :c:type:`struct in6_addr`.
  353. Supported values for *address_family* are currently :const:`AF_INET` and
  354. :const:`AF_INET6`. If the string *packed_ip* is not the correct length for the
  355. specified address family, :exc:`ValueError` will be raised. A
  356. :exc:`socket.error` is raised for errors from the call to :func:`inet_ntop`.
  357. Availability: Unix (maybe not all platforms).
  358. ..
  359. XXX: Are sendmsg(), recvmsg() and CMSG_*() available on any
  360. non-Unix platforms? The old (obsolete?) 4.2BSD form of the
  361. interface, in which struct msghdr has no msg_control or
  362. msg_controllen members, is not currently supported.
  363. .. function:: CMSG_LEN(length)
  364. Return the total length, without trailing padding, of an ancillary
  365. data item with associated data of the given *length*. This value
  366. can often be used as the buffer size for :meth:`~socket.recvmsg` to
  367. receive a single item of ancillary data, but :rfc:`3542` requires
  368. portable applications to use :func:`CMSG_SPACE` and thus include
  369. space for padding, even when the item will be the last in the
  370. buffer. Raises :exc:`OverflowError` if *length* is outside the
  371. permissible range of values.
  372. Availability: most Unix platforms, possibly others.
  373. .. versionadded:: 3.3
  374. .. function:: CMSG_SPACE(length)
  375. Return the buffer size needed for :meth:`~socket.recvmsg` to
  376. receive an ancillary data item with associated data of the given
  377. *length*, along with any trailing padding. The buffer space needed
  378. to receive multiple items is the sum of the :func:`CMSG_SPACE`
  379. values for their associated data lengths. Raises
  380. :exc:`OverflowError` if *length* is outside the permissible range
  381. of values.
  382. Note that some systems might support ancillary data without
  383. providing this function. Also note that setting the buffer size
  384. using the results of this function may not precisely limit the
  385. amount of ancillary data that can be received, since additional
  386. data may be able to fit into the padding area.
  387. Availability: most Unix platforms, possibly others.
  388. .. versionadded:: 3.3
  389. .. function:: getdefaulttimeout()
  390. Return the default timeout in seconds (float) for new socket objects. A value
  391. of ``None`` indicates that new socket objects have no timeout. When the socket
  392. module is first imported, the default is ``None``.
  393. .. function:: setdefaulttimeout(timeout)
  394. Set the default timeout in seconds (float) for new socket objects. When
  395. the socket module is first imported, the default is ``None``. See
  396. :meth:`~socket.settimeout` for possible values and their respective
  397. meanings.
  398. .. function:: sethostname(name)
  399. Set the machine's hostname to *name*. This will raise a
  400. :exc:`socket.error` if you don't have enough rights.
  401. Availability: Unix.
  402. .. versionadded:: 3.3
  403. .. function:: if_nameindex()
  404. Return a list of network interface information
  405. (index int, name string) tuples.
  406. :exc:`socket.error` if the system call fails.
  407. Availability: Unix.
  408. .. versionadded:: 3.3
  409. .. function:: if_nametoindex(if_name)
  410. Return a network interface index number corresponding to an
  411. interface name.
  412. :exc:`socket.error` if no interface with the given name exists.
  413. Availability: Unix.
  414. .. versionadded:: 3.3
  415. .. function:: if_indextoname(if_index)
  416. Return a network interface name corresponding to a
  417. interface index number.
  418. :exc:`socket.error` if no interface with the given index exists.
  419. Availability: Unix.
  420. .. versionadded:: 3.3
  421. .. data:: SocketType
  422. This is a Python type object that represents the socket object type. It is the
  423. same as ``type(socket(...))``.
  424. .. _socket-objects:
  425. Socket Objects
  426. --------------
  427. Socket objects have the following methods. Except for :meth:`makefile` these
  428. correspond to Unix system calls applicable to sockets.
  429. .. method:: socket.accept()
  430. Accept a connection. The socket must be bound to an address and listening for
  431. connections. The return value is a pair ``(conn, address)`` where *conn* is a
  432. *new* socket object usable to send and receive data on the connection, and
  433. *address* is the address bound to the socket on the other end of the connection.
  434. .. method:: socket.bind(address)
  435. Bind the socket to *address*. The socket must not already be bound. (The format
  436. of *address* depends on the address family --- see above.)
  437. .. method:: socket.close()
  438. Close the socket. All future operations on the socket object will fail. The
  439. remote end will receive no more data (after queued data is flushed). Sockets are
  440. automatically closed when they are garbage-collected.
  441. .. note::
  442. :meth:`close()` releases the resource associated with a connection but
  443. does not necessarily close the connection immediately. If you want
  444. to close the connection in a timely fashion, call :meth:`shutdown()`
  445. before :meth:`close()`.
  446. .. method:: socket.connect(address)
  447. Connect to a remote socket at *address*. (The format of *address* depends on the
  448. address family --- see above.)
  449. .. method:: socket.connect_ex(address)
  450. Like ``connect(address)``, but return an error indicator instead of raising an
  451. exception for errors returned by the C-level :c:func:`connect` call (other
  452. problems, such as "host not found," can still raise exceptions). The error
  453. indicator is ``0`` if the operation succeeded, otherwise the value of the
  454. :c:data:`errno` variable. This is useful to support, for example, asynchronous
  455. connects.
  456. .. method:: socket.detach()
  457. Put the socket object into closed state without actually closing the
  458. underlying file descriptor. The file descriptor is returned, and can
  459. be reused for other purposes.
  460. .. versionadded:: 3.2
  461. .. method:: socket.fileno()
  462. Return the socket's file descriptor (a small integer). This is useful with
  463. :func:`select.select`.
  464. Under Windows the small integer returned by this method cannot be used where a
  465. file descriptor can be used (such as :func:`os.fdopen`). Unix does not have
  466. this limitation.
  467. .. method:: socket.getpeername()
  468. Return the remote address to which the socket is connected. This is useful to
  469. find out the port number of a remote IPv4/v6 socket, for instance. (The format
  470. of the address returned depends on the address family --- see above.) On some
  471. systems this function is not supported.
  472. .. method:: socket.getsockname()
  473. Return the socket's own address. This is useful to find out the port number of
  474. an IPv4/v6 socket, for instance. (The format of the address returned depends on
  475. the address family --- see above.)
  476. .. method:: socket.getsockopt(level, optname[, buflen])
  477. Return the value of the given socket option (see the Unix man page
  478. :manpage:`getsockopt(2)`). The needed symbolic constants (:const:`SO_\*` etc.)
  479. are defined in this module. If *buflen* is absent, an integer option is assumed
  480. and its integer value is returned by the function. If *buflen* is present, it
  481. specifies the maximum length of the buffer used to receive the option in, and
  482. this buffer is returned as a bytes object. It is up to the caller to decode the
  483. contents of the buffer (see the optional built-in module :mod:`struct` for a way
  484. to decode C structures encoded as byte strings).
  485. .. method:: socket.gettimeout()
  486. Return the timeout in seconds (float) associated with socket operations,
  487. or ``None`` if no timeout is set. This reflects the last call to
  488. :meth:`setblocking` or :meth:`settimeout`.
  489. .. method:: socket.ioctl(control, option)
  490. :platform: Windows
  491. The :meth:`ioctl` method is a limited interface to the WSAIoctl system
  492. interface. Please refer to the `Win32 documentation
  493. <http://msdn.microsoft.com/en-us/library/ms741621%28VS.85%29.aspx>`_ for more
  494. information.
  495. On other platforms, the generic :func:`fcntl.fcntl` and :func:`fcntl.ioctl`
  496. functions may be used; they accept a socket object as their first argument.
  497. .. method:: socket.listen(backlog)
  498. Listen for connections made to the socket. The *backlog* argument specifies the
  499. maximum number of queued connections and should be at least 0; the maximum value
  500. is system-dependent (usually 5), the minimum value is forced to 0.
  501. .. method:: socket.makefile(mode='r', buffering=None, *, encoding=None, \
  502. errors=None, newline=None)
  503. .. index:: single: I/O control; buffering
  504. Return a :term:`file object` associated with the socket. The exact returned
  505. type depends on the arguments given to :meth:`makefile`. These arguments are
  506. interpreted the same way as by the built-in :func:`open` function.
  507. Closing the file object won't close the socket unless there are no remaining
  508. references to the socket. The socket must be in blocking mode; it can have
  509. a timeout, but the file object's internal buffer may end up in a inconsistent
  510. state if a timeout occurs.
  511. .. note::
  512. On Windows, the file-like object created by :meth:`makefile` cannot be
  513. used where a file object with a file descriptor is expected, such as the
  514. stream arguments of :meth:`subprocess.Popen`.
  515. .. method:: socket.recv(bufsize[, flags])
  516. Receive data from the socket. The return value is a bytes object representing the
  517. data received. The maximum amount of data to be received at once is specified
  518. by *bufsize*. See the Unix manual page :manpage:`recv(2)` for the meaning of
  519. the optional argument *flags*; it defaults to zero.
  520. .. note::
  521. For best match with hardware and network realities, the value of *bufsize*
  522. should be a relatively small power of 2, for example, 4096.
  523. .. method:: socket.recvfrom(bufsize[, flags])
  524. Receive data from the socket. The return value is a pair ``(bytes, address)``
  525. where *bytes* is a bytes object representing the data received and *address* is the
  526. address of the socket sending the data. See the Unix manual page
  527. :manpage:`recv(2)` for the meaning of the optional argument *flags*; it defaults
  528. to zero. (The format of *address* depends on the address family --- see above.)
  529. .. method:: socket.recvmsg(bufsize[, ancbufsize[, flags]])
  530. Receive normal data (up to *bufsize* bytes) and ancillary data from
  531. the socket. The *ancbufsize* argument sets the size in bytes of
  532. the internal buffer used to receive the ancillary data; it defaults
  533. to 0, meaning that no ancillary data will be received. Appropriate
  534. buffer sizes for ancillary data can be calculated using
  535. :func:`CMSG_SPACE` or :func:`CMSG_LEN`, and items which do not fit
  536. into the buffer might be truncated or discarded. The *flags*
  537. argument defaults to 0 and has the same meaning as for
  538. :meth:`recv`.
  539. The return value is a 4-tuple: ``(data, ancdata, msg_flags,
  540. address)``. The *data* item is a :class:`bytes` object holding the
  541. non-ancillary data received. The *ancdata* item is a list of zero
  542. or more tuples ``(cmsg_level, cmsg_type, cmsg_data)`` representing
  543. the ancillary data (control messages) received: *cmsg_level* and
  544. *cmsg_type* are integers specifying the protocol level and
  545. protocol-specific type respectively, and *cmsg_data* is a
  546. :class:`bytes` object holding the associated data. The *msg_flags*
  547. item is the bitwise OR of various flags indicating conditions on
  548. the received message; see your system documentation for details.
  549. If the receiving socket is unconnected, *address* is the address of
  550. the sending socket, if available; otherwise, its value is
  551. unspecified.
  552. On some systems, :meth:`sendmsg` and :meth:`recvmsg` can be used to
  553. pass file descriptors between processes over an :const:`AF_UNIX`
  554. socket. When this facility is used (it is often restricted to
  555. :const:`SOCK_STREAM` sockets), :meth:`recvmsg` will return, in its
  556. ancillary data, items of the form ``(socket.SOL_SOCKET,
  557. socket.SCM_RIGHTS, fds)``, where *fds* is a :class:`bytes` object
  558. representing the new file descriptors as a binary array of the
  559. native C :c:type:`int` type. If :meth:`recvmsg` raises an
  560. exception after the system call returns, it will first attempt to
  561. close any file descriptors received via this mechanism.
  562. Some systems do not indicate the truncated length of ancillary data
  563. items which have been only partially received. If an item appears
  564. to extend beyond the end of the buffer, :meth:`recvmsg` will issue
  565. a :exc:`RuntimeWarning`, and will return the part of it which is
  566. inside the buffer provided it has not been truncated before the
  567. start of its associated data.
  568. On systems which support the :const:`SCM_RIGHTS` mechanism, the
  569. following function will receive up to *maxfds* file descriptors,
  570. returning the message data and a list containing the descriptors
  571. (while ignoring unexpected conditions such as unrelated control
  572. messages being received). See also :meth:`sendmsg`. ::
  573. import socket, array
  574. def recv_fds(sock, msglen, maxfds):
  575. fds = array.array("i") # Array of ints
  576. msg, ancdata, flags, addr = sock.recvmsg(msglen, socket.CMSG_LEN(maxfds * fds.itemsize))
  577. for cmsg_level, cmsg_type, cmsg_data in ancdata:
  578. if (cmsg_level == socket.SOL_SOCKET and cmsg_type == socket.SCM_RIGHTS):
  579. # Append data, ignoring any truncated integers at the end.
  580. fds.fromstring(cmsg_data[:len(cmsg_data) - (len(cmsg_data) % fds.itemsize)])
  581. return msg, list(fds)
  582. Availability: most Unix platforms, possibly others.
  583. .. versionadded:: 3.3
  584. .. method:: socket.recvmsg_into(buffers[, ancbufsize[, flags]])
  585. Receive normal data and ancillary data from the socket, behaving as
  586. :meth:`recvmsg` would, but scatter the non-ancillary data into a
  587. series of buffers instead of returning a new bytes object. The
  588. *buffers* argument must be an iterable of objects that export
  589. writable buffers (e.g. :class:`bytearray` objects); these will be
  590. filled with successive chunks of the non-ancillary data until it
  591. has all been written or there are no more buffers. The operating
  592. system may set a limit (:func:`~os.sysconf` value ``SC_IOV_MAX``)
  593. on the number of buffers that can be used. The *ancbufsize* and
  594. *flags* arguments have the same meaning as for :meth:`recvmsg`.
  595. The return value is a 4-tuple: ``(nbytes, ancdata, msg_flags,
  596. address)``, where *nbytes* is the total number of bytes of
  597. non-ancillary data written into the buffers, and *ancdata*,
  598. *msg_flags* and *address* are the same as for :meth:`recvmsg`.
  599. Example::
  600. >>> import socket
  601. >>> s1, s2 = socket.socketpair()
  602. >>> b1 = bytearray(b'----')
  603. >>> b2 = bytearray(b'0123456789')
  604. >>> b3 = bytearray(b'--------------')
  605. >>> s1.send(b'Mary had a little lamb')
  606. 22
  607. >>> s2.recvmsg_into([b1, memoryview(b2)[2:9], b3])
  608. (22, [], 0, None)
  609. >>> [b1, b2, b3]
  610. [bytearray(b'Mary'), bytearray(b'01 had a 9'), bytearray(b'little lamb---')]
  611. Availability: most Unix platforms, possibly others.
  612. .. versionadded:: 3.3
  613. .. method:: socket.recvfrom_into(buffer[, nbytes[, flags]])
  614. Receive data from the socket, writing it into *buffer* instead of creating a
  615. new bytestring. The return value is a pair ``(nbytes, address)`` where *nbytes* is
  616. the number of bytes received and *address* is the address of the socket sending
  617. the data. See the Unix manual page :manpage:`recv(2)` for the meaning of the
  618. optional argument *flags*; it defaults to zero. (The format of *address*
  619. depends on the address family --- see above.)
  620. .. method:: socket.recv_into(buffer[, nbytes[, flags]])
  621. Receive up to *nbytes* bytes from the socket, storing the data into a buffer
  622. rather than creating a new bytestring. If *nbytes* is not specified (or 0),
  623. receive up to the size available in the given buffer. Returns the number of
  624. bytes received. See the Unix manual page :manpage:`recv(2)` for the meaning
  625. of the optional argument *flags*; it defaults to zero.
  626. .. method:: socket.send(bytes[, flags])
  627. Send data to the socket. The socket must be connected to a remote socket. The
  628. optional *flags* argument has the same meaning as for :meth:`recv` above.
  629. Returns the number of bytes sent. Applications are responsible for checking that
  630. all data has been sent; if only some of the data was transmitted, the
  631. application needs to attempt delivery of the remaining data.
  632. .. method:: socket.sendall(bytes[, flags])
  633. Send data to the socket. The socket must be connected to a remote socket. The
  634. optional *flags* argument has the same meaning as for :meth:`recv` above.
  635. Unlike :meth:`send`, this method continues to send data from *bytes* until
  636. either all data has been sent or an error occurs. ``None`` is returned on
  637. success. On error, an exception is raised, and there is no way to determine how
  638. much data, if any, was successfully sent.
  639. .. method:: socket.sendto(bytes[, flags], address)
  640. Send data to the socket. The socket should not be connected to a remote socket,
  641. since the destination socket is specified by *address*. The optional *flags*
  642. argument has the same meaning as for :meth:`recv` above. Return the number of
  643. bytes sent. (The format of *address* depends on the address family --- see
  644. above.)
  645. .. method:: socket.sendmsg(buffers[, ancdata[, flags[, address]]])
  646. Send normal and ancillary data to the socket, gathering the
  647. non-ancillary data from a series of buffers and concatenating it
  648. into a single message. The *buffers* argument specifies the
  649. non-ancillary data as an iterable of buffer-compatible objects
  650. (e.g. :class:`bytes` objects); the operating system may set a limit
  651. (:func:`~os.sysconf` value ``SC_IOV_MAX``) on the number of buffers
  652. that can be used. The *ancdata* argument specifies the ancillary
  653. data (control messages) as an iterable of zero or more tuples
  654. ``(cmsg_level, cmsg_type, cmsg_data)``, where *cmsg_level* and
  655. *cmsg_type* are integers specifying the protocol level and
  656. protocol-specific type respectively, and *cmsg_data* is a
  657. buffer-compatible object holding the associated data. Note that
  658. some systems (in particular, systems without :func:`CMSG_SPACE`)
  659. might support sending only one control message per call. The
  660. *flags* argument defaults to 0 and has the same meaning as for
  661. :meth:`send`. If *address* is supplied and not ``None``, it sets a
  662. destination address for the message. The return value is the
  663. number of bytes of non-ancillary data sent.
  664. The following function sends the list of file descriptors *fds*
  665. over an :const:`AF_UNIX` socket, on systems which support the
  666. :const:`SCM_RIGHTS` mechanism. See also :meth:`recvmsg`. ::
  667. import socket, array
  668. def send_fds(sock, msg, fds):
  669. return sock.sendmsg([msg], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", fds))])
  670. Availability: most Unix platforms, possibly others.
  671. .. versionadded:: 3.3
  672. .. method:: socket.setblocking(flag)
  673. Set blocking or non-blocking mode of the socket: if *flag* is false, the
  674. socket is set to non-blocking, else to blocking mode.
  675. This method is a shorthand for certain :meth:`~socket.settimeout` calls:
  676. * ``sock.setblocking(True)`` is equivalent to ``sock.settimeout(None)``
  677. * ``sock.setblocking(False)`` is equivalent to ``sock.settimeout(0.0)``
  678. .. method:: socket.settimeout(value)
  679. Set a timeout on blocking socket operations. The *value* argument can be a
  680. nonnegative floating point number expressing seconds, or ``None``.
  681. If a non-zero value is given, subsequent socket operations will raise a
  682. :exc:`timeout` exception if the timeout period *value* has elapsed before
  683. the operation has completed. If zero is given, the socket is put in
  684. non-blocking mode. If ``None`` is given, the socket is put in blocking mode.
  685. For further information, please consult the :ref:`notes on socket timeouts <socket-timeouts>`.
  686. .. method:: socket.setsockopt(level, optname, value)
  687. .. index:: module: struct
  688. Set the value of the given socket option (see the Unix manual page
  689. :manpage:`setsockopt(2)`). The needed symbolic constants are defined in the
  690. :mod:`socket` module (:const:`SO_\*` etc.). The value can be an integer or a
  691. bytes object representing a buffer. In the latter case it is up to the caller to
  692. ensure that the bytestring contains the proper bits (see the optional built-in
  693. module :mod:`struct` for a way to encode C structures as bytestrings).
  694. .. method:: socket.shutdown(how)
  695. Shut down one or both halves of the connection. If *how* is :const:`SHUT_RD`,
  696. further receives are disallowed. If *how* is :const:`SHUT_WR`, further sends
  697. are disallowed. If *how* is :const:`SHUT_RDWR`, further sends and receives are
  698. disallowed. Depending on the platform, shutting down one half of the connection
  699. can also close the opposite half (e.g. on Mac OS X, ``shutdown(SHUT_WR)`` does
  700. not allow further reads on the other end of the connection).
  701. Note that there are no methods :meth:`read` or :meth:`write`; use
  702. :meth:`~socket.recv` and :meth:`~socket.send` without *flags* argument instead.
  703. Socket objects also have these (read-only) attributes that correspond to the
  704. values given to the :class:`socket` constructor.
  705. .. attribute:: socket.family
  706. The socket family.
  707. .. attribute:: socket.type
  708. The socket type.
  709. .. attribute:: socket.proto
  710. The socket protocol.
  711. .. _socket-timeouts:
  712. Notes on socket timeouts
  713. ------------------------
  714. A socket object can be in one of three modes: blocking, non-blocking, or
  715. timeout. Sockets are by default always created in blocking mode, but this
  716. can be changed by calling :func:`setdefaulttimeout`.
  717. * In *blocking mode*, operations block until complete or the system returns
  718. an error (such as connection timed out).
  719. * In *non-blocking mode*, operations fail (with an error that is unfortunately
  720. system-dependent) if they cannot be completed immediately: functions from the
  721. :mod:`select` can be used to know when and whether a socket is available for
  722. reading or writing.
  723. * In *timeout mode*, operations fail if they cannot be completed within the
  724. timeout specified for the socket (they raise a :exc:`timeout` exception)
  725. or if the system returns an error.
  726. .. note::
  727. At the operating system level, sockets in *timeout mode* are internally set
  728. in non-blocking mode. Also, the blocking and timeout modes are shared between
  729. file descriptors and socket objects that refer to the same network endpoint.
  730. This implementation detail can have visible consequences if e.g. you decide
  731. to use the :meth:`~socket.fileno()` of a socket.
  732. Timeouts and the ``connect`` method
  733. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  734. The :meth:`~socket.connect` operation is also subject to the timeout
  735. setting, and in general it is recommended to call :meth:`~socket.settimeout`
  736. before calling :meth:`~socket.connect` or pass a timeout parameter to
  737. :meth:`create_connection`. However, the system network stack may also
  738. return a connection timeout error of its own regardless of any Python socket
  739. timeout setting.
  740. Timeouts and the ``accept`` method
  741. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  742. If :func:`getdefaulttimeout` is not :const:`None`, sockets returned by
  743. the :meth:`~socket.accept` method inherit that timeout. Otherwise, the
  744. behaviour depends on settings of the listening socket:
  745. * if the listening socket is in *blocking mode* or in *timeout mode*,
  746. the socket returned by :meth:`~socket.accept` is in *blocking mode*;
  747. * if the listening socket is in *non-blocking mode*, whether the socket
  748. returned by :meth:`~socket.accept` is in blocking or non-blocking mode
  749. is operating system-dependent. If you want to ensure cross-platform
  750. behaviour, it is recommended you manually override this setting.
  751. .. _socket-example:
  752. Example
  753. -------
  754. Here are four minimal example programs using the TCP/IP protocol: a server that
  755. echoes all data that it receives back (servicing only one client), and a client
  756. using it. Note that a server must perform the sequence :func:`socket`,
  757. :meth:`~socket.bind`, :meth:`~socket.listen`, :meth:`~socket.accept` (possibly
  758. repeating the :meth:`~socket.accept` to service more than one client), while a
  759. client only needs the sequence :func:`socket`, :meth:`~socket.connect`. Also
  760. note that the server does not :meth:`~socket.send`/:meth:`~socket.recv` on the
  761. socket it is listening on but on the new socket returned by
  762. :meth:`~socket.accept`.
  763. The first two examples support IPv4 only. ::
  764. # Echo server program
  765. import socket
  766. HOST = '' # Symbolic name meaning all available interfaces
  767. PORT = 50007 # Arbitrary non-privileged port
  768. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  769. s.bind((HOST, PORT))
  770. s.listen(1)
  771. conn, addr = s.accept()
  772. print('Connected by', addr)
  773. while True:
  774. data = conn.recv(1024)
  775. if not data: break
  776. conn.send(data)
  777. conn.close()
  778. ::
  779. # Echo client program
  780. import socket
  781. HOST = 'daring.cwi.nl' # The remote host
  782. PORT = 50007 # The same port as used by the server
  783. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  784. s.connect((HOST, PORT))
  785. s.send(b'Hello, world')
  786. data = s.recv(1024)
  787. s.close()
  788. print('Received', repr(data))
  789. The next two examples are identical to the above two, but support both IPv4 and
  790. IPv6. The server side will listen to the first address family available (it
  791. should listen to both instead). On most of IPv6-ready systems, IPv6 will take
  792. precedence and the server may not accept IPv4 traffic. The client side will try
  793. to connect to the all addresses returned as a result of the name resolution, and
  794. sends traffic to the first one connected successfully. ::
  795. # Echo server program
  796. import socket
  797. import sys
  798. HOST = None # Symbolic name meaning all available interfaces
  799. PORT = 50007 # Arbitrary non-privileged port
  800. s = None
  801. for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC,
  802. socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
  803. af, socktype, proto, canonname, sa = res
  804. try:
  805. s = socket.socket(af, socktype, proto)
  806. except socket.error as msg:
  807. s = None
  808. continue
  809. try:
  810. s.bind(sa)
  811. s.listen(1)
  812. except socket.error as msg:
  813. s.close()
  814. s = None
  815. continue
  816. break
  817. if s is None:
  818. print('could not open socket')
  819. sys.exit(1)
  820. conn, addr = s.accept()
  821. print('Connected by', addr)
  822. while True:
  823. data = conn.recv(1024)
  824. if not data: break
  825. conn.send(data)
  826. conn.close()
  827. ::
  828. # Echo client program
  829. import socket
  830. import sys
  831. HOST = 'daring.cwi.nl' # The remote host
  832. PORT = 50007 # The same port as used by the server
  833. s = None
  834. for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM):
  835. af, socktype, proto, canonname, sa = res
  836. try:
  837. s = socket.socket(af, socktype, proto)
  838. except socket.error as msg:
  839. s = None
  840. continue
  841. try:
  842. s.connect(sa)
  843. except socket.error as msg:
  844. s.close()
  845. s = None
  846. continue
  847. break
  848. if s is None:
  849. print('could not open socket')
  850. sys.exit(1)
  851. s.send(b'Hello, world')
  852. data = s.recv(1024)
  853. s.close()
  854. print('Received', repr(data))
  855. The last example shows how to write a very simple network sniffer with raw
  856. sockets on Windows. The example requires administrator privileges to modify
  857. the interface::
  858. import socket
  859. # the public network interface
  860. HOST = socket.gethostbyname(socket.gethostname())
  861. # create a raw socket and bind it to the public interface
  862. s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
  863. s.bind((HOST, 0))
  864. # Include IP headers
  865. s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
  866. # receive all packages
  867. s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
  868. # receive a package
  869. print(s.recvfrom(65565))
  870. # disabled promiscuous mode
  871. s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)
  872. Running an example several times with too small delay between executions, could
  873. lead to this error::
  874. socket.error: [Errno 98] Address already in use
  875. This is because the previous execution has left the socket in a ``TIME_WAIT``
  876. state, and can't be immediately reused.
  877. There is a :mod:`socket` flag to set, in order to prevent this,
  878. :data:`socket.SO_REUSEADDR`::
  879. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  880. s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  881. s.bind((HOST, PORT))
  882. the :data:`SO_REUSEADDR` flag tells the kernel to reuse a local socket in
  883. ``TIME_WAIT`` state, without waiting for its natural timeout to expire.
  884. .. seealso::
  885. For an introduction to socket programming (in C), see the following papers:
  886. - *An Introductory 4.3BSD Interprocess Communication Tutorial*, by Stuart Sechrest
  887. - *An Advanced 4.3BSD Interprocess Communication Tutorial*, by Samuel J. Leffler et
  888. al,
  889. both in the UNIX Programmer's Manual, Supplementary Documents 1 (sections
  890. PS1:7 and PS1:8). The platform-specific reference material for the various
  891. socket-related system calls are also a valuable source of information on the
  892. details of socket semantics. For Unix, refer to the manual pages; for Windows,
  893. see the WinSock (or Winsock 2) specification. For IPv6-ready APIs, readers may
  894. want to refer to :rfc:`3493` titled Basic Socket Interface Extensions for IPv6.