2021-08-21 22:20:11 +00:00
|
|
|
'''
|
|
|
|
networktools
|
|
|
|
============
|
|
|
|
|
|
|
|
This module provides functions for learning the current network status and
|
|
|
|
internal / external IP addresses.
|
|
|
|
'''
|
2021-08-11 08:18:04 +00:00
|
|
|
import requests
|
|
|
|
import socket
|
2021-09-09 04:54:03 +00:00
|
|
|
import time
|
2021-08-11 08:18:04 +00:00
|
|
|
|
|
|
|
from voussoirkit import vlogging
|
|
|
|
|
|
|
|
log = vlogging.getLogger(__name__, 'networktools')
|
|
|
|
|
2021-10-10 19:02:09 +00:00
|
|
|
# This is the IP address we'll use to determine if we have an internet
|
|
|
|
# connection. Change it if this server ever becomes unavailable.
|
|
|
|
INTERNET_IP = '8.8.8.8'
|
|
|
|
|
2021-09-09 04:54:03 +00:00
|
|
|
class NetworkToolsException(Exception):
|
|
|
|
pass
|
|
|
|
|
|
|
|
class NoInternet(NetworkToolsException):
|
|
|
|
pass
|
|
|
|
|
2021-08-11 08:18:04 +00:00
|
|
|
def get_external_ip():
|
|
|
|
url = 'https://voussoir.net/whatsmyip'
|
|
|
|
response = requests.get(url)
|
|
|
|
response.raise_for_status()
|
|
|
|
ip = response.text.strip()
|
|
|
|
return ip
|
|
|
|
|
|
|
|
def get_lan_ip():
|
|
|
|
'''
|
|
|
|
thank you unknwntech
|
|
|
|
https://stackoverflow.com/a/166589
|
|
|
|
'''
|
|
|
|
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
2021-10-10 19:02:09 +00:00
|
|
|
sock.connect((INTERNET_IP, 80))
|
2021-08-11 08:18:04 +00:00
|
|
|
return sock.getsockname()[0]
|
|
|
|
|
|
|
|
def get_gateway_ip():
|
|
|
|
# How to find ip of the router?
|
|
|
|
raise NotImplementedError
|
|
|
|
|
|
|
|
def has_lan():
|
|
|
|
# Open a socket to the router
|
|
|
|
raise NotImplementedError
|
|
|
|
|
|
|
|
def has_internet(timeout=2):
|
|
|
|
socket.setdefaulttimeout(timeout)
|
|
|
|
try:
|
|
|
|
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
2021-10-10 19:02:09 +00:00
|
|
|
sock.connect((INTERNET_IP, 53))
|
2021-08-11 08:18:04 +00:00
|
|
|
return True
|
|
|
|
except socket.error as exc:
|
|
|
|
return False
|
2021-09-09 04:54:03 +00:00
|
|
|
|
|
|
|
def wait_for_internet(timeout):
|
|
|
|
started = time.time()
|
|
|
|
while True:
|
|
|
|
if time.time() - started >= timeout:
|
|
|
|
raise NoInternet()
|
|
|
|
if has_internet(timeout=1):
|
|
|
|
return
|