← Back to all snippets
BASH

Checking if a Network Port is Open and Listening

Discover a concise bash snippet to verify if a specific TCP port is active and listening on your server, useful for debugging network services or pre-deployment checks.

#!/bin/bash

# Configuration
HOST="localhost"
PORT="8080"
TIMEOUT="1" # Timeout in seconds

# Check if nc (netcat) is available
if ! command -v nc &> /dev/null; then
    echo "Error: netcat (nc) command not found. Please install it (e.g., sudo apt install netcat-openbsd)."
    exit 1
fi

echo "Checking if ${HOST}:${PORT} is open and listening..."

# Use netcat to check if the port is open
if nc -z -w ${TIMEOUT} ${HOST} ${PORT}; then
  echo "Port ${PORT} on ${HOST} is open and listening."
  exit 0
else
  echo "Port ${PORT} on ${HOST} is closed or not listening."
  exit 1
fi
How it works: This script provides a quick way to check if a specific TCP port on a given host is open and actively listening. It leverages the `netcat` (nc) utility with the `-z` option for zero-I/O mode (port scan only) and `-w` for a timeout. This is incredibly useful for web developers to verify that backend services, databases, or web servers are running and accessible on their expected ports, whether locally or on a remote server, during development, deployment, or debugging.

Need help integrating this into your project?

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

Hire DigitalCodeLabs