Update internetConnected.py

Simple function to quickly check, are we connected to the internet.
Returns true or false.
Needed to solve bug where hangs forever on resume from suspend or sleep, due to no longer connected to internet, or IP address change.
This commit is contained in:
Chris Coleman 2017-03-23 21:07:55 -04:00 committed by GitHub
parent 95ac561d94
commit 0f0f182fbe
1 changed files with 8 additions and 17 deletions

View File

@ -1,19 +1,10 @@
import socket
def internetConnected(host="8.8.8.8", port=53, timeout=3):
"""
Simple function to quickly check, are we connected to the internet.
Needed to detect when waking up from sleep or returning from suspend.
Network can take a few seconds to reconnect. Sometimes longer.
Default connect to host: 8.8.8.8 (google-public-dns-a.google.com)
OpenPort: 53/tcp
Service: domain (DNS/TCP)
Average time to check is less than 0.2 second (200 ms).
"""
import requests
def internetConnected(httpshost="www.google.com"):
try:
socket.setdefaulttimeout(timeout)
socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port))
return True
except Exception as ex:
print ex.message
return False
r = requests.get("https://" + httpshost)
except Exception as ex:
return False
return True