Skip to content

esp32 network: Add a fixed IPv4 address to Ethernet - #2484

Open
gabrielmancini wants to merge 2 commits into
atomvm:release-0.7from
iobee-io:esp32-eth-static-ip
Open

gabrielmancini wants to merge 2 commits into
atomvm:release-0.7from
iobee-io:esp32-eth-static-ip

Conversation

@gabrielmancini

Copy link
Copy Markdown

Adds an {ipv4, {Address, Netmask, Gateway}} option to the eth configuration of network:start/1 on ESP32. With it, the Ethernet netif uses a fixed address instead of DHCP.

Use case

The cable goes to a field network with fixed addresses and no DHCP server, such as a PLC or a dosing pump speaking Modbus TCP, while STA or PPP stay the way out. A gateway of {0, 0, 0, 0} and a route_priority below theirs keep the default route on them:

{eth, [..., {route_priority, 2}, {ipv4, {{10, 10, 0, 50}, {255, 255, 255, 0}, {0, 0, 0, 0}}}]}

How

The address is set on the netif, with the DHCP client stopped, before the link comes up. esp_netif's connected action then sees a stopped client and a valid static address, and posts ETH_GOT_IP itself, so got_ip still fires as with DHCP.

The DHCP client never starts. This matters because esp_netif_dhcpc_start calls dns_clear_servers, and lwIP's DNS servers are global. A first version started the client on link up and stopped it right after. That wiped the DNS servers the STA had obtained, and the station lost name resolution.

Tests

  • Built for ESP32 with CONFIG_AVM_ENABLE_ETHERNET=y.
  • clang-format 16 adds no new findings to network_driver.c, and erlfmt passes on network.erl.
  • Hardware: an ESP32 LilyGO T-Internet-COM (LAN8720), with eth at 10.10.0.50/24 cabled straight to a PC at 10.10.0.11, and STA up at the same time.
    • The PC pings the board.
    • A Modbus TCP client on the board reads the PC over the cable.
    • TLS and MQTT stay up over STA, with DNS intact.

The docs (Ethernet options table) and the CHANGELOG are updated.

These changes are made under both the "Apache 2.0" and the "GNU Lesser General
Public License 2.1 or later" license terms (dual license).

SPDX-License-Identifier: Apache-2.0 OR LGPL-2.1-or-later

An {ipv4, {Address, Netmask, Gateway}} option in the eth config sets a
fixed address instead of DHCP. It is set on the netif with the DHCP
client stopped before the link comes up, so esp_netif's connected action
posts ETH_GOT_IP itself and the client never starts: starting it, even
to stop it right after, clears the DNS servers, which lwIP shares with
the other netifs, and the station lost name resolution.

A gateway of {0, 0, 0, 0} is none, for a cable to a field network (a PLC
or a pump with a fixed address) that is not the way out; route_priority
keeps the default route on Wi-Fi or PPP.

Signed-off-by: Gabriel Mancini <gabriel.mancini@gmail.com>
@petermm

petermm commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

AMP code:

review last commit, ask the oracle, write findings to PR_REVIEW.md in markdown, include code diffs for small fixes/suggestions/missing tests.

Review: fixed IPv4 for ESP32 Ethernet

Commit: c73cacef067ddad1fc7e429c1202fd6360d5d64f — esp32 network: Add a fixed IPv4 address to Ethernet
Scope: HEAD versus HEAD^, including the Ethernet startup/event lifecycle, Erlang API, documentation, and existing ESP32 tests.
Recommendation: Request changes. One high-priority DNS defect and one medium-priority configuration-validation defect.

The oracle performed an independent read-only review. Both findings below were then checked against the repository and local ESP-IDF v5.5.5 source. The local v6.1-development checkout also contains the DNS-clearing setter. These are source-confirmed findings, not hardware reproductions. No firmware build, emulator run, or device test was performed. Suggested patches below are not applied.

1. [P1] Setting the static address still clears shared DNS

Location: src/platforms/esp32/components/avm_builtins/network_driver.c:1624–1626.

