05-09-2022, 08:46 AM
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 in the following sample code snippet?
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 (), execute the code below. For the terminal used in this example, the command prompt is a dollar sign (). Your terminal prompt may be different.
Hit the key on the keyboard to start the installation process.
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.
Method 1: Use urlopen()
This example uses to establish a connection to the URL shown below. In addition, two (2) parameters are passed: a valid URL and a timeout.
This code is wrapped inside a statement. When run, the code drops inside the statement and checks to see if a connection can be established to the indicated URL. This attempt waits three (3) seconds before timing out.
Depending on the connection status, a message indicating the same is output to the terminal.
Output
Method 2: Use requests.get()
This example requires the use of the library and uses to establish a connection to the URL shown below. A status code returns indicating Success or Failure.
This code accepts a URL and attempts to establish a connection to the same. The results of this connection save to as an object.
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
Method 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!
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
Method 4: Use socket
This example requires the library and creates a function to establish a connection to the URL shown below. A Boolean value returns indicating /.
This code defines a new function,. Using a try/except statement attempts to connect to the indicated URL. Depending on the result, the function returns either or .
Finally, the function is called, the code runs, and the result outputs to the terminal.
Output
Summary
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!
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:
- If your computer has access, you want to print .Code:
"Success"
- Otherwise, you want to print .Code:
"Failure"
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:
- Method 1: Use Code:
urlopen()
- Method 2: Use Code:
requests.get()
- Method 3: Use a Lambda
- Method 4: Use Code:
socket
Preparation
Before any data manipulation can occur, one (1) new library will require installation.
- The Requests library allows access to its many methods and makes data manipulation a breeze!
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!

