How to See If There's an Available and Active Network Connection in Python

How can I see if there's an available and active network connection in Python?

Perhaps you could use something like this:

import urllib2

def internet_on():
try:
urllib2.urlopen('http://216.58.192.142', timeout=1)
return True
except urllib2.URLError as err:
return False

Currently, 216.58.192.142 is one of the IP addresses for google.com. Change http://216.58.192.142 to whatever site can be expected to respond quickly.

This fixed IP will not map to google.com forever. So this code is
not robust -- it will need constant maintenance to keep it working.

The reason why the code above uses a fixed IP address instead of fully qualified domain name (FQDN) is because a FQDN would require a DNS lookup. When the machine does not have a working internet connection, the DNS lookup itself may block the call to urllib_request.urlopen for more than a second. Thanks to @rzetterberg for pointing this out.


If the fixed IP address above is not working, you can find a current IP address for google.com (on unix) by running

% dig google.com  +trace 
...
google.com. 300 IN A 216.58.192.142

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).

Checking internet connection with Python

you should do something like

def check_internet():
for timeout in [1,5,10,15]:
try:
print "checking internet connection.."
socket.setdefaulttimeout(timeout)
host = socket.gethostbyname("www.google.com")
s = socket.create_connection((host, 80), 2)
s.close()
print 'internet on.'
return True

except Exception,e:
print e
print "internet off."
return False

or even better (mostly taken from other answer linked in comments)

def internet_on():
for timeout in [1,5,10,15]:
try:
response=urllib2.urlopen('http://google.com',timeout=timeout)
return True
except urllib2.URLError as err: pass
return False

How to check if user is connected to internet in python?

You could do something like this where you check for connection to a site.

import urllib.request 
import urllib.parse

try:
x = urllib.request.urlopen('https://www.google.com')
except Exception as e:
print(str(e))

python wait until connection active

Definitely don't do it recursively. Use a loop instead:

def wait_for_internet_connection():
while True:
try:
response = urllib2.urlopen('http://74.125.113.99',timeout=1)
return
except urllib2.URLError:
pass

def main():
...

wait_for_internet_connection()
main()


Related Topics



Leave a reply



Submit