usocket – socket module

This module implements a subset of the corresponding CPython module, as described below. For more information, please refer to the original CPython documentation: socket

This module provides access to the BSD socket interface.

Differences from CPython

For efficiency and consistency, socket objects in MicroPython directly implement the stream (file-like) interface. In CPython, you need to use the makefile() method to convert a socket into a file-like object. This method is still supported by MicroPython (but is a no-op), so for CPython compatibility, please be sure to use it.

Socket address format

The following functions use the (ipv4_address, port) network address, where ipv4_address is a string composed of dots and numbers, such as "8.8.8.8", and the port is a number from 1 to 65535. Note that a domain name cannot be used as ipv4_address; a domain name must first be resolved using socket.getaddrinfo().

The native socket address format of the usocket module is an opaque data type returned by the getaddrinfo function, which must be used to resolve textual addresses (including numeric addresses):

sockaddr = usocket.getaddrinfo('www.micropython.org', 80)[0][-1]
# You must use getaddrinfo() even for numeric addresses
sockaddr = usocket.getaddrinfo('127.0.0.1', 80)[0][-1]
# Now you can use that address
sock.connect(addr)

Using getaddrinfo is the most efficient (in terms of both memory and processing power) and most convenient way to handle addresses.

Functions

usocket.socket(af=AF_INET, type=SOCK_STREAM, proto=IPPROTO_TCP)
  • af: address

    • socket.AF_INET:=2 — TCP/IP – IPv4

    • socket.AF_INET6 :=10 — TCP/IP – IPv6

  • type: socket type

    • socket.SOCK_STREAM:=1 — TCP stream

    • socket.SOCK_DGRAM:=2 — UDP datagram

    • socket.SOCK_RAW :=3 — raw socket

    • socket.SO_REUSEADDR : =4 — the socket is reusable

  • proto: protocol number

    • socket.IPPROTO_TCP =6

    • socket.IPPROTO_UDP =17

Generally, the proto parameter is not specified, because some MicroPython firmware provides default parameters:

>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> print(s)
<socket>
usocket.getaddrinfo(host, port)

Translate the host domain name (host) and port (port) into a sequence of 5-tuples used to create sockets. The structure of the list of tuples is as follows:

(family, type, proto, canonname, sockaddr)

The following shows how to connect to a URL:

s = usocket.socket()
s.connect(usocket.getaddrinfo('www.micropython.org', 80)[0][-1])

Differences from CPython

When this function encounters an error, it raises a socket.gaierror exception (a subclass of OSError). MicroPython does not have socket.gaierror; it raises OSError directly. Note: the error numbers of getaddrinfo() form a separate namespace, which may not match the error numbers in the uerrno system error code module. To distinguish getaddrinfo() errors, these errors are marked with negative numbers, while standard system errors are positive (the error number can be accessed using the e.args[0] attribute of the exception object). Negative numbers are used for now; this may change in the future.

socket class

Methods

socket.close()

Mark the socket as closed and release all resources. Once this happens, all future operations on the socket object will fail. If supported by the protocol, the remote end will receive an EOF indication.

The socket is closed automatically during garbage collection, but it is still recommended to close it with close() when necessary.

socket.bind(address)

Bind the address and port number as a list or tuple. The socket must not already be bound.

  • address: a list or tuple containing the address and port number.

Example:

addr = ("127.0.0.1",10000)
s.bind(addr)
socket.listen([backlog])

Listen on the socket, enabling the server to accept connections. If backlog is specified, it must be at least 0 (if it is lower, it will be set to 0); it specifies the number of unaccepted connections that the system will allow before refusing new connections. If not specified, a default reasonable value is chosen.

  • backlog: the maximum number of accepted sockets, at least 0; if not specified, a default reasonable value is used.

socket.accept()

Accept a connection request. The socket needs to have a specified address and be listening for connections. The return value is (conn, address), where conn is the socket used to receive and send data, and address is the socket bound to the other end.

  • conn: a new socket object that can be used to send and receive messages

  • address: the address of the client connected to the server

socket.connect(address)

Connect to a remote socket at the specified address.

  • address: a tuple or list of the address and port number

Example:

host = "192.168.3.147"
port = 100
s.connect((host, port))
socket.send(bytes)

Send data to the socket. The socket must be connected to a remote socket. Return the number of bytes sent, which may be less than the length of the data (“short write”).

  • bytes: bytes-type data