The new static-address path stops DHCP and then calls esp_netif_set_ip_info(). However, the netif retains ESP_NETIF_DHCP_CLIENT from ESP_NETIF_INHERENT_DEFAULT_ETH(). For a netif with that flag, ESP-IDF's setter calls dns_clear_servers(true) after checking that DHCP is stopped. Stopping DHCP therefore does not prevent this setter from clearing the main and backup DNS servers. The fallback server is preserved.

This directly defeats the change's stated DNS-preservation goal. A concrete failing ordering is:

  1. Start STA and static Ethernet together, with Ethernet route priority below STA's 100.
  2. STA obtains DHCP-supplied DNS while Ethernet initializes its PHY. This ordering is possible because start_network() starts Wi-Fi before Ethernet (network_driver.c:2143–2156), and Ethernet initialization waits for hardware.
  3. Ethernet's new esp_netif_set_ip_info() call clears the shared main/backup DNS entries. STA can remain the default route, but uncached hostname lookups fail if no usable fallback DNS server exists. Ethernet does not need a connected cable to trigger the clearing.

The schedule is conditional; the destructive setter call itself is unconditional on link state and is confirmed in the SDK source. A later STA DHCP response can mask the problem by repopulating DNS.

Supporting SDK source (relative to /Users/petermm/esp/esp-idf-v5.5.5/):

  • components/esp_netif/include/esp_netif_defaults.h:85–95: Ethernet's default DHCP-client flag.
  • components/esp_netif/lwip/esp_netif_lwip.c:1981–1991: the stopped-DHCP check followed by DNS clearing in esp_netif_set_ip_info_api().
  • components/esp_netif/lwip/esp_netif_lwip.c:1589–1599: main/backup clearing while preserving fallback.
  • components/esp_netif/lwip/esp_netif_lwip.c:667–677: netif creation copies base->ip_info directly, without using the setter.

Suggested small fix

Supply the static address in the netif creation configuration instead of calling the DNS-clearing setter. Retain the DHCP stop before starting Ethernet: it transitions the new client's state from INIT to STOPPED without starting DHCP or discarding the configured address.

diff --git a/src/platforms/esp32/components/avm_builtins/network_driver.c b/src/platforms/esp32/components/avm_builtins/network_driver.c
--- a/src/platforms/esp32/components/avm_builtins/network_driver.c
+++ b/src/platforms/esp32/components/avm_builtins/network_driver.c
@@
     esp_netif_inherent_config_t netif_base = ESP_NETIF_INHERENT_DEFAULT_ETH();
     netif_base.route_prio = route_priority;
+    if (data->eth_static) {
+        netif_base.ip_info = &data->eth_ip;
+    }
     esp_netif_config_t netif_config = { .base = &netif_base, .driver = NULL, .stack = ESP_NETIF_NETSTACK_DEFAULT_ETH };
@@
         err = esp_netif_dhcpc_stop(data->eth_netif);
