This is the documentation for the latest development branch of MicroPython and may refer to features that are not available in released versions.

If you are looking for the documentation for a specific release, use the drop-down menu on the left and select the desired version.

socket – socket module

This module implements a subset of the correspondingCPythonmodule,as described below. For more information, refer to the originalCPython documentation:socket.

This module provides access to the BSD socket interface.

Difference to CPython

For efficiency and consistency, socket objects in MicroPython implement astream(file-like) interface directly. In CPython, you need to convert a socket toa file-like object usingmakefile() method. This method is still supportedby MicroPython (but is a no-op), so where compatibility with CPython matters,be sure to use it.

Socket address format(s)

The native socket address format of thesocket module is an opaque data typereturned bygetaddrinfo function, which must be used to resolve textual address(including numeric addresses):

sockaddr=socket.getaddrinfo('www.micropython.org',80)[0][-1]# You must use getaddrinfo() even for numeric addressessockaddr=socket.getaddrinfo('127.0.0.1',80)[0][-1]# Now you can use that addresssock.connect(sockaddr)

Usinggetaddrinfo is the most efficient (both in terms of memory and processingpower) and portable way to work with addresses.

However,socket module (note the difference with native MicroPythonsocket module described here) provides CPython-compatible way to specifyaddresses using tuples, as described below. Note that depending on aMicroPython port,socket module can be builtin or need to beinstalled frommicropython-lib (as in the case ofMicroPython Unix port),and some ports still accept only numeric addresses in the tuple format,and require to usegetaddrinfo function to resolve domain names.

Summing up:

  • Always usegetaddrinfo when writing portable applications.

  • Tuple addresses described below can be used as a shortcut forquick hacks and interactive use, if your port supports them.

Tuple address format forsocket module:

  • IPv4:(ipv4_address, port), whereipv4_address is a string withdot-notation numeric IPv4 address, e.g."8.8.8.8", andport is andinteger port number in the range 1-65535. Note the domain names are notaccepted asipv4_address, they should be resolved first usingsocket.getaddrinfo().

  • IPv6:(ipv6_address, port, flowinfo, scopeid), whereipv6_addressis a string with colon-notation numeric IPv6 address, e.g."2001:db8::1",andport is an integer port number in the range 1-65535.flowinfomust be 0.scopeid is the interface scope identifier for link-localaddresses. Note the domain names are not accepted asipv6_address,they should be resolved first usingsocket.getaddrinfo(). Availabilityof IPv6 support depends on aMicroPython port.

Functions

socket.getaddrinfo(host,port,af=0,type=0,proto=0,flags=0,/)

Translate the host/port argument into a sequence of 5-tuples that contain all thenecessary arguments for creating a socket connected to that service. Argumentsaf,type, andproto (which have the same meaning as for thesocket() function)can be used to filter which kind of addresses are returned. If a parameter is notspecified or zero, all combinations of addresses can be returned (requiringfiltering on the user side).

The resulting list of 5-tuples has the following structure:

(family,type,proto,canonname,sockaddr)

The following example shows how to connect to a given url:

s=socket.socket()# This assumes that if "type" is not specified, an address for# SOCK_STREAM will be returned, which may be not trues.connect(socket.getaddrinfo('www.micropython.org',80)[0][-1])

Recommended use of filtering params:

s=socket.socket()# Guaranteed to return an address which can be connect'ed to for# stream operation.s.connect(socket.getaddrinfo('www.micropython.org',80,0,SOCK_STREAM)[0][-1])

Difference to CPython

CPython raises asocket.gaierror exception (OSError subclass) in caseof error in this function. MicroPython doesn’t havesocket.gaierrorand raises OSError directly. Note that error numbers ofgetaddrinfo()form a separate namespace and may not match error numbers fromtheerrno module. To distinguishgetaddrinfo() errors, they arerepresented by negative numbers, whereas standard system errors arepositive numbers (error numbers are accessible usinge.args[0] propertyfrom an exception object). The use of negative values is a provisionaldetail which may change in the future.

socket.inet_ntop(af,bin_addr)

Convert a binary network addressbin_addr of the given address familyafto a textual representation:

>>>socket.inet_ntop(socket.AF_INET,b"\x7f\0\0\1")'127.0.0.1'
socket.inet_pton(af,txt_addr)

Convert a textual network addresstxt_addr of the given address familyafto a binary representation:

>>>socket.inet_pton(socket.AF_INET,"1.2.3.4")b'\x01\x02\x03\x04'

Constants

socket.AF_INET
socket.AF_INET6

Address family types. Availability depends on a particularMicroPython port.

socket.SOCK_STREAM
socket.SOCK_DGRAM

Socket types.

socket.IPPROTO_UDP
socket.IPPROTO_TCP

IP protocol numbers. Availability depends on a particularMicroPython port.Note that you don’t need to specify these in a call tosocket.socket(),becauseSOCK_STREAM socket type automatically selectsIPPROTO_TCP, andSOCK_DGRAM -IPPROTO_UDP. Thus, the only real use of these constantsis as an argument tosetsockopt().

socket.SOL_*

Socket option levels (an argument tosetsockopt()). The exactinventory depends on aMicroPython port.

socket.SO_*

Socket options (an argument tosetsockopt()). The exactinventory depends on aMicroPython port.

Constants specific to WiPy:

socket.IPPROTO_SEC

