Add networktools.wait_for_internet.

This commit is contained in:
voussoir 2021-09-08 21:54:03 -07:00
parent 0274b9d4a5
commit d37e6fdf0b
No known key found for this signature in database
GPG key ID: 5F7554F8C26DACCB

View file

@ -7,11 +7,18 @@ internal / external IP addresses.
''' '''
import requests import requests
import socket import socket
import time
from voussoirkit import vlogging from voussoirkit import vlogging
log = vlogging.getLogger(__name__, 'networktools') log = vlogging.getLogger(__name__, 'networktools')
class NetworkToolsException(Exception):
pass
class NoInternet(NetworkToolsException):
pass
def get_external_ip(): def get_external_ip():
url = 'https://voussoir.net/whatsmyip' url = 'https://voussoir.net/whatsmyip'
response = requests.get(url) response = requests.get(url)
@ -44,3 +51,11 @@ def has_internet(timeout=2):
return True return True
except socket.error as exc: except socket.error as exc:
return False return False
def wait_for_internet(timeout):
started = time.time()
while True:
if time.time() - started >= timeout:
raise NoInternet()
if has_internet(timeout=1):
return