socket.sendall(bytes)

Send all data to the socket. The socket must be connected to a remote socket. Unlike send(), this method will attempt to send all data by sending data chunks in succession.

The behavior of this method on non-blocking sockets is undefined. Therefore, on MicroPython, it is recommended to use the write() method, which has the same “no short write” policy for blocking sockets and will return the number of bytes sent on non-blocking sockets.

  • bytes: bytes-type data

socket.recv(bufsize)

Receive data from the socket. The return value is a bytes object representing the received data. The maximum amount of data to be received at once is specified by bufsize.

  • bufsize: specifies the maximum amount of data to receive at once

Example:

data = conn.recv(1024)
socket.sendto(bytes, address)

Send data to the socket. The socket should not be connected to a remote socket, because the target socket is specified by the address. Used for UDP communication; returns the size of the data sent.

  • bytes: bytes-type data

  • address: a tuple of the target address and port number

socket.recvfrom(bufsize)

Receive data from the socket. The return value is a pair (bytes, address), where bytes is a bytes object representing the received data and address is the address of the socket sending the data. Used for UDP communication.

  • bufsize: specifies the maximum amount of data to receive at once

socket.setsockopt(level, optname, value)

Set the value of the given socket option. The required symbolic constants are defined in the socket module (SO_*, etc.). The value can be an integer or a bytes-like object representing a buffer.

  • level: the socket option level

  • optname: the socket option

  • value: can be an integer, or a bytes-like object representing a buffer.

Example:

s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
socket.settimeout(value)

Set the timeout, in seconds.

Set the timeout. The value parameter can be a non-negative floating-point number representing seconds, or None. If a non-zero value is given, subsequent socket operations will raise an OSError exception if the timeout period value has elapsed before the operation has completed. If zero is given, the socket is put in non-blocking mode. If None is given, the socket is put in blocking mode.

Example:

s.settimeout(2)
socket.setblocking(flag)

Set the blocking or non-blocking mode of the socket: if the flag is false, the socket is set to non-blocking mode; otherwise to blocking mode.

This method is a shorthand for certain settimeout() calls:

  • sock.setblocking(True) is equivalent to sock.settimeout(None)

  • sock.setblocking(False) is equivalent to sock.settimeout(0)

Difference to CPython

CPython raises a socket.timeout exception in the case of a timeout, which is a subclass of OSError. MicroPython raises OSError directly. If you use it to catch the exception, your code will work in both MicroPython and CPython.

socket.makefile(mode='rb', buffering=0)

Return a file object associated with the socket. The exact return type depends on the arguments given to makefile(). The support is limited to binary modes (‘rb’ and ‘wb’). The CPython arguments encoding, errors and newline are not supported.

The socket must be in blocking mode; a timeout can be present, but if a timeout occurs, the internal buffer of the file object may end up in an inconsistent state.

Differences from CPython

  • Since MicroPython does not support buffered streams, the value of the buffering parameter will be ignored and it will be treated as if the value were 0 (unbuffered).

  • Closing all file objects returned by makefile() will also close the original socket.

socket.read([size])

Read size bytes from the socket. Return a bytes object. If size is not given, it behaves similarly to socket.readall(), see below.

socket.readinto(buf[, nbytes])

Read bytes into the buffer. If nbytes is specified, read at most that number of bytes. Otherwise, read at most len(buf) bytes. Like read(), this method follows the “no short reads” approach.

Return value: the number of bytes read and stored into the buffer

socket.readline()

Receive a line of data, ending at a newline, and return an object with the received data.

socket.write(buf)

Write the buffer of bytes to the socket. This function will attempt to write all data to the socket (no “short writes”). However, for a non-blocking socket, this may not be possible, and the return value will be less than the length of buf.

Return value: the number of bytes written.

exception usocket.error

MicroPython does not have this exception.

Difference to CPython

CPython once had a socket.error exception, now deprecated, which is an alias for OSError. In MicroPython, OSError is used directly.

Constants

usocket.AF_INET
usocket.AF_INET6

Address family

usocket.SOCK_STREAM
usocket.SOCK_DGRAM

Socket type

usocket.IPPROTO_UDP
usocket.IPPROTO_TCP

IP protocol number

usocket.SOL_SOCKET

The socket option level, default=4095