A Simple Way to Check for Internet Connectivity in Scripts
hive-186392·@thecrazygm·
0.000 HBDA Simple Way to Check for Internet Connectivity in Scripts
Hey everyone, I run a lot of scripts via **cron**, even on my laptop, but my laptop isn't always connected to the internet. This can cause issues for scripts that need an online connection to do their job. To solve this, I wrote a simple helper function called `is_online` that I can use at the start of my scripts to check for an internet connection before proceeding. It's a small but useful way to make my automated tasks more reliable. --- ### The "204 No Content" Trick The function works by using a clever and efficient trick that many modern operating systems use for their own "captive portal" checks. Instead of pinging a server or downloading a full webpage, it makes a request to a special URL that is designed to return an **HTTP 204** status code.  A **`204 No Content`** response is unique because it tells the client that the request was successful, but there's intentionally no content to return. The server doesn't send a body, not even an empty one. This is perfect for a connectivity check because it confirms a successful connection with minimal data usage and resource cost. --- ### The `is_online` Function Here is the simple Bash function I use: ```bash # Checks if there is an internet connection. is_online() { local url="http://google.com/generate_204" # use TLS if privacy matters # local url="https://cp.cloudflare.com/generate_204" local timeout=1 local response response=$( curl \ --output /dev/null \ --write-out "%{http_code}" \ --max-time "$timeout" \ --silent \ "$url" ) if [ "$response" = "200" ] || [ "$response" = "204" ]; then return 0 else return 1 fi } ``` This function uses `curl` to make a request to Google's connectivity check URL and only outputs the HTTP response code. If the code is `204` (or `200`, as some proxies might return), the function returns a successful exit code (`0`). Otherwise, it returns an error code (`1`). ### Quick Example Usage ```bash if is_online; then echo "Online" echo "Do stuff" else echo "Offline" fi ``` --- ### Alternative Providers Several major companies provide these `generate_204` endpoints. Here are a few alternatives: - **Google:** The default for many Android devices, using domains like `connectivitycheck.gstatic.com`. - **Cloudflare:** Provides a TLS-encrypted option at `cp.cloudflare.com/generate_204`. - **Microsoft:** Uses `edge-http.microsoft.com/captiveportal/generate_204`, particularly for the Edge browser. - **GrapheneOS:** This privacy-focused Android variant uses `connectivitycheck.grapheneos.network/generate_204`. By adding this simple check to my scripts, I can ensure they only run when they're supposed to, preventing a backlog of errors when my laptop is offline. As always, Michael Garcia a.k.a. TheCrazyGM
👍 freecompliments, hdmed, hetty-rowan, magnacarta, boeltermc, beststart, poplar-22, ngwinndave, georgesantana73, hive-140084, pepetoken, fc-curation, fc-rewards, fc-arbitration, indiasierra, magicalex, indeedly, trovepower, mmbbot, steemulant, steemtelly, jacor, moretea, morwhale, coolguy123, guurry123, thelogicaldude, gurseerat, alkirua, pishio, trashyomen, tub3r0, holdeck2, vrezion, whitneyalexx, tengolotodo.leo, timix648, converter.bonus, bankrobbery, spoonies, pepe.voter, claudiavb, murtaza-7868, michael561, braaiboy, dailyspam, vrezyy, noctury, chrisly.social, d-a-d, digi-alt, joeyarnoldvn, emsenn0, morwhaleplus, morwhalebonus, najat, gabrieljr, savvyfrog, robtheranger, thearned, baasdebeer, afternoondrinks, aydie1000, ilanisnapshots, manclar, wynella, shmieta, svanbo, esmeesmith, fonestreet, casimodo, hive-lu, ecoinstats, mk992039, instagram-models, treasure.hoard, ryosai, partytime.inleo, thecrazygm.bank, ecoinstant, eturnerx, tomiscurious, votehero, promo-mentors, voter001, eturnerx-dbuzz, fatman, lisamgentile1961, ijebest, blessskateshop, calebmarvel24, cryptoknight12, jozefkrichards, onewolfe, hivedrip, mvd, dante31, futurethinker, osarueseosato, tinyhousecryptos, dpend.active, sketching, iviaxpow3r, mxm0unite, thorlock, mighty-thor, splinterwhale, iproto, steembasicincome, archon-gov, sbi2, sbi3, irisworld, sbi4, qwertm, pof.archon, anikys3reasure, sbi-tokens, sbi5, shauner, sbi6, sbi7, sbi8, abrockman, monsterrerentals, sbi9, sbi10, everythingsmgirl, gamer00, pixelfan, neoxvoter, sports.power.bot, ambyr00, ykretz, kiemis, youloseagain, mviews, holovision.stem, learn2code, hivelist, stem.alfa, ecp.rclease, ecp.dump, penguinpablo, cryptonized, alphacore, guysellars, funnyman, hungrybear, calmphoenix, jacuzzi, rudy-dj, kasih-sayang, ecp.curator, realblockchain, rulivyxo, keithtaylor, team, podanrj, ichheilee, green77, zvaleska, mes, beaker007, cryptoniusrex, onezetty, lolz.byte, dstampede, mytechtrail, magic.byte, bbarelyseal, olympicdragon, eforucom, fw206, woelfchen, tydynrain, likedeeler, lordnasty, artlover, vasigo, memess.byte,