Python: Code Snippets - Check Internet Connection

Monday 24th July 2017 3:18am

This code snippets checks if the computer has an internet connection:

To run this script copy the code below and save to a file called internet_connection.py

internet_connection.py:


#!/usr/bin/env python
 
# Check Internet Connection
# A quick way to check if computer is
# currently connected to the internet
 
# Date: 07 March 2016
# Written By: Phantom Raspberry Blower

import urllib2  # Module to request web page


class InternetConnection():

    def internet_connected(self, url):
        # Function that checks the internet is available
        try:
            response = urllib2.urlopen(url, timeout=5)
            return True
        except:
            return False

# Check if running stand-alone or imported
if __name__ == '__main__':
    import internet_connection
    it = InternetConnection()
    try:
        if it.internet_connected("http://www.google.co.uk"):
            print("Internet connection is available :)")
        else:
            print("Internet connection not avaiable :(")
    except:
        print("Something wicked happened :(")

Output:

python internet_connection.py
Internet connection is available : )
FB Like & Share