-        if ((err != ESP_OK && err != ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED)
-            || (err = esp_netif_set_ip_info(data->eth_netif, &data->eth_ip)) != ESP_OK) {
+        if (err != ESP_OK && err != ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED) {
             goto error;
         }

Do not simply remove ESP_NETIF_DHCP_CLIENT: esp_netif_action_connected() returns early without that flag, bypassing the static got_ip event (components/esp_netif/esp_netif_handlers.c:35–74). With the flag retained and DHCP stopped, it emits got_ip for a valid static address.

Required regression: In an isolated ESP32/OpenETH integration fixture, initialize the network stack, seed distinct main and backup DNS servers, start only static Ethernet through the public network API, and assert that both entries remain unchanged. For example, use main 192.0.2.53 and backup 198.51.100.53; do not rely only on cached hostname lookups or a fallback server. Coordinate the native fixture so DNS is seeded before the new setter would run. Do not wrap the entire existing test_eth suite in this assertion: its DHCP cases can legitimately change DNS. Test mixed STA/static-Ethernet startup separately with STA winning the route priority.

2. [P2] Reject zero address/netmask before reporting successful startup

Location: src/platforms/esp32/components/avm_builtins/network_driver.c:1457–1463.

eth_static_ip() accepts any three syntactically valid IPv4 tuples, including a zero address or zero netmask. ESP-IDF's setter accepts them, but its connected handler later calls esp_netif_is_valid_static_ip(), which explicitly rejects either zero value. It logs invalid static ip and never posts IP_EVENT_ETH_GOT_IP. DHCP is stopped, so there is no alternative address-acquisition path.

For example, on a working link these configurations make network:wait_for_eth(Config, 1000) return {error, timeout} instead of promptly rejecting an unusable configuration:

[{ipv4, {{0, 0, 0, 0}, {255, 255, 255, 0}, {0, 0, 0, 0}}}]
[{ipv4, {{10, 0, 2, 42}, {0, 0, 0, 0}, {0, 0, 0, 0}}}]

Evidence: components/esp_netif/lwip/esp_netif_lwip.c:1944–1950 rejects zero address or netmask; components/esp_netif/esp_netif_handlers.c:48–74 only emits got_ip when that check succeeds. libs/avm_network/src/network.erl:1313–1327 waits for the event or times out.

Suggested small fix

Match the SDK's minimum static-address validity requirement before initializing hardware. Keep zero gateway valid. This intentionally rejects /0 because the SDK's static-event path does not support it; it does not propose broader subnet-policy validation.

diff --git a/src/platforms/esp32/components/avm_builtins/network_driver.c b/src/platforms/esp32/components/avm_builtins/network_driver.c
--- a/src/platforms/esp32/components/avm_builtins/network_driver.c
+++ b/src/platforms/esp32/components/avm_builtins/network_driver.c
@@
     if (!term_is_tuple(ipv4) || term_get_tuple_arity(ipv4) != 3
         || !term_to_ip4(term_get_tuple_element(ipv4, 0), &data->eth_ip.ip)
         || !term_to_ip4(term_get_tuple_element(ipv4, 1), &data->eth_ip.netmask)
-        || !term_to_ip4(term_get_tuple_element(ipv4, 2), &data->eth_ip.gw)) {
+        || !term_to_ip4(term_get_tuple_element(ipv4, 2), &data->eth_ip.gw)
+        || data->eth_ip.ip.addr == 0
+        || data->eth_ip.netmask.addr == 0) {
         return false;
     }

Missing tests: suggested public-interface coverage

The commit adds no tests. Extend src/platforms/esp32/test/main/test_erl_sources/test_eth.erl, which already covers OpenETH DHCP, invalid configuration, event ordering, and stop/start. The following patch adds malformed/boundary cases and verifies exact static address reporting across two complete start/stop cycles. The zero-address/netmask cases should fail on HEAD and pass after finding 2 is fixed. The successful-static cases are controls, not detectors of finding 1.

diff --git a/src/platforms/esp32/test/main/test_erl_sources/test_eth.erl b/src/platforms/esp32/test/main/test_erl_sources/test_eth.erl
--- a/src/platforms/esp32/test/main/test_erl_sources/test_eth.erl
+++ b/src/platforms/esp32/test/main/test_erl_sources/test_eth.erl
@@
 start() ->
     ok = test_badarg(),
     ok = test_wait_for_eth_refused(),
+    ok = test_static_ip(),
     ok = test_callbacks_in_order(),
@@
-        [{route_priority, 256}]
+        [{route_priority, 256}],
+        [{ipv4, invalid}],
+        [{ipv4, {{10, 0, 2, 42}, {255, 255, 255, 0}}}],
+        [{ipv4, {{10, 0, 42}, {255, 255, 255, 0}, {0, 0, 0, 0}}}],
+        [{ipv4, {{10, 0, 2, -1}, {255, 255, 255, 0}, {0, 0, 0, 0}}}],
+        [{ipv4, {{10, 0, 2, 42}, {255, 255, 255, 256}, {0, 0, 0, 0}}}],
+        [{ipv4, {{10, 0, 2, 42}, {255, 255, 255, 0}, {0, 0, 0, 1 bsl 40}}}],
+        [{ipv4, {{0, 0, 0, 0}, {255, 255, 255, 0}, {0, 0, 0, 0}}}],
+        [{ipv4, {{10, 0, 2, 42}, {0, 0, 0, 0}, {0, 0, 0, 0}}}]
     ]).
