usocket – Socket Module

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

This module provides access to the BSD socket interface.

Difference to CPython

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

Socket Address Format

The following functions use (ipv4_address, port) network addresses, where ipv4_address is a string composed of dots and numbers, such as "8.8.8.8", and port is a number from 1-65535. Note that domain names cannot be used as ipv4_address; domain names 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 text 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 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 family

    • 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 – Socket reusable

  • proto: Protocol number

    • socket.IPPROTO_TCP =6

    • socket.IPPROTO_UDP =17

Normally 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 name (host) and port into a sequence of 5-tuples for creating sockets. The structure of the tuple list 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])

Difference to CPython

When this function encounters an error, it raises a socket.gaierror exception (an OSError subclass). MicroPython does not have socket.gaierror and raises OSError directly. Note: The error numbers for getaddrinfo() form a separate namespace, which may not match the error numbers in the uerrno system error code module. To distinguish getaddrinfo() errors, they are marked with negative numbers, while standard system errors are positive (error numbers can be accessed via the e.args[0] attribute of the exception object). Negative numbers are used temporarily and 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. The remote end will receive an EOF indication if supported by protocol.

Sockets are automatically closed when garbage collected, but it is still recommended to explicitly close them with close() when needed.

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 for connections on the socket, enabling the server to accept connections. If backlog is specified, it must be at least 0 (if 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: Maximum number of pending connections, at least 0. If not specified, a reasonable default value is used.

socket.accept()

Accept a connection request. The socket must be bound to an address and listening for connections. The return value is (conn, address), where conn is a socket for receiving and sending data, and address is the socket bound to the other end.

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

  • address: Address of the client connected to the server

socket.connect(address)

Connect to a remote socket at the specified address.

  • address: Tuple or list of 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. Returns the number of bytes sent, which may be less than the data length (“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 blocks consecutively.

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 writes” 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, since the destination socket is specified by address. Used for UDP communication. Returns the size of data sent.

  • bytes: bytes type data

  • address: Tuple of destination 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 needed 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: Socket option level

  • optname: 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 float representing seconds, or None. If a non-zero value is given, subsequent socket operations will raise an OSError if the timeout period value has been exceeded before the operation completed. If zero is given, the socket is in non-blocking mode. If None is given, the socket is in blocking mode.

Example:

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

Set blocking or non-blocking mode of the socket: if 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 socket.timeout raises an exception in case of a timeout, which is an OSError subclass. MicroPython raises OSError directly. If you use it to catch exceptions, 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 returned type depends on the arguments given to makefile(). Support is limited to binary mode only (‘rb’ and ‘wb’). CPython parameters not supported: encoding, errors, newline.

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.

Difference to CPython

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

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

socket.read([size])

Read size bytes from the socket. Returns a bytes object. If size is not given, it operates in a mode similar to socket.readall(), see below.

socket.readinto(buf[, nbytes])

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

Return value: Number of bytes read and stored in the buffer.

socket.readline()

Receive one line of data, ending at a newline character, and return the received data object.

socket.write(buf)

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

Return value: Number of bytes written.

exception usocket.error

MicroPython does not have this exception.

Difference to CPython

CPython formerly had a socket.error exception which is now deprecated and 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

Socket option level, default=4095