1

How do I check if a python3 module is connected to the internet?

I saw this is solution for Python2 and wanted to do something similar.

Sam Murphy
  • 815
  • 11
  • 23
  • 2
    Possible duplicate of [Test if an internet connection is present in python](https://stackoverflow.com/questions/20913411/test-if-an-internet-connection-is-present-in-python) – Mihai Chelaru May 28 '18 at 01:39

5 Answers5

5

The following snippet worked for me.

from urllib.request import urlopen

def internet_on():
   try:
        response = urlopen('https://www.google.com/', timeout=10)
        return True
    except: 
        return False

Improved error handling and/or other configurations might be required for other use cases.

Sam Murphy
  • 815
  • 11
  • 23
  • 2
    Good job on managing to find a solution working on the code in the question linked. Did you try running the code in the accepted answer (or a few of the other answers)? They should also be able to run successfully in Python 3 (although I appreciate that the code provided in the question will not). – Nick is tired May 28 '18 at 01:45
  • The top voted solution works in Python3. I was looking for a urllib2 equivalent, however, as I find it neater. Embarrassingly, that is also posted on the original thread (!). I had missed it because I searched for the term python3 (to no avail). Should I delete this post? – Sam Murphy May 29 '18 at 03:24
  • You could, but better would be to accept the proposed duplicate (you should see a yellow dialog box by your question saying there is a suggested duplicate, with the button "yes this answers my question" or something similar). That way future users with the same question can use this as a sign post to find a solution – Nick is tired May 29 '18 at 04:26
  • @SamMurphy Is there any other way to check internet running status. Because if you pining `google.com` again again, then they will block our IP. So Is there any other waya.? – Sanjiv Aug 21 '19 at 08:29
  • 1
    @Sanjiv it depends how often you need to check the internet connection is working. I was using it on a personal project (so safe from getting blocked by google) but you you might have, or want to scale to, many users. In that case you should probably set up your own server. The easiest way would be to use a service like netlify or heroku (they both have free tiers). Then you could ping that url instead of google.com. – Sam Murphy Aug 22 '19 at 09:14
  • a friend of mine just showed me you can switch google.com for this site http://amionline.net/ – Sam Murphy Aug 22 '19 at 14:40
0

You can check also only the hostname if is online: (useful is the url is an API and needs a POST, instead of a GET)

def have_internet(url):
   try:
      o = urlparse(url)
      response = urlopen(o.scheme+'://'+o.netloc, timeout=5)
      return True
   except:
      print('No access to',url)
      return False
Imran
  • 5,542
  • 3
  • 23
  • 46
Isidoros Moulas
  • 520
  • 3
  • 10
0

this is for python3 . I am using this for a while now.

import socket,time
mem1 = 0
while True:
    try:
            host = socket.gethostbyname("www.google.com") #Change to personal choice of site
            s = socket.create_connection((host, 80), 2)
            s.close()
            mem2 = 1
            if (mem2 == mem1):
                pass #Add commands to be executed on every check
            else:
                mem1 = mem2
                print ("Internet is working") #Will be executed on state change

    except Exception as e:
            mem2 = 0
            if (mem2 == mem1):
                pass
            else:
                mem1 = mem2
                print ("Internet is down")
    time.sleep(10) #timeInterval for checking
desertnaut
  • 57,590
  • 26
  • 140
  • 166
0

We use the following code to test the internet connection. Here generate_204 will generate code 204 when the internet is connected or else give errors.

import requests

url = 'http://clients3.google.com/generate_204'

try:
    response = requests.get(url, timeout=5)
    if response.status_code == 204:
        print(response.status_code)
        response.raise_for_status()
except requests.exceptions.RequestException as err:
    print("OOps: Something Else", err)
except requests.exceptions.HTTPError as errh:
    print("Http Error:", errh)
except requests.exceptions.ConnectionError as errc:
    print("Error Connecting:", errc)
except requests.exceptions.Timeout as errt:
    print("Timeout Error:", errt)
S Habeeb Ullah
  • 968
  • 10
  • 15
-1
response = urlopen('https://www.google.com/', timeout=10)
print(response)
<http.client.HTTPResponse object at 0x0000024E196C9CC0>

so..

import sys
from urllib.request import urlopen

response = urlopen('https://www.google.com/', timeout=10)

if response == "<http.client.HTTPResponse object at 0x0000024E196C9CC0>":
    print("Ok!")
else:
    print("NO!!!")
Pang
  • 9,564
  • 146
  • 81
  • 122