@@
-%% Pid callbacks are sent from the network gen_server itself, so they arrive in
+test_static_ip() ->
+    IpInfo = {{10, 0, 2, 42}, {255, 255, 255, 0}, {0, 0, 0, 0}},
+    lists:foreach(
+        fun(_) ->
+            {ok, IpInfo} = network:wait_for_eth([{ipv4, IpInfo}], 5000),
+            connected = network:eth_status(),
+            ok = network:stop()
+        end,
+        [first, second]
+    ).
+
+%% Pid callbacks are sent from the network gen_server itself, so they arrive in
 %% the order of the driver events.

Also exercise static started → connected → got_ip callbacks with the exact configured tuple, unplug/replug with no DHCP server, and a nonzero gateway. Verify that mixed-interface traffic uses STA/PPP while same-subnet traffic reaches the Ethernet peer. These remain integration-validation gaps, not additional confirmed defects. Keep the existing no-ipv4 DHCP tests unchanged to detect regressions in the default path.

Small documentation suggestions (non-blocking)

The Ethernet got_ip table entry and wait_for_eth/2 API documentation still describe DHCP only. The newly extended malformed-configuration sentence also promises a synchronous error from network:start/1, but network:init/1 defers port startup to handle_continue/2; the existing expect_badarg/1 test monitors {start_port_failed, badarg} after {ok, Pid}. Document the observable behavior rather than relying on callers to discover it.

diff --git a/doc/src/network-programming-guide.md b/doc/src/network-programming-guide.md
--- a/doc/src/network-programming-guide.md
+++ b/doc/src/network-programming-guide.md
@@
-Invalid pins, a `phy_addr` out of range or a malformed `ipv4` make `network:start/1` return
-`{error, badarg}`.
+Invalid pins, a `phy_addr` out of range or an invalid `ipv4` make the network server terminate
+with `{start_port_failed, badarg}` after `network:start/1` returns `{ok, Pid}`.
+`network:wait_for_eth/2` monitors startup and returns `{error, badarg}` instead.

In the Ethernet table, replace “DHCP lease obtained” with “IPv4 address ready (DHCP or static)”. In wait_for_eth/2's EDoc, replace “the link to come up and DHCP to assign an address” with “the link to come up and an IPv4 address to become available”. Clarify that the static address and netmask must be nonzero once finding 2 is fixed.

Review boundaries

  • No octet truncation defect found: term_is_integer() accepts unboxed integers only, and the code checks 0..255 before casting; boxed out-of-range integers are rejected.
  • Zero gateway is intentionally supported; it must not be rejected alongside zero address/netmask.
  • The suggested DNS fix preserves the DHCP-client flag specifically to retain SDK-generated static got_ip events.
  • Proposed code/test diffs require compilation and execution in the ESP32/OpenETH suite before merge. The dual-interface DNS/routing schedule and physical cable-cycle behavior have not been runtime-tested in this review.
  • Only this review document was added; no production fixes or test changes were applied.

@gabrielmancini

Copy link
Copy Markdown
Author

Thanks for the review. Both findings are fixed in a new commit on top (esp32 network: Keep DNS with a fixed Ethernet address, reject zeros).

1. [P1] DNS cleared by the setter. Confirmed in IDF 5.5.5 esp_netif_set_ip_info_api(): for a netif with the DHCP client flag, dns_clear_servers(true) runs even with the client stopped. As you suggested:

  • the address now goes in netif_base.ip_info, which esp_netif_new() copies without the setter;
  • esp_netif_dhcpc_stop() stays before esp_eth_start();
  • the DHCP flag stays too, so esp_netif_action_connected() still posts ETH_GOT_IP.

