Test if an internet connection is present in python

My approach would be something like this:

import socket
REMOTE_SERVER = "one.one.one.one"
def is_connected(hostname):
  try:
    # see if we can resolve the host name -- tells us if there is
    # a DNS listening
    host = socket.gethostbyname(hostname)
    # connect to the host -- tells us if the host is actually reachable
    s = socket.create_connection((host, 80), 2)
    s.close()
    return True
  except Exception:
     pass # we ignore any errors, returning False
  return False
%timeit is_connected(REMOTE_SERVER)
> 31.9 ms ± 627 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

This will return within less than a second if there is no connection (Linux, Python 3.8).

Note: This test can return false positives — e.g. the DNS lookup may return a server within the local network. To be really sure you are connected to the internet, and talking to a valid host, be sure to use more sophisticated methods (e.g. SSL).

Leave a Comment