{"id":124502,"date":"2022-05-04T18:33:18","date_gmt":"2022-05-04T18:33:18","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=339914"},"modified":"2022-05-04T18:33:18","modified_gmt":"2022-05-04T18:33:18","slug":"how-to-check-your-internet-connection-in-python","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2022\/05\/04\/how-to-check-your-internet-connection-in-python\/","title":{"rendered":"How to Check Your Internet Connection in Python?"},"content":{"rendered":"<div class=\"kk-star-ratings kksr-valign-top kksr-align-left \" data-payload=\"{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;339914&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;count&quot;:&quot;1&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;5\\\/5 - (1 vote)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\\\/{best} - ({count} {votes})&quot;}\">\n<div class=\"kksr-stars\">\n<div class=\"kksr-stars-inactive\">\n<div class=\"kksr-star\" data-star=\"1\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"2\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"3\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"4\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"5\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<div class=\"kksr-stars-active\" style=\"width: 142.5px;\">\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<\/div>\n<div class=\"kksr-legend\"> 5\/5 &#8211; (1 vote) <\/div>\n<\/div>\n<h2 class=\"wp-embed-aspect-16-9 wp-has-aspect-ratio\">Problem Formulation and Solution Overview<\/h2>\n<p class=\"wp-embed-aspect-16-9 wp-has-aspect-ratio\">In this article, you&#8217;ll learn how to check an Internet Connection in Python.<\/p>\n<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>\n<p><strong>Example:<\/strong><\/p>\n<ul>\n<li>If your computer has access, you want to print <code>\"Success\"<\/code>. <\/li>\n<li>Otherwise, you want to print <code>\"Failure\"<\/code>. <\/li>\n<\/ul>\n<p>Specifically, how to implement the function <code>has_connection()<\/code> in the following sample code snippet?<\/p>\n<pre class=\"wp-block-preformatted\"><code>if <strong>check_connection()<\/strong>: print('Success!')\nelse: print('Failure!')<\/code><\/pre>\n<hr class=\"wp-block-separator\"\/>\n<p class=\"wp-embed-aspect-16-9 wp-has-aspect-ratio\">To make it more fun, we have the following running scenario:<\/p>\n<p>Let&#8217;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>\n<p class=\"wp-embed-aspect-16-9 wp-has-aspect-ratio has-global-color-8-background-color has-background\"><em><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/13.1.0\/72x72\/1f4ac.png\" alt=\"\ud83d\udcac\" 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>\n<p class=\"wp-embed-aspect-16-9 wp-has-aspect-ratio\">We can accomplish this task by one of the following options:<\/p>\n<ul type=\"video\" class=\"wp-embed-aspect-16-9 wp-has-aspect-ratio\">\n<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>\n<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>\n<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>\n<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>\n<\/ul>\n<hr class=\"wp-block-separator\"\/>\n<h2>Preparation<\/h2>\n<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>\n<ul>\n<li>The&nbsp;<em><a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/how-to-install-requests-in-python\/\" target=\"_blank\">Requests<\/a><\/em>&nbsp;library allows access to its many methods and makes data manipulation a breeze!<\/li>\n<\/ul>\n<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>\n<hr class=\"wp-block-separator\"\/>\n<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>\n<p>Hit the <code>&lt;Enter&gt;<\/code> key on the keyboard to start the installation process.<\/p>\n<p>If the installation was successful, a message displays in the terminal indicating the same.<\/p>\n<hr class=\"wp-block-separator\"\/>\n<p>Feel free to view the PyCharm installation guide for the required library.<\/p>\n<ul>\n<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>\n<\/ul>\n<hr class=\"wp-block-separator\"\/>\n<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>\n<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\nimport requests\nimport socket <\/pre>\n<hr class=\"wp-block-separator\"\/>\n<h2>Method 1: Use urlopen()<\/h2>\n<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>\n<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')\nexcept ConnectionError as e: print(f'Failure - {e}')<\/pre>\n<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>\n<p>Depending on the connection status, a message indicating the same is output to the terminal.<\/p>\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<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>\n<\/div>\n<\/figure>\n<p><strong>Output<\/strong><\/p>\n<pre class=\"wp-block-preformatted\"><code>Success<\/code><\/pre>\n<hr class=\"wp-block-separator\"\/>\n<h2>Method 2: Use requests.get()<\/h2>\n<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>\n<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\/')\nprint(res) if (res.status_code): print('Success')\nelse: print('f'Failure')<\/pre>\n<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>\n<pre class=\"wp-block-preformatted\"><code>&lt;Response [200]><\/code><\/pre>\n<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>\n<p><strong>Output<\/strong><\/p>\n<pre class=\"wp-block-preformatted\"><code>Success<\/code><\/pre>\n<hr class=\"wp-block-separator\"\/>\n<h2>Method 3: Use a Lambda<\/h2>\n<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>\n<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:\nprint((lambda a: 'Success' if 0 == a.system('ping finxter.com -w 4 > clear') else 'Failure')(__import__('os')))<\/pre>\n<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>\n<figure class=\"wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio\">\n<div class=\"wp-block-embed__wrapper\">\n<iframe loading=\"lazy\" title=\"Let&#039;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>\n<\/div>\n<\/figure>\n<p><strong>Output<\/strong><\/p>\n<pre class=\"wp-block-preformatted\"><code>Success<\/code><\/pre>\n<hr class=\"wp-block-separator\"\/>\n<h2>Method 4: Use socket<\/h2>\n<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>\n<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()\nprint(res)<\/pre>\n<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>\n<p>Finally, the function is called, the code runs, and the result outputs to the terminal.<\/p>\n<p><strong>Output<\/strong><\/p>\n<pre class=\"wp-block-preformatted\"><code>True<\/code><\/pre>\n<hr class=\"wp-block-separator\"\/>\n<h2>Summary<\/h2>\n<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>\n<p>Good Luck &amp; Happy Coding!<\/p>\n<hr class=\"wp-block-separator\"\/>\n","protected":false},"excerpt":{"rendered":"<p>5\/5 &#8211; (1 vote) Problem Formulation and Solution Overview In this article, you&#8217;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 [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-124502","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/124502","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=124502"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/124502\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=124502"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=124502"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=124502"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}