BASH

Check if a Network Port is Open and Service is Responsive

A bash script to check if a specific network port on a given host is open and optionally, if a basic HTTP/S service is responsive, useful for server health checks.

#!/bin/bash

# --- Configuration ---
HOST="localhost"
PORT="80"
CHECK_HTTP="true" # Set to "true" to also attempt an HTTP GET request
HTTP_PATH="/"     # Path to request if CHECK_HTTP is true

echo "Checking service on ${HOST}:${PORT}..."

# Check if port is open using netcat (nc)
if nc -zvw1 "${HOST}" "${PORT}" &> /dev/null; then
    echo "Port ${PORT} on ${HOST} is OPEN."

    if [ "${CHECK_HTTP}" = "true" ]; then
        echo "Attempting HTTP GET request to http://${HOST}:${PORT}${HTTP_PATH}..."
        HTTP_STATUS=$(curl -s -o /dev/null -w "%{\http_code}" "http://${HOST}:${PORT}${HTTP_PATH}")
        if [ "${HTTP_STATUS}" -ge 200 ] && [ "${HTTP_STATUS}" -lt 400 ]; then
            echo "HTTP service is RESPONSIVE (Status: ${HTTP_STATUS})."
            exit 0
        else
            echo "HTTP service is NOT RESPONSIVE (Status: ${HTTP_STATUS})."
            exit 1
        fi
    else
        exit 0 # Port is open, HTTP check not requested
    fi
else
    echo "Port ${PORT} on ${HOST} is CLOSED or host is unreachable."
    exit 1
fi
How it works: This script provides a health check for network services. It first uses `nc` (netcat) to determine if a specified port on a given host is open. Optionally, if configured, it then uses `curl` to perform an HTTP GET request to that host and port, checking if the web service returns a successful HTTP status code (2xx or 3xx), indicating responsiveness.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs