I'm having a problem with a Python script which should check if the user is connected to a wifi network with a captive portal. Specifically, the script is long-running, attempting to connect to example.org every 60 seconds.
The problem is that if the network starts offline (meaning the  wifi isn't connected at the start of the script), socket.getaddrinfo will always fail with the error "Name or service not known", even once the wifi is connected, until the Python script is restarted. (This isn't a DNS thing -- all requests fail.)
Because both urllib and requests use sockets, it's totally impossible to download an example page once Python gets into this state.
Is there a way around this or a way to reset sockets so it works properly once the network fails?
To be clear, here's a repro:

Disconnect wifi
Run an interactive Python session
import urllib and urllib.open("http://stackoverflow.com/") -- fails as expected
Reconnect wifi
urllib.open("http://example.com/")

Expected: Returned HTML from example.com
Actual: socket.gaierror: [Errno -2] Name or service not known
If you're not connected to an access point when running the script, and don't have an IP address assigned to your device socket.getaddrinfo will fail. Maybe it's still connecting when you run the script. The domain name cannot be resolved because you are not connected to the network, thus no DNS.
Does it fail when you're actually connected to the network? Does curl http://icanhazip.com work at the point when the script fails? Or if you run ifconfig does your device have an IP? (I'm assuming you're on a *nix box).
socket.getaddrinfo fails if network started offline