Function internetConnected() returns True or False

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-01 15:59:57 -05:00 committed by GitHub
parent c1df95b7d3
commit 95ac561d94
1 changed files with 19 additions and 0 deletions

View File

@ -0,0 +1,19 @@
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).
"""
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