Best way to check if there is internet?

Chris Angelico rosuav at gmail.com
Wed Feb 23 12:31:11 EST 2022


On Thu, 24 Feb 2022 at 03:39, Akkana Peck <akkana at shallowsky.com> wrote:
>
> 2QdxY4RzWzUUiLuE at potatochowder.com writes:
> > I think someone said it way upthread:  don't check, just do whatever you
> > came to do, and it will work or it will fail (presumably, your program
> > can tell the difference, regardless of a past snapshot of being able to
> > retrieve data from an arbitrary URL).
> >
> > EAFP, anyone?
>
> Yes, but the code being discussed is still helpful, if only for
> error handling: yes, the network isn't fully up, but *why" isn't it?
>
> while True:
>     try:
>         do_whatever_I_came_to_do()
>     except NetworkError:
>         net_config_with_good_error_detection()

That's fair, although the NetworkError should at least be able to
distinguish between "no DNS server", "DNS server returned error",
"timeout connecting", "host not found", "network not found",
"connection refused", etc.

> Aside from error handling, it's useful in a network-up script:
> when you've just enabled a network, it's good to check right then if
> there's a captive portal and deal with it.

That's a little harder to recognize, since there are so many ways that
it can be done. Do all HTTP requests return 302 redirects? Do all
requests return a static HTML page? What do non-HTTP requests return?
I don't know that there's a generic way to recognize those kinds of
login screens.

> If you just assume that
> the first thing the user wants is to go to an http: page in a
> browser, and so don't bother to check for a captive portal,
> that'll be annoying for people who want to fetch IMAP mail,
> or run ssh, or load an https: page.

Agreed, it is annoying, especially when those logins time out after
fifteen minutes and force you to watch another ad before they let you
use the connection. But it's still extremely hard to recognize
reliably, so you'd probably end up coding something for the specific
portal that you are experienced with.

ChrisA


More information about the Python-list mailing list