network — Network configuration
This module provides network drivers and routing configuration. To use this module, you must install a MicroPython variant/build with networking support. Network drivers for specific hardware are available in this module for configuring the hardware network interfaces. The network services provided by the configured interfaces can then be used through the socket module.
For example:
# Connect/display the IP configuration of a specific network interface
# See the specific driver examples below
import network
import time
nic = network.Driver(...)
if not nic.isconnected():
nic.connect()
print("Waiting for connection...")
while not nic.isconnected():
time.sleep(1)
print(nic.ipconfig("addr4"))
# Now use the socket as usual
import socket
addr = socket.getaddrinfo('micropython.org', 80)[0][-1]
s = socket.socket()
s.connect(addr)
s.send(b'GET / HTTP/1.1\r\nHost: micropython.org\r\n\r\n')
data = s.recv(1000)
s.close()
Generic network adapter interface
This section describes the (implicit) abstract base class of all network interface classes, which are implemented by MicroPython ports for different hardware. This means that MicroPython does not actually provide an AbstractNIC class, but any actual NIC class (as described below) implements the methods described here.
- class network.AbstractNIC(id=None, ...)
Instantiate a network interface object. The parameters depend on the network interface. If there are multiple interfaces of the same type, the first parameter should be id.
- AbstractNIC.active([is_active])
If a boolean argument is passed, activate (“up”) or deactivate (“down”) the network interface. Otherwise, if no argument is provided, query the current state. Most other methods require an active interface (the behavior of calling them on an inactive interface is undefined).
- AbstractNIC.connect([service_id, key=None, *, ...])
Connect the interface to a network. This method is optional and only applies to interfaces that are not “always connected”. If no arguments are given, connect to the default (or only) service. If a single argument is given, it is the primary identifier of the service to connect to. It may be accompanied by the key (password) required to access said service. Depending on the network media type and/or specific device, there may be more arbitrary keyword-only arguments. Arguments can be used to: a) specify an alternative service identifier type; b) provide additional connection parameters. For various media types, there are different predefined/recommended argument sets, including:
Wi-Fi: the bssid keyword is used to connect to a specific BSSID (MAC address)
- AbstractNIC.disconnect()
Disconnect from the network.
- AbstractNIC.isconnected()
Return
Trueif connected to a network, otherwise returnFalse.
- AbstractNIC.scan(*, ...)
Scan for available network services/connections. Return a list of tuples with the discovered service parameters. For various network media, there are different predefined/recommended tuple formats, including:
Wi-Fi: (ssid, bssid, channel, RSSI, security, hidden). There may be additional fields specific to a particular device.
This function may accept additional keyword arguments to filter the scan results (for example, scanning for a specific service, a specific channel, a specific set of services, etc.), and to affect the scan duration and other parameters. Where possible, argument names should match those in connect().
- AbstractNIC.status([param])
Query the dynamic status information of the interface. When called with no arguments, the return value describes the network link status. Otherwise, param should be the string name of the specific status parameter to retrieve.
The return type and value depend on the network media/technology. Some parameters that may be supported are:
Wi-Fi STA: use
'rssi'to retrieve the RSSI of the AP signalWi-Fi AP: use
'stations'to retrieve a list of all STAs connected to the AP. The list contains tuples of the form (MAC, RSSI).
- AbstractNIC.ipconfig('param')
- AbstractNIC.ipconfig(param=value, ...)
Get or set interface-specific IP configuration parameters. The supported parameters are as follows (the availability of specific parameters depends on the port and the specific network interface):
dhcp4(True/False) obtain the IPv4 address, gateway and DNS server via DHCP. This method does not block and wait for the address to be obtained. To check whether an address has been obtained, use the read-only attributehas_dhcp4.gw4get/set the IPv4 default gateway.dhcp6(True/False) obtain the DNS server via stateless DHCPv6. Obtaining an IP address via DHCPv6 is not currently implemented.autoconf6(True/False) obtain a stateless IPv6 address via the network prefix shared in router advertisements. To check whether a stateless address has been obtained, use the read-only attributehas_autoconf6.addr4(e.g.192.168.0.4/24) get the current IPv4 address and network mask as an(ip, subnet)tuple, regardless of how this address was obtained. This method can be used to set a static IPv4 address, either as an(ip, subnet)tuple or in CIDR notation.addr6(e.g.fe80::1234:5678) get the current list of IPv6 addresses as(ip, state, preferred_lifetime, valid_lifetime)tuples. This includes link-local, SLAAC and static addresses.preferred_lifetimeandvalid_lifetimeindicate the remaining valid and preferred lifetimes (in seconds) of each IPv6 address.stateindicates the current state of the address:0x08-0x0findicate the address is tentative, counting the number of probes sent.0x10the address is deprecated (but still valid)0x30the address is preferred (and valid)0x40the address is duplicate and cannot be used.
This method can be used to set a static IPv6 address by setting this parameter to the address, such as
fe80::1234:5678.
- AbstractNIC.ifconfig([(ip, subnet, gateway, dns)])
Note
This function is deprecated; please use ipconfig() instead.
Get/set IP-level network interface parameters: the IP address, subnet mask, gateway and DNS server. When called with no arguments, this method returns a 4-tuple containing the above information. To set the above values, pass a 4-tuple containing the desired information. For example:
nic.ifconfig(('192.168.0.4', '255.255.255.0', '192.168.0.1', '8.8.8.8'))
- AbstractNIC.config('param')
- AbstractNIC.config(param=value, ...)
Get or set general network interface parameters. These methods allow handling parameters beyond the standard IP configuration (which is handled by ipconfig()). These include network-specific and hardware-specific parameters. For setting parameters, keyword argument syntax should be used, and multiple parameters can be set at once. For querying, the parameter name should be referenced as a string, and only one parameter can be queried at a time:
# Set the Wi-Fi access point name (formally known as SSID) and Wi-Fi channel ap.config(ssid='My AP', channel=11) # Query the parameters one by one print(ap.config('ssid')) print(ap.config('channel'))
Specific network class implementations
The following concrete classes implement the AbstractNIC interface and provide methods for controlling various types of network interfaces.
Network functions
The following are the functions available in the network module.
- network.country([code])
Get or set the two-letter ISO 3166-1 Alpha-2 country code used for radio compliance.
If the code argument is provided, the country will be set to this value. If the function is called with no arguments, it returns the current country.
The default code
"XX"represents the “worldwide” region.
- network.hostname([name])
Get or set the hostname that will identify this device on this network. It will be used by all interfaces.
- This hostname is used for:
Sending to the DHCP server in client requests. (if DHCP is used)
Broadcasting via mDNS. (if enabled)
If the name argument is provided, the hostname will be set to this value. If the function is called with no arguments, it returns the current hostname.
Changes to the hostname are usually only applied during connection. For DHCP, this is because the hostname is part of the DHCP client request, and the mDNS implementation in most ports initializes the hostname only once during connection. Therefore, you must set the hostname before activating/connecting the network interface.
The length of the hostname is limited to 32 characters. A MicroPython port may choose to set a lower limit for memory reasons. If the given name does not fit, a ValueError will be raised.
The default hostname is usually the name of the board.
- network.ipconfig('param')
- network.ipconfig(param=value, ...)
Get or set global IP configuration parameters. The supported parameters are as follows (the availability of specific parameters depends on the port and the specific network interface):
dnsget/set the DNS server. This method can support both IPv4 and IPv6 addresses.prefer(4/6) specify which address type to return if a domain name has both A and AAAA records. Note that this does not clear the local DNS cache, so any previously obtained address may not change.
- network.phy_mode([mode])
Get or set the PHY mode.
If the mode argument is provided, the PHY mode will be set to this value. If the function is called with no arguments, it returns the current PHY mode.
- The possible modes are defined as constants:
MODE_11B– IEEE 802.11b,MODE_11G– IEEE 802.11g,MODE_11N– IEEE 802.11n.
Availability: ESP8266.