05-09-2022, 08:46 AM
How to Check Your Internet Connection in Python?
<div><div class="kk-star-ratings kksr-valign-top kksr-align-left " data-payload="{"align":"left","id":"339914","slug":"default","valign":"top","reference":"auto","count":"1","readonly":"","score":"5","best":"5","gap":"5","greet":"Rate this post","legend":"5\/5 - (1 vote)","size":"24","width":"142.5","_legend":"{score}\/{best} - ({count} {votes})"}">
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 142.5px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend"> 5/5 – (1 vote) </div>
</div>
<h2 class="wp-embed-aspect-16-9 wp-has-aspect-ratio">Problem Formulation and Solution Overview</h2>
<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">In this article, you’ll learn how to check an Internet Connection in Python.</p>
<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio"><strong>Problem</strong>: 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. </p>
<p><strong>Example:</strong></p>
<ul>
<li>If your computer has access, you want to print <code>"Success"</code>. </li>
<li>Otherwise, you want to print <code>"Failure"</code>. </li>
</ul>
<p>Specifically, how to implement the function <code>has_connection()</code> in the following sample code snippet?</p>
<pre class="wp-block-preformatted"><code>if <strong>check_connection()</strong>: print('Success!')
else: print('Failure!')</code></pre>
<hr class="wp-block-separator"/>
<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">To make it more fun, we have the following running scenario:</p>
<p>Let’s assume you are a Python Coder working for <strong>AllTech</strong>. 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.</p>
<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio has-global-color-8-background-color has-background"><em><img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f4ac.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Question</strong>: How would we write Python code to check to see if an internet connection has been established?</em></p>
<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">We can accomplish this task by one of the following options:</p>
<ul type="video" class="wp-embed-aspect-16-9 wp-has-aspect-ratio">
<li><strong>Method 1</strong>: Use <a rel="noreferrer noopener" href="https://docs.python.org/3/library/urllib.request.html" data-type="URL" data-id="https://docs.python.org/3/library/urllib.request.html" target="_blank"><code>urlopen()</code></a></li>
<li><strong>Method 2</strong>: Use <a rel="noreferrer noopener" href="https://blog.finxter.com/python-requests-get-the-ultimate-guide/" data-type="URL" data-id="https://blog.finxter.com/python-requests-get-the-ultimate-guide/" target="_blank"><code>requests.get()</code></a></li>
<li><strong>Method 3</strong>: Use a <a rel="noreferrer noopener" href="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/" data-type="URL" data-id="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/" target="_blank">Lambda</a></li>
<li><strong>Method 4</strong>: Use <a rel="noreferrer noopener" href="https://docs.python.org/3/library/socket.html" data-type="URL" data-id="https://docs.python.org/3/library/socket.html" target="_blank"><code>socket</code></a></li>
</ul>
<hr class="wp-block-separator"/>
<h2>Preparation</h2>
<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">Before any data manipulation can occur, one (1) new library will require installation.</p>
<ul>
<li>The <em><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-install-requests-in-python/" target="_blank">Requests</a></em> library allows access to its many methods and makes data manipulation a breeze!</li>
</ul>
<p>To install this library, navigate to an <a rel="noreferrer noopener" href="https://blog.finxter.com/best-python-ide/" data-type="post" data-id="8106" target="_blank">IDE</a> terminal. At the command prompt (<code>$</code>), execute the code below. For the terminal used in this example, the command prompt is a dollar sign (<code>$</code>). Your terminal prompt may be different.</p>
<hr class="wp-block-separator"/>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">$ pip install requests</pre>
<p>Hit the <code><Enter></code> key on the keyboard to start the installation process.</p>
<p>If the installation was successful, a message displays in the terminal indicating the same.</p>
<hr class="wp-block-separator"/>
<p>Feel free to view the PyCharm installation guide for the required library.</p>
<ul>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-install-a-library-on-pycharm/" data-type="URL" data-id="https://blog.finxter.com/how-to-install-a-library-on-pycharm/" target="_blank">How to install Requests on PyCharm</a></li>
</ul>
<hr class="wp-block-separator"/>
<p id="block-3b5c9c73-276c-4b84-a1bc-d5ba1de38d56">Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.</p>
<pre class="EnlighterJSRAW wp-embed-aspect-16-9 wp-has-aspect-ratio" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from urllib.request import urlopen as url
import requests
import socket </pre>
<hr class="wp-block-separator"/>
<h2>Method 1: Use urlopen()</h2>
<p class="has-global-color-8-background-color has-background">This example uses <code>urlopen()</code> to establish a connection to the URL shown below. In addition, two (2) parameters are passed: a valid URL and a timeout.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">try: url('https://finxter.com/', timeout=3) print('Success')
except ConnectionError as e: print(f'Failure - {e}')</pre>
<p>This code is wrapped inside a <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-catch-and-print-exception-messages-in-python/" data-type="URL" data-id="https://blog.finxter.com/how-to-catch-and-print-exception-messages-in-python/" target="_blank"><code>try/except</code></a> statement. When run, the code drops inside the <code>try</code> statement and checks to see if a connection can be established to the indicated URL. This attempt waits three (3) seconds before timing out. </p>
<p>Depending on the connection status, a message indicating the same is output to the terminal.</p>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Python Basics Urllib Urlopen" width="780" height="439" src="https://www.youtube.com/embed/rnkILdjWYjo?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</figure>
<p><strong>Output</strong></p>
<pre class="wp-block-preformatted"><code>Success</code></pre>
<hr class="wp-block-separator"/>
<h2>Method 2: Use requests.get()</h2>
<p class="has-global-color-8-background-color has-background">This example requires the use of the <code><a href="https://blog.finxter.com/python-requests-library-2/" data-type="post" data-id="37804" target="_blank" rel="noreferrer noopener">requests</a></code> library and uses <a rel="noreferrer noopener" href="https://blog.finxter.com/python-requests-get-the-ultimate-guide/" data-type="URL" data-id="https://blog.finxter.com/python-requests-get-the-ultimate-guide/" target="_blank"><code>requests.get()</code></a> to establish a connection to the URL shown below. A status code returns indicating Success or Failure.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="1" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">res = requests.get('https://finxter.com/')
print(res) if (res.status_code): print('Success')
else: print('f'Failure')</pre>
<p>This code accepts a URL and attempts to establish a connection to the same. The results of this connection save to <code>res</code> as an object.</p>
<pre class="wp-block-preformatted"><code><Response [200]></code></pre>
<p>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.</p>
<p><strong>Output</strong></p>
<pre class="wp-block-preformatted"><code>Success</code></pre>
<hr class="wp-block-separator"/>
<h2>Method 3: Use a Lambda</h2>
<p class="has-global-color-8-background-color has-background">In the methods above, we used a few lines of code to establish a connection and display the appropriate result. This <a href="https://pythononeliners.com/" data-type="URL" data-id="https://pythononeliners.com/" target="_blank" rel="noreferrer noopener">one-liner</a> accomplishes the same task in one line!</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># One-Liner to Check Internet Connection:
print((lambda a: 'Success' if 0 == a.system('ping finxter.com -w 4 > clear') else 'Failure')(__import__('os')))</pre>
<p>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!</p>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Let's Play Finxter - The Lambda Function in Python" width="780" height="439" src="https://www.youtube.com/embed/kBg4n52XoUQ?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</figure>
<p><strong>Output</strong></p>
<pre class="wp-block-preformatted"><code>Success</code></pre>
<hr class="wp-block-separator"/>
<h2>Method 4: Use socket</h2>
<p class="has-global-color-8-background-color has-background">This example requires the <code><a href="https://blog.finxter.com/python-networking-with-sockets/" data-type="post" data-id="31586" target="_blank" rel="noreferrer noopener">socket</a></code> library and creates a function to establish a connection to the URL shown below. A Boolean value returns indicating <code>True</code>/<code>False</code>.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="9" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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)</pre>
<p>This code defines a new function, <code>check_connection</code>. Using a <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-catch-and-print-exception-messages-in-python/" data-type="URL" data-id="https://blog.finxter.com/how-to-catch-and-print-exception-messages-in-python/" target="_blank">try/except</a> statement attempts to connect to the indicated URL. Depending on the result, the function returns either <code>True</code> or <code>False</code>.</p>
<p>Finally, the function is called, the code runs, and the result outputs to the terminal.</p>
<p><strong>Output</strong></p>
<pre class="wp-block-preformatted"><code>True</code></pre>
<hr class="wp-block-separator"/>
<h2>Summary</h2>
<p>These four (4) methods to check the internet connection should give you enough information to select the best one for your coding requirements.</p>
<p>Good Luck & Happy Coding!</p>
<hr class="wp-block-separator"/>
</div>
https://www.sickgaming.net/blog/2022/05/...in-python/
<div><div class="kk-star-ratings kksr-valign-top kksr-align-left " data-payload="{"align":"left","id":"339914","slug":"default","valign":"top","reference":"auto","count":"1","readonly":"","score":"5","best":"5","gap":"5","greet":"Rate this post","legend":"5\/5 - (1 vote)","size":"24","width":"142.5","_legend":"{score}\/{best} - ({count} {votes})"}">
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 142.5px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend"> 5/5 – (1 vote) </div>
</div>
<h2 class="wp-embed-aspect-16-9 wp-has-aspect-ratio">Problem Formulation and Solution Overview</h2>
<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">In this article, you’ll learn how to check an Internet Connection in Python.</p>
<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio"><strong>Problem</strong>: 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. </p>
<p><strong>Example:</strong></p>
<ul>
<li>If your computer has access, you want to print <code>"Success"</code>. </li>
<li>Otherwise, you want to print <code>"Failure"</code>. </li>
</ul>
<p>Specifically, how to implement the function <code>has_connection()</code> in the following sample code snippet?</p>
<pre class="wp-block-preformatted"><code>if <strong>check_connection()</strong>: print('Success!')
else: print('Failure!')</code></pre>
<hr class="wp-block-separator"/>
<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">To make it more fun, we have the following running scenario:</p>
<p>Let’s assume you are a Python Coder working for <strong>AllTech</strong>. 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.</p>
<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio has-global-color-8-background-color has-background"><em><img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f4ac.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Question</strong>: How would we write Python code to check to see if an internet connection has been established?</em></p>
<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">We can accomplish this task by one of the following options:</p>
<ul type="video" class="wp-embed-aspect-16-9 wp-has-aspect-ratio">
<li><strong>Method 1</strong>: Use <a rel="noreferrer noopener" href="https://docs.python.org/3/library/urllib.request.html" data-type="URL" data-id="https://docs.python.org/3/library/urllib.request.html" target="_blank"><code>urlopen()</code></a></li>
<li><strong>Method 2</strong>: Use <a rel="noreferrer noopener" href="https://blog.finxter.com/python-requests-get-the-ultimate-guide/" data-type="URL" data-id="https://blog.finxter.com/python-requests-get-the-ultimate-guide/" target="_blank"><code>requests.get()</code></a></li>
<li><strong>Method 3</strong>: Use a <a rel="noreferrer noopener" href="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/" data-type="URL" data-id="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/" target="_blank">Lambda</a></li>
<li><strong>Method 4</strong>: Use <a rel="noreferrer noopener" href="https://docs.python.org/3/library/socket.html" data-type="URL" data-id="https://docs.python.org/3/library/socket.html" target="_blank"><code>socket</code></a></li>
</ul>
<hr class="wp-block-separator"/>
<h2>Preparation</h2>
<p class="wp-embed-aspect-16-9 wp-has-aspect-ratio">Before any data manipulation can occur, one (1) new library will require installation.</p>
<ul>
<li>The <em><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-install-requests-in-python/" target="_blank">Requests</a></em> library allows access to its many methods and makes data manipulation a breeze!</li>
</ul>
<p>To install this library, navigate to an <a rel="noreferrer noopener" href="https://blog.finxter.com/best-python-ide/" data-type="post" data-id="8106" target="_blank">IDE</a> terminal. At the command prompt (<code>$</code>), execute the code below. For the terminal used in this example, the command prompt is a dollar sign (<code>$</code>). Your terminal prompt may be different.</p>
<hr class="wp-block-separator"/>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">$ pip install requests</pre>
<p>Hit the <code><Enter></code> key on the keyboard to start the installation process.</p>
<p>If the installation was successful, a message displays in the terminal indicating the same.</p>
<hr class="wp-block-separator"/>
<p>Feel free to view the PyCharm installation guide for the required library.</p>
<ul>
<li><a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-install-a-library-on-pycharm/" data-type="URL" data-id="https://blog.finxter.com/how-to-install-a-library-on-pycharm/" target="_blank">How to install Requests on PyCharm</a></li>
</ul>
<hr class="wp-block-separator"/>
<p id="block-3b5c9c73-276c-4b84-a1bc-d5ba1de38d56">Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.</p>
<pre class="EnlighterJSRAW wp-embed-aspect-16-9 wp-has-aspect-ratio" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">from urllib.request import urlopen as url
import requests
import socket </pre>
<hr class="wp-block-separator"/>
<h2>Method 1: Use urlopen()</h2>
<p class="has-global-color-8-background-color has-background">This example uses <code>urlopen()</code> to establish a connection to the URL shown below. In addition, two (2) parameters are passed: a valid URL and a timeout.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">try: url('https://finxter.com/', timeout=3) print('Success')
except ConnectionError as e: print(f'Failure - {e}')</pre>
<p>This code is wrapped inside a <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-catch-and-print-exception-messages-in-python/" data-type="URL" data-id="https://blog.finxter.com/how-to-catch-and-print-exception-messages-in-python/" target="_blank"><code>try/except</code></a> statement. When run, the code drops inside the <code>try</code> statement and checks to see if a connection can be established to the indicated URL. This attempt waits three (3) seconds before timing out. </p>
<p>Depending on the connection status, a message indicating the same is output to the terminal.</p>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Python Basics Urllib Urlopen" width="780" height="439" src="https://www.youtube.com/embed/rnkILdjWYjo?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</figure>
<p><strong>Output</strong></p>
<pre class="wp-block-preformatted"><code>Success</code></pre>
<hr class="wp-block-separator"/>
<h2>Method 2: Use requests.get()</h2>
<p class="has-global-color-8-background-color has-background">This example requires the use of the <code><a href="https://blog.finxter.com/python-requests-library-2/" data-type="post" data-id="37804" target="_blank" rel="noreferrer noopener">requests</a></code> library and uses <a rel="noreferrer noopener" href="https://blog.finxter.com/python-requests-get-the-ultimate-guide/" data-type="URL" data-id="https://blog.finxter.com/python-requests-get-the-ultimate-guide/" target="_blank"><code>requests.get()</code></a> to establish a connection to the URL shown below. A status code returns indicating Success or Failure.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="1" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">res = requests.get('https://finxter.com/')
print(res) if (res.status_code): print('Success')
else: print('f'Failure')</pre>
<p>This code accepts a URL and attempts to establish a connection to the same. The results of this connection save to <code>res</code> as an object.</p>
<pre class="wp-block-preformatted"><code><Response [200]></code></pre>
<p>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.</p>
<p><strong>Output</strong></p>
<pre class="wp-block-preformatted"><code>Success</code></pre>
<hr class="wp-block-separator"/>
<h2>Method 3: Use a Lambda</h2>
<p class="has-global-color-8-background-color has-background">In the methods above, we used a few lines of code to establish a connection and display the appropriate result. This <a href="https://pythononeliners.com/" data-type="URL" data-id="https://pythononeliners.com/" target="_blank" rel="noreferrer noopener">one-liner</a> accomplishes the same task in one line!</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># One-Liner to Check Internet Connection:
print((lambda a: 'Success' if 0 == a.system('ping finxter.com -w 4 > clear') else 'Failure')(__import__('os')))</pre>
<p>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!</p>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Let's Play Finxter - The Lambda Function in Python" width="780" height="439" src="https://www.youtube.com/embed/kBg4n52XoUQ?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</figure>
<p><strong>Output</strong></p>
<pre class="wp-block-preformatted"><code>Success</code></pre>
<hr class="wp-block-separator"/>
<h2>Method 4: Use socket</h2>
<p class="has-global-color-8-background-color has-background">This example requires the <code><a href="https://blog.finxter.com/python-networking-with-sockets/" data-type="post" data-id="31586" target="_blank" rel="noreferrer noopener">socket</a></code> library and creates a function to establish a connection to the URL shown below. A Boolean value returns indicating <code>True</code>/<code>False</code>.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="9" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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)</pre>
<p>This code defines a new function, <code>check_connection</code>. Using a <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-catch-and-print-exception-messages-in-python/" data-type="URL" data-id="https://blog.finxter.com/how-to-catch-and-print-exception-messages-in-python/" target="_blank">try/except</a> statement attempts to connect to the indicated URL. Depending on the result, the function returns either <code>True</code> or <code>False</code>.</p>
<p>Finally, the function is called, the code runs, and the result outputs to the terminal.</p>
<p><strong>Output</strong></p>
<pre class="wp-block-preformatted"><code>True</code></pre>
<hr class="wp-block-separator"/>
<h2>Summary</h2>
<p>These four (4) methods to check the internet connection should give you enough information to select the best one for your coding requirements.</p>
<p>Good Luck & Happy Coding!</p>
<hr class="wp-block-separator"/>
</div>
https://www.sickgaming.net/blog/2022/05/...in-python/