Python to Check Internet Connection with Source Code

A small python script to check internet connectivity.

Prerequisites:

  • Python3

Run the Script:

python3 internet_connection_check.pyCode language: CSS (css)

Source Code:

internet_connection_check.py

import requests
from requests.exceptions import ConnectionError

def internet_connection_test():
	url = 'https://www.google.com/'
	print(f'Attempting to connect to {url} to determine internet connection status.')
	
	try:
		print(url)
		resp = requests.get(url, timeout = 10)
		resp.text
		resp.status_code
		print(f'Connection to {url} was successful.')
		return True
	except ConnectionError as e:
		requests.ConnectionError
		print(f'Failed to connect to {url}.')
		return False
	except:
		print(f'Failed with unparsed reason.')
		return False

internet_connection_test()Code language: PHP (php)

Output:

Leave a Comment