Check Internet Connection in a Script

Summary: Write a script to test connectivity with ping/curl.


Ensuring reliable internet connectivity is crucial for many scripts and automated processes. Before running network-dependent operations, it's a best practice to verify that your system is online. This article covers how to programmatically check your internet connection using simple scripts with tools like ping and curl, applicable across different platforms.

Why Check Internet Connection in a Script?

When you automate tasks like file downloads, API requests, or software updates, any interruption or lack of connectivity can cause failures. By verifying the internet connection at the start of your script, you can provide early feedback and avoid cascading errors.

Common Tools

  • Ping: Sends ICMP echo requests to a remote host and measures response.
  • Curl: Transfers data to or from a server; can verify HTTP/HTTPS access.

Let's see how to utilize these tools in practice.


Using ping to Check Connectivity

The ping command is universally available on almost all systems. Here are sample scripts:

Bash (Linux/macOS)

#!/bin/bash

# Host to test (Google DNS)
HOST="8.8.8.8"

if ping -c 1 -W 2 $HOST &> /dev/null
then
  echo "Internet connection is active."
else
  echo "No internet connection."
  exit 1
fi
  • -c 1: Send one ping packet.
  • -W 2: Wait up to 2 seconds for a response.

Tip: Change the host for alternative IPs (e.g., Cloudflare: 1.1.1.1).

Windows Batch

@echo off

SET HOST=8.8.8.8
ping -n 1 %HOST% >nul

IF %ERRORLEVEL% == 0 (
  echo Internet connection is active.
) ELSE (
  echo No internet connection.
  exit /b 1
)

Using curl to Check Connectivity

curl is excellent for testing end-to-end connectivity, including DNS resolution and HTTP(S) server reachability.

Bash Example

#!/bin/bash

URL="https://www.google.com"

if curl -s --head --request GET $URL | grep "200 OK" > /dev/null
then
  echo "Internet connection is active."
else
  echo "No internet connection."
  exit 1
fi
  • -s: Silent mode.
  • --head: Fetch headers only.
  • grep "200 OK": Checks HTTP 200 status.

PowerShell Example

$URL = "https://www.google.com"

try {
    $response = Invoke-WebRequest -Uri $URL -UseBasicParsing -TimeoutSec 5
    if ($response.StatusCode -eq 200) {
        Write-Output "Internet connection is active."
    } else {
        Write-Output "No internet connection."
        exit 1
    }
} catch {
    Write-Output "No internet connection."
    exit 1
}

Best Practices

  • Retry logic: Consider allowing a few retries before declaring failure.
  • Timeouts: Use timeouts to prevent delays if the network is slow or unresponsive.
  • Dependency selection: Use ping for basic reachability (ICMP), and curl or Invoke-WebRequest for verifying access to specific services.
  • Informative messages: Provide clear feedback in your scripts for logging and debugging purposes.

Conclusion

Testing internet connectivity within your scripts helps preempt errors and makes automation more resilient. Whether you prefer ping for low-level checks or HTTP-based checks with curl, integrating a simple connection test is easy and effective.

Try integrating these checks into your next script to ensure smoother, more reliable automation!