Regression: a new native case, test_eth_static_dns. It seeds main 192.0.2.53 and backup 198.51.100.53 on the lwIP thread, starts a fixed address through network:wait_for_eth/2, stops, and checks that both entries are unchanged. It is a separate test module, so the DHCP cases in test_eth cannot mask it.

I ran the ESP32 suite in QEMU (IDF 5.5.5, OpenETH):

  • with the fix, test_eth, test_eth_static_dns and test_eth_teardown pass;
  • with the old setter path restored, test_eth_static_dns fails on the DNS assertion, so the test detects the defect.

test_socket fails on this machine with or without the change, because of its local network environment. It is unrelated.

2. [P2] Zero address or netmask. These are now refused with badarg before any hardware is touched. A zero gateway is still valid.

Tests. Your test_eth additions are in:

  • the malformed and zero ipv4 cases in test_badarg;
  • test_static_ip, which runs two start/stop cycles that check the exact reported tuple and eth_status/0.

Docs.

  • The got_ip row now reads "IPv4 address ready (DHCP or ipv4)".
  • The wait_for_eth/2 EDoc says "an IPv4 address to become available (by DHCP, or the ipv4 option)".
  • The bad-configuration sentence now describes the observable behaviour: the server terminates with {start_port_failed, badarg} after network:start/1 returns {ok, Pid}, and wait_for_eth/2 returns {error, badarg}.

Not covered here: unplug/replug without a DHCP server, and mixed STA plus static Ethernet routing. Our fleet runs that combination on hardware (Wi-Fi uplink with route priority 100, fixed Ethernet to a Modbus device with priority 2). I will move those boards to this commit and report back.

@gabrielmancini

Copy link
Copy Markdown
Author

Hardware follow-up: the fix is on an ESP32 without PSRAM in our fleet. It runs Wi-Fi STA as the uplink (route priority 100) and a fixed Ethernet address 10.10.0.50/24 with no gateway (priority 2) to a Modbus TCP peer at 10.10.0.11. Results after a cold boot:

  • the static got_ip arrives;
  • SNTP resolves its server by name, so the DNS from the STA lease survived;
  • the device reaches its cloud services over Wi-Fi;
  • the Modbus link over the cable is open, and the peer pings the board at about 1.3 ms.

Same-subnet traffic goes to the Ethernet peer, and everything else goes over the STA.

esp_netif_set_ip_info() clears lwIP's main and backup DNS servers for a
netif with the DHCP client flag, even with the client stopped, and lwIP
shares them with every interface: a fixed Ethernet address started next
to Wi-Fi could wipe the DNS servers the STA got. The address is now given
at netif creation (esp_netif_new copies base->ip_info without the
setter). The DHCP client is still stopped before the link comes up, and
the flag kept: without it esp_netif_action_connected() returns before it
posts ETH_GOT_IP.

A zero address or netmask is refused with badarg: the SDK's connected
handler rejects them as an invalid static IP and never posts got_ip, so
wait_for_eth/2 timed out instead.

Tests: test_eth gains malformed and zero ipv4 cases and two start/stop
cycles of a fixed address; the new native test_eth_static_dns seeds the
DNS servers, starts a fixed address and checks both are kept (it fails
with the setter). The guide and wait_for_eth/2 docs say got_ip is DHCP
or fixed, and that a bad configuration terminates the network server
with {start_port_failed, badarg} while wait_for_eth/2 returns
{error, badarg}.

Signed-off-by: Gabriel Mancini <gabriel.mancini@gmail.com>
@gabrielmancini

Copy link
Copy Markdown
Author

Formatting-only amend: the clang-format-prettier-check failure was the include order in test_main.c (<lwip/dns.h> now after <esp_vfs_fat.h>). The commit is now d0df0106, with the same content as 20e7168c otherwise. Checked locally with clang-format 16.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants