This needs to be fixed properly in socket.getaddrinfo() so it doesn't block indefinitely.
urequests timeout
I currently have a problem that if the wifi is not great a request will hang and hold up the whole script. Is there a way to add a timeout to the request? I don't want to use async requests as the program shouldn't keep running without the current data but i would like to retry the requests until a response is received from the server.
Is there a way to do that?
requests: guard against getaddrinfo() hang when WiFi not connected
Summary
The request() function in requests/__init__.py calls socket.getaddrinfo() (line 81) without verifying network connectivity. On platforms where getaddrinfo() blocks indefinitely when the WiFi interface is active but not connected (see micropython/micropython#18797), this causes the device to freeze with no way to recover except a hard reset.
The timeout parameter passed to requests.get() has no effect because socket.settimeout() is applied to the socket object (line 93) — which is created after getaddrinfo() returns. So the hang occurs before any timeout takes effect.
Suggested fix
Add a connectivity check before getaddrinfo():
# Guard: getaddrinfo() blocks indefinitely on RP2040/RP2350 when the
# CYW43 WiFi interface is active but has no IP address.
try:
import network
_wlan = network.WLAN(network.STA_IF)
if not _wlan.isconnected():
raise OSError(-1, "WiFi not connected")
except ImportError:
pass # Non-WiFi platform, skip guard
ai = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM)
This is wrapped in try/except ImportError so it's safe on non-WiFi platforms (ESP32 Ethernet, Unix port, etc.).
Also consider
A default socket timeout (e.g., 30s) applied before getaddrinfo() would provide defense-in-depth, though it wouldn't help here since settimeout() only affects socket operations, not DNS resolution.
Environment
- Board: Raspberry Pi Pico 2 W (RP2350 + CYW43)
- MicroPython: v1.26.1
- Upstream issue: micropython/micropython#18797
+1
Hi
I have rewritten the library, with some improvements and timeouts.
Do you want to test it ?
After your feedback, I will open source it and propose the new version to the Micropython mantainers.
Sure. Is it your repo?
Hi Taylor
It isn't published on a public repo.
For these first users' feedback, I prefer to "talk" by email.
Write me: massimo.sala.71 AT gmail.com
+1 on wanting a settable timeout. I suspect an os -2 I'm getting is because of a (short) timeout (hard coded) value.
So a
try/exceptblock stops the -2 from crashing the script. I could still use a shorter timeout. My failures are generally because the server I'm GETting from and POSTing to are on the wrong network in the house. Should be quick to establish and the current timeout isn't.+1
hi @mstaffa @MartinPacker @TaylorJayM
I have submitted a fix here.
https://github.com/micropython/micropython-lib/pull/890/files