Special protocol value to create SSL-compatible socket.

class socket

classsocket.socket(af=AF_INET,type=SOCK_STREAM,proto=IPPROTO_TCP,/)

Create a new socket using the given address family, socket type andprotocol number. Note that specifyingproto in most cases is notrequired (and not recommended, as some MicroPython ports may omitIPPROTO_* constants). Instead,type argument will select neededprotocol automatically:

# Create STREAM TCP socketsocket(AF_INET,SOCK_STREAM)# Create DGRAM UDP socketsocket(AF_INET,SOCK_DGRAM)

Methods

socket.close()

Mark the socket closed and release all resources. Once that happens, all future operationson the socket object will fail. The remote end will receive EOF indication ifsupported by protocol.

Sockets are automatically closed when they are garbage-collected, but it is recommendedtoclose() them explicitly as soon you finished working with them.

socket.bind(address)

Bind the socket toaddress. The socket must not already be bound.

socket.listen([backlog])

Enable a server to accept connections. Ifbacklog is specified, it must be at least 0(if it’s lower, it will be set to 0); and specifies the number of unaccepted connectionsthat the system will allow before refusing new connections. If not specified, a defaultreasonable value is chosen.

socket.accept()

Accept a connection. The socket must be bound to an address and listening for connections.The return value is a pair (conn, address) where conn is a new socket object usable to sendand receive data on the connection, and address is the address bound to the socket on theother end of the connection.

socket.connect(address)

Connect to a remote socket ataddress.

socket.send(bytes)

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

socket.sendall(bytes)

Send all data to the socket. The socket must be connected to a remote socket.Unlikesend(), this method will try to send all of data, by sending datachunk by chunk consecutively.

The behaviour of this method on non-blocking sockets is undefined. Due to this,on MicroPython, it’s recommended to usewrite() method instead, whichhas the same “no short writes” policy for blocking sockets, and will returnnumber of bytes sent on non-blocking sockets.

socket.recv(bufsize[,flags])

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

Most ports support the optionalflags argument. Availableflags are defined as constantsin the socket module and have the same meaning as in CPython.MSG_PEEK andMSG_DONTWAITare supported on all ports which accept theflags argument.

socket.sendto(bytes,address)

Send data to the socket. The socket should not be connected to a remote socket, since thedestination socket is specified byaddress.

socket.recvfrom(bufsize[,flags])

Receive data from the socket. The return value is a pair(bytes, address) wherebytes is abytes object representing the data received andaddress is the address of the socket sendingthe data.

See therecv function for an explanation of the optionalflags argument.

socket.setsockopt(level,optname,value)

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

socket.settimeout(value)

Note: Not every port supports this method, see below.

Set a timeout on blocking socket operations. The value argument can be a nonnegative floatingpoint number expressing seconds, or None. If a non-zero value is given, subsequent socket operationswill raise anOSError exception if the timeout period value has elapsed before the operation hascompleted. If zero is given, the socket is put in non-blocking mode. If None is given, the socketis put in blocking mode.

Not everyMicroPython port supports this method. A more portable andgeneric solution is to useselect.poll object. This allows to wait onmultiple objects at the same time (and not just on sockets, but on genericstream objects which support polling). Example:

# Instead of:s.settimeout(1.0)# time in secondss.read(10)# may timeout# Use:poller=select.poll()poller.register(s,select.POLLIN)res=poller.poll(1000)# time in millisecondsifnotres:# s is still not ready for input, i.e. operation timed out

Difference to CPython

CPython raises asocket.timeout exception in case of timeout,which is anOSError subclass. MicroPython raises an OSError directlyinstead. If you useexceptOSError: to catch the exception,your code will work both in MicroPython and CPython.

socket.setblocking(flag)

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

This method is a shorthand for certainsettimeout() calls:

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

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

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

Return a file object associated with the socket. The exact returned type depends on the argumentsgiven to makefile(). The support is limited to binary modes only (‘rb’, ‘wb’, and ‘rwb’).CPython’s arguments:encoding,errors andnewline are not supported.

Difference to CPython

As MicroPython doesn’t support buffered streams, values ofbufferingparameter is ignored and treated as if it was 0 (unbuffered).

Difference to CPython

Closing the file object returned by makefile() WILL close theoriginal socket as well.

socket.read([size])

Read up to size bytes from the socket. Return a bytes object. Ifsize is not given, itreads all data available from the socket until EOF; as such the method will not return untilthe socket is closed. This function tries to read as much data asrequested (no “short reads”). This may be not possible withnon-blocking socket though, and then less data will be returned.

socket.readinto(buf[,nbytes])

Read bytes into thebuf. Ifnbytes is specified then read at mostthat many bytes. Otherwise, read at mostlen(buf) bytes. Just asread(), this method follows “no short reads” policy.

Return value: number of bytes read and stored intobuf.

socket.readline()

Read a line, ending in a newline character.

Return value: the line read.

socket.write(buf)

Write the buffer of bytes to the socket. This function will try towrite all data to a socket (no “short writes”). This may be not possiblewith a non-blocking socket though, and returned value will be less thanthe length ofbuf.

Return value: number of bytes written.

exceptionsocket.error

MicroPython does NOT have this exception.

Difference to CPython

CPython used to have asocket.error exception which is now deprecated,and is an alias ofOSError. In MicroPython, useOSError directly.