usocket.rst 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. *******************************
  2. :mod:`usocket` -- socket module
  3. *******************************
  4. .. module:: usocket
  5. :synopsis: socket module
  6. |see_cpython_module| :mod:`python:socket`.
  7. This module provides access to the BSD socket interface.
  8. .. admonition:: Difference to CPython
  9. :class: attention
  10. For efficiency and consistency, socket objects in MicroPython implement a `stream`
  11. (file-like) interface directly. In CPython, you need to convert a socket to
  12. a file-like object using `makefile()` method. This method is still supported
  13. by MicroPython (but is a no-op), so where compatibility with CPython matters,
  14. be sure to use it.
  15. Socket address format(s)
  16. ------------------------
  17. The native socket address format of the ``usocket`` module is an opaque data type
  18. returned by `getaddrinfo` function, which must be used to resolve textual address
  19. (including numeric addresses)::
  20. sockaddr = usocket.getaddrinfo('www.micropython.org', 80)[0][-1]
  21. # You must use getaddrinfo() even for numeric addresses
  22. sockaddr = usocket.getaddrinfo('127.0.0.1', 80)[0][-1]
  23. # Now you can use that address
  24. sock.connect(addr)
  25. Using `getaddrinfo` is the most efficient (both in terms of memory and processing
  26. power) and portable way to work with addresses.
  27. However, ``socket`` module (note the difference with native MicroPython
  28. ``usocket`` module described here) provides CPython-compatible way to specify
  29. addresses using tuples, as described below. Note that depending on a
  30. `MicroPython port`, ``socket`` module can be builtin or need to be
  31. installed from `micropython-lib` (as in the case of `MicroPython Unix port`),
  32. and some ports still accept only numeric addresses in the tuple format,
  33. and require to use `getaddrinfo` function to resolve domain names.
  34. Summing up:
  35. * Always use `getaddrinfo` when writing portable applications.
  36. * Tuple addresses described below can be used as a shortcut for
  37. quick hacks and interactive use, if your port supports them.
  38. Tuple address format for ``socket`` module:
  39. * IPv4: *(ipv4_address, port)*, where *ipv4_address* is a string with
  40. dot-notation numeric IPv4 address, e.g. ``"8.8.8.8"``, and *port* is and
  41. integer port number in the range 1-65535. Note the domain names are not
  42. accepted as *ipv4_address*, they should be resolved first using
  43. `usocket.getaddrinfo()`.
  44. * IPv6: *(ipv6_address, port, flowinfo, scopeid)*, where *ipv6_address*
  45. is a string with colon-notation numeric IPv6 address, e.g. ``"2001:db8::1"``,
  46. and *port* is an integer port number in the range 1-65535. *flowinfo*
  47. must be 0. *scopeid* is the interface scope identifier for link-local
  48. addresses. Note the domain names are not accepted as *ipv6_address*,
  49. they should be resolved first using `usocket.getaddrinfo()`. Availability
  50. of IPv6 support depends on a `MicroPython port`.
  51. Functions
  52. ---------
  53. .. function:: socket(af=AF_INET, type=SOCK_STREAM, proto=IPPROTO_TCP)
  54. Create a new socket using the given address family, socket type and
  55. protocol number. Note that specifying *proto* in most cases is not
  56. required (and not recommended, as some MicroPython ports may omit
  57. ``IPPROTO_*`` constants). Instead, *type* argument will select needed
  58. protocol automatically::
  59. # Create STREAM TCP socket
  60. socket(AF_INET, SOCK_STREAM)
  61. # Create DGRAM UDP socket
  62. socket(AF_INET, SOCK_DGRAM)
  63. .. function:: getaddrinfo(host, port, af=0, type=0, proto=0, flags=0)
  64. Translate the host/port argument into a sequence of 5-tuples that contain all the
  65. necessary arguments for creating a socket connected to that service. Arguments
  66. *af*, *type*, and *proto* (which have the same meaning as for the `socket()` function)
  67. can be used to filter which kind of addresses are returned. If a parameter is not
  68. specified or zero, all combinations of addresses can be returned (requiring
  69. filtering on the user side).
  70. The resulting list of 5-tuples has the following structure::
  71. (family, type, proto, canonname, sockaddr)
  72. The following example shows how to connect to a given url::
  73. s = usocket.socket()
  74. # This assumes that if "type" is not specified, an address for
  75. # SOCK_STREAM will be returned, which may be not true
  76. s.connect(usocket.getaddrinfo('www.micropython.org', 80)[0][-1])
  77. Recommended use of filtering params::
  78. s = usocket.socket()
  79. # Guaranteed to return an address which can be connect'ed to for
  80. # stream operation.
  81. s.connect(usocket.getaddrinfo('www.micropython.org', 80, 0, SOCK_STREAM)[0][-1])
  82. .. admonition:: Difference to CPython
  83. :class: attention
  84. CPython raises a ``socket.gaierror`` exception (`OSError` subclass) in case
  85. of error in this function. MicroPython doesn't have ``socket.gaierror``
  86. and raises OSError directly. Note that error numbers of `getaddrinfo()`
  87. form a separate namespace and may not match error numbers from
  88. the :mod:`uerrno` module. To distinguish `getaddrinfo()` errors, they are
  89. represented by negative numbers, whereas standard system errors are
  90. positive numbers (error numbers are accessible using ``e.args[0]`` property
  91. from an exception object). The use of negative values is a provisional
  92. detail which may change in the future.
  93. .. function:: inet_ntop(af, bin_addr)
  94. Convert a binary network address *bin_addr* of the given address family *af*
  95. to a textual representation::
  96. >>> usocket.inet_ntop(usocket.AF_INET, b"\x7f\0\0\1")
  97. '127.0.0.1'
  98. .. function:: inet_pton(af, txt_addr)
  99. Convert a textual network address *txt_addr* of the given address family *af*
  100. to a binary representation::
  101. >>> usocket.inet_pton(usocket.AF_INET, "1.2.3.4")
  102. b'\x01\x02\x03\x04'
  103. Constants
  104. ---------
  105. .. data:: AF_INET
  106. AF_INET6
  107. Address family types. Availability depends on a particular `MicroPython port`.
  108. .. data:: SOCK_STREAM
  109. SOCK_DGRAM
  110. Socket types.
  111. .. data:: IPPROTO_UDP
  112. IPPROTO_TCP
  113. IP protocol numbers. Availability depends on a particular `MicroPython port`.
  114. Note that you don't need to specify these in a call to `usocket.socket()`,
  115. because `SOCK_STREAM` socket type automatically selects `IPPROTO_TCP`, and
  116. `SOCK_DGRAM` - `IPPROTO_UDP`. Thus, the only real use of these constants
  117. is as an argument to `setsockopt()`.
  118. .. data:: usocket.SOL_*
  119. Socket option levels (an argument to `setsockopt()`). The exact
  120. inventory depends on a `MicroPython port`.
  121. .. data:: usocket.SO_*
  122. Socket options (an argument to `setsockopt()`). The exact
  123. inventory depends on a `MicroPython port`.
  124. Constants specific to WiPy:
  125. .. data:: IPPROTO_SEC
  126. Special protocol value to create SSL-compatible socket.
  127. class socket
  128. ============
  129. Methods
  130. -------
  131. .. method:: socket.close()
  132. Mark the socket closed and release all resources. Once that happens, all future operations
  133. on the socket object will fail. The remote end will receive EOF indication if
  134. supported by protocol.
  135. Sockets are automatically closed when they are garbage-collected, but it is recommended
  136. to `close()` them explicitly as soon you finished working with them.
  137. .. method:: socket.bind(address)
  138. Bind the socket to *address*. The socket must not already be bound.
  139. .. method:: socket.listen([backlog])
  140. Enable a server to accept connections. If *backlog* is specified, it must be at least 0
  141. (if it's lower, it will be set to 0); and specifies the number of unaccepted connections
  142. that the system will allow before refusing new connections. If not specified, a default
  143. reasonable value is chosen.
  144. .. method:: socket.accept()
  145. Accept a connection. The socket must be bound to an address and listening for connections.
  146. The return value is a pair (conn, address) where conn is a new socket object usable to send
  147. and receive data on the connection, and address is the address bound to the socket on the
  148. other end of the connection.
  149. .. method:: socket.connect(address)
  150. Connect to a remote socket at *address*.
  151. .. method:: socket.send(bytes)
  152. Send data to the socket. The socket must be connected to a remote socket.
  153. Returns number of bytes sent, which may be smaller than the length of data
  154. ("short write").
  155. .. method:: socket.sendall(bytes)
  156. Send all data to the socket. The socket must be connected to a remote socket.
  157. Unlike `send()`, this method will try to send all of data, by sending data
  158. chunk by chunk consecutively.
  159. The behavior of this method on non-blocking sockets is undefined. Due to this,
  160. on MicroPython, it's recommended to use `write()` method instead, which
  161. has the same "no short writes" policy for blocking sockets, and will return
  162. number of bytes sent on non-blocking sockets.
  163. .. method:: socket.recv(bufsize)
  164. Receive data from the socket. The return value is a bytes object representing the data
  165. received. The maximum amount of data to be received at once is specified by bufsize.
  166. .. method:: socket.sendto(bytes, address)
  167. Send data to the socket. The socket should not be connected to a remote socket, since the
  168. destination socket is specified by *address*.
  169. .. method:: socket.recvfrom(bufsize)
  170. Receive data from the socket. The return value is a pair *(bytes, address)* where *bytes* is a
  171. bytes object representing the data received and *address* is the address of the socket sending
  172. the data.
  173. .. method:: socket.setsockopt(level, optname, value)
  174. Set the value of the given socket option. The needed symbolic constants are defined in the
  175. socket module (SO_* etc.). The *value* can be an integer or a bytes-like object representing
  176. a buffer.
  177. .. method:: socket.settimeout(value)
  178. **Note**: Not every port supports this method, see below.
  179. Set a timeout on blocking socket operations. The value argument can be a nonnegative floating
  180. point number expressing seconds, or None. If a non-zero value is given, subsequent socket operations
  181. will raise an `OSError` exception if the timeout period value has elapsed before the operation has
  182. completed. If zero is given, the socket is put in non-blocking mode. If None is given, the socket
  183. is put in blocking mode.
  184. Not every `MicroPython port` supports this method. A more portable and
  185. generic solution is to use `uselect.poll` object. This allows to wait on
  186. multiple objects at the same time (and not just on sockets, but on generic
  187. `stream` objects which support polling). Example::
  188. # Instead of:
  189. s.settimeout(1.0) # time in seconds
  190. s.read(10) # may timeout
  191. # Use:
  192. poller = uselect.poll()
  193. poller.register(s, uselect.POLLIN)
  194. res = poller.poll(1000) # time in milliseconds
  195. if not res:
  196. # s is still not ready for input, i.e. operation timed out
  197. .. admonition:: Difference to CPython
  198. :class: attention
  199. CPython raises a ``socket.timeout`` exception in case of timeout,
  200. which is an `OSError` subclass. MicroPython raises an OSError directly
  201. instead. If you use ``except OSError:`` to catch the exception,
  202. your code will work both in MicroPython and CPython.
  203. .. method:: socket.setblocking(flag)
  204. Set blocking or non-blocking mode of the socket: if flag is false, the socket is set to non-blocking,
  205. else to blocking mode.
  206. This method is a shorthand for certain `settimeout()` calls:
  207. * ``sock.setblocking(True)`` is equivalent to ``sock.settimeout(None)``
  208. * ``sock.setblocking(False)`` is equivalent to ``sock.settimeout(0)``
  209. .. method:: socket.makefile(mode='rb', buffering=0)
  210. Return a file object associated with the socket. The exact returned type depends on the arguments
  211. given to makefile(). The support is limited to binary modes only ('rb', 'wb', and 'rwb').
  212. CPython's arguments: *encoding*, *errors* and *newline* are not supported.
  213. .. admonition:: Difference to CPython
  214. :class: attention
  215. As MicroPython doesn't support buffered streams, values of *buffering*
  216. parameter is ignored and treated as if it was 0 (unbuffered).
  217. .. admonition:: Difference to CPython
  218. :class: attention
  219. Closing the file object returned by makefile() WILL close the
  220. original socket as well.
  221. .. method:: socket.read([size])
  222. Read up to size bytes from the socket. Return a bytes object. If *size* is not given, it
  223. reads all data available from the socket until EOF; as such the method will not return until
  224. the socket is closed. This function tries to read as much data as
  225. requested (no "short reads"). This may be not possible with
  226. non-blocking socket though, and then less data will be returned.
  227. .. method:: socket.readinto(buf[, nbytes])
  228. Read bytes into the *buf*. If *nbytes* is specified then read at most
  229. that many bytes. Otherwise, read at most *len(buf)* bytes. Just as
  230. `read()`, this method follows "no short reads" policy.
  231. Return value: number of bytes read and stored into *buf*.
  232. .. method:: socket.readline()
  233. Read a line, ending in a newline character.
  234. Return value: the line read.
  235. .. method:: socket.write(buf)
  236. Write the buffer of bytes to the socket. This function will try to
  237. write all data to a socket (no "short writes"). This may be not possible
  238. with a non-blocking socket though, and returned value will be less than
  239. the length of *buf*.
  240. Return value: number of bytes written.
  241. .. exception:: usocket.error
  242. MicroPython does NOT have this exception.
  243. .. admonition:: Difference to CPython
  244. :class: attention
  245. CPython used to have a ``socket.error`` exception which is now deprecated,
  246. and is an alias of `OSError`. In MicroPython, use `OSError` directly.