![]() |
|
[Tut] How to Check Your Internet Connection in Python? - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] How to Check Your Internet Connection in Python? (/thread-99360.html) |
[Tut] How to Check Your Internet Connection in Python? - xSicKxBot - 05-09-2022 How to Check Your Internet Connection in Python? 5/5 – (1 vote) Problem Formulation and Solution Overview In this article, you’ll learn how to check an Internet Connection in Python. Problem: Given a Python program. You want to check if your computer currently has access to the Internet so you can do some follow-up work. Example:
Specifically, how to implement the function Code: has_connection()Code: if check_connection(): print('Success!')
else: print('Failure!')To make it more fun, we have the following running scenario: Let’s assume you are a Python Coder working for AllTech. Lately, they have been having issues with their internet connections. You are tasked with writing code to check the connection and return a status/error message. Question: How would we write Python code to check to see if an internet connection has been established?We can accomplish this task by one of the following options:
Preparation Before any data manipulation can occur, one (1) new library will require installation.
To install this library, navigate to an IDE terminal. At the command prompt ( Code: $Code: $Code: $ pip install requestsHit the Code: <Enter>If the installation was successful, a message displays in the terminal indicating the same. Feel free to view the PyCharm installation guide for the required library. Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free. Code: from urllib.request import urlopen as url
import requests
import socketMethod 1: Use urlopen() This example uses Code: urlopen()Code: try: url('https://finxter.com/', timeout=3) print('Success')
except ConnectionError as e: print(f'Failure - {e}')This code is wrapped inside a Code: try/exceptCode: tryDepending on the connection status, a message indicating the same is output to the terminal. Output Code: SuccessMethod 2: Use requests.get() This example requires the use of the Code: requestsCode: requests.get()Code: res = requests.get('https://finxter.com/')
print(res) if (res.status_code): print('Success')
else: print('f'Failure')This code accepts a URL and attempts to establish a connection to the same. The results of this connection save to Code: resCode: <Response [200]>This object must be referenced as indicated above to retrieve the status code. Then, the appropriate message is output to the terminal depending on this code. Output Code: SuccessMethod 3: Use a Lambda In the methods above, we used a few lines of code to establish a connection and display the appropriate result. This one-liner accomplishes the same task in one line! Code: # One-Liner to Check Internet Connection:
print((lambda a: 'Success' if 0 == a.system('ping finxter.com -w 4 > clear') else 'Failure')(__import__('os')))This code pings the shown URL and, depending on the results, outputs the appropriate message to the terminal. The remarkable thing is how you can import a library on-the-fly! Output Code: SuccessMethod 4: Use socket This example requires the Code: socketCode: TrueCode: FalseCode: def check_connection(): try: host = socket.gethostbyname('www.google.com') s = socket.create_connection((host, 80), 2) return True except: return False res = check_connection()
print(res)This code defines a new function, Code: check_connectionCode: TrueCode: FalseFinally, the function is called, the code runs, and the result outputs to the terminal. Output Code: TrueSummary These four (4) methods to check the internet connection should give you enough information to select the best one for your coding requirements. Good Luck & Happy Coding! |