Website Vidya
SecurityStep-by-Step Guide

How to Check Open Ports in Linux: nmap, netcat, and Bash

Learn check open ports in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

RR
Rajesh RayLead Systems Educator
Published:
11 min read
PDF Cheat Sheet
How to Check Open Ports in Linux: nmap, netcat, and Bash
AI Executive SummaryWebsiteVidya AI

11 min read

Learn check open ports in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What nc Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

Interactive Builder for this Guide

Build your custom firewall syntax (How to Check Open Ports in Linux: nmap, netcat, and Bash)

Generated POSIX Command
sudo ufw allow port 443 proto tcp comment 'Production HTTPS'
UFW rule to ALLOW port 443/tcp.
Flag-by-Flag Breakdown
ufw allowallow matching inbound packets
port 443Match destination port 443
proto tcpFilter TCP transport traffic

Knowing how to check open ports in linux is an essential discipline for systems engineers, security auditors, and network administrators responsible for infrastructure hardening and service deployment. In TCP/IP networking, a port represents an addressable communication endpoint mapped to an active operating system service. Auditing open ports verifies that production daemons—such as web servers, SSH access points, and database backends—are reachable through firewalls while ensuring unauthorized or insecure services are not exposed to the public internet.

Port auditing strategies divide fundamentally between local kernel inspection and remote network probing. While internal kernel tools like ss and lsof interrogate local socket tables to report which daemons are bound to 0.0.0.0 or 127.0.0.1, external network probing with nmap, netcat, and Bash evaluates actual packet traversal through physical routers, cloud security groups, and packet-filtering firewalls.

This technical guide explains the underlying transport-layer mechanics of TCP three-way handshakes and UDP datagram probing, demonstrates how to test port accessibility using nmap and netcat, and provides dependency-free Bash techniques for minimal container environments where external utilities cannot be installed.

Advertisement
How to Check Open Ports in Linux: nmap, netcat, and Bash — syntax, flags, and practical terminal workflow diagram
How to Check Open Ports in Linux: nmap, netcat, and Bash — command syntax, key options, and production workflow reference.

What nc Does and When to Use It

From an operating system and networking perspective, checking a remote TCP port requires initiating or simulating a TCP three-way handshake. When a scanner dispatches a SYN packet to a destination IP and port, three potential outcomes occur: if the port is open and listening, the target kernel returns a SYN-ACK packet; if the port is closed, the target kernel returns an active RST (Reset) packet; if an intermediate firewall or packet filter drops the packet silently without replying, the scanner receives no response and marks the port as 'filtered'.

UDP port scanning operates under distinct transport semantics because UDP is connectionless. When an application probes a UDP port, it dispatches an empty datagram or protocol-specific payload. If the port is closed, RFC 792 specifies that the destination host should return an ICMP Port Unreachable message (Type 3, Code 3). If no ICMP error is received, the port is classified as 'open|filtered', because stateful firewalls frequently drop UDP datagrams without returning ICMP feedback.

At the operating system level, nc interacts with the Linux kernel networking stack through netlink sockets (AF_NETLINK), raw packet sockets, or standard POSIX resolver APIs. When running nc in cloud instances or Kubernetes worker nodes, combining flags such as -z, -v, -w N, -p PORTS lets you bypass slow reverse DNS lookups and inspect numeric IPv4/IPv6 addresses and socket states directly.

Availability and Installation Across Linux Distributions

The nc utility is packaged in nmap across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:

Advertisement

Before running administrative tasks or automation scripts, verify whether nc is installed and inspect which binary path and version your shell resolves:

type -a nc
nc --version 2>/dev/null || man -f nc

# Illustrative output (reviewed against documentation)
nc is /usr/bin/nc
nc (nmap)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y nmap netcat-openbsd

# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y nmap nmap-ncat

# Arch Linux
sudo pacman -S --noconfirm nmap openbsd-netcat

# Alpine Linux
sudo apk add --no-cache nmap netcat-openbsd

Command Syntax, Arguments, and Exit Status Codes

nc -zv [HOST] [PORT] | nmap -p [PORTS] [HOST] | exec 3<>/dev/tcp/[HOST]/[PORT]

Netcat (nc) uses a concise syntax for port verification: nc -z -v [-w timeout] HOST PORT(S). The -z flag configures zero-I/O mode, instructing netcat to tear down the connection immediately upon establishing a handshake without transferring application payload, while -v provides human-readable connection status messages.

Nmap provides granular control over scan types and port ranges: nmap [SCAN_TYPE] -p [PORTS] HOST. Common scan types include -sS (TCP SYN stealth scan requiring root privileges) and -sT (full unprivileged TCP Connect scan). For environments lacking external packages, GNU Bash natively supports pseudo-path redirection using /dev/tcp/HOST/PORT, allowing admins to test connectivity using pure shell conditionals.

  • 0 — The tested port is open, listening, and accessible through the network path.
  • 1 — The tested port is closed (connection refused), unreachable, or blocked by a packet filter.
  • 124 — The connection attempt timed out due to a silent packet drop by a stateful firewall or network drop.

Important Options and Flags Reference

Option / FlagLong Form / ArgumentTechnical Behavior and Purpose
-z--zero-io (netcat)Instructs netcat to poll for open ports without sending any application payload data over the established connection.
-v--verbose (netcat/nmap)Enables verbose diagnostic output showing detailed connection progress, status transitions, and port states.
-w N--wait=N (netcat)Configures a network connection and response timeout interval of N seconds before aborting the probe.
-p PORTS--ports (nmap)Specifies individual ports (e.g., -p 80,443), comma-separated lists, or ranges (e.g., -p 1-1024) to scan.
-sS--syn-scan (nmap)Executes a stealthy TCP SYN scan without completing the full three-way handshake (requires root/CAP_NET_RAW).
-sT--connect-scan (nmap)Executes a standard TCP connect() scan using the operating system networking stack, usable by unprivileged accounts.
-sU--udp-scan (nmap)Scans UDP ports by dispatching datagrams and listening for ICMP Port Unreachable return packets.
-n--no-dns (nmap/netcat)Disables reverse DNS resolution of target IP addresses, dramatically accelerating multi-host scans.
--open--open (nmap)Filters scan results to display only ports that are confirmed to be in an open state, suppressing closed/filtered lines.

When auditing remote systems with netcat, always combine -z, -v, and -w (for example, nc -zvw 2 192.0.2.10 443). Without the -w timeout argument, netcat will hang indefinitely on filtered ports where firewalls drop incoming SYN packets without sending RST replies.

Advertisement

When using nmap on production networks, pairing -sS with -n and --open provides maximum execution speed and clarity. Bypassing reverse DNS lookups (-n) prevents local latency bottlenecks, while --open hides thousands of closed ports, instantly surfacing listening attack surfaces.

When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.

Practical Basic and Advanced Usage Examples

1. Check a Single Remote TCP Port Using Netcat

Quickly verify whether a remote web server is accepting connections on TCP port 443 with a two-second connection timeout.

nc -zvw 2 192.0.2.10 443

# Illustrative output (reviewed against documentation)
Connection to 192.0.2.10 443 port [tcp/https] succeeded!

Netcat executes a TCP handshake, reports success upon receiving SYN-ACK, terminates the socket cleanly with zero payload sent, and exits with status 0.

2. Scan a Range of Remote TCP Ports Using Netcat

Audit a contiguous range of ports on a remote machine to identify common open services such as SSH, SMTP, and HTTP.

nc -zvw 1 192.0.2.10 20-25

# Illustrative output (reviewed against documentation)
nc: connect to 192.0.2.10 port 20 (tcp) failed: Connection refused
nc: connect to 192.0.2.10 port 21 (tcp) failed: Connection refused
Connection to 192.0.2.10 22 port [tcp/ssh] succeeded!
nc: connect to 192.0.2.10 port 23 (tcp) failed: Connection refused
nc: connect to 192.0.2.10 port 24 (tcp) failed: Connection refused
Connection to 192.0.2.10 25 port [tcp/smtp] succeeded!

Netcat tests ports 20 through 25 sequentially. Ports 22 (SSH) and 25 (SMTP) return successful handshakes, while closed ports return immediate connection resets.

3. Perform Targeted Multi-Port Scanning with Nmap

Use nmap to inspect standard administrative and web service ports on a target host, suppressing reverse DNS lookups for speed.

nmap -p 22,80,443,3306,8080 -n 192.0.2.10

# Illustrative output (reviewed against documentation)
Starting Nmap 7.94 ( https://nmap.org ) at 2026-10-22 20:00 UTC
Nmap scan report for 192.0.2.10
Host is up (0.0012s latency).

PORT     STATE  SERVICE
22/tcp   open   ssh
80/tcp   open   http
443/tcp  open   https
3306/tcp closed mysql
8080/tcp closed http-proxy

Nmap done: 1 IP address (1 host up) scanned in 0.15 seconds

Nmap interrogates the five specified ports, categorizing ports 22, 80, and 443 as open and ports 3306 and 8080 as closed.

4. Execute Fast TCP SYN Stealth Scanning with Nmap

Run a SYN stealth scan with root privileges, which tears down the connection with an RST packet before the handshake completes to avoid application-layer logging.

sudo nmap -sS -p 80,443,8443 --open -n 192.0.2.10

# Illustrative output (reviewed against documentation)
Starting Nmap 7.94 ( https://nmap.org ) at 2026-10-22 20:01 UTC
Nmap scan report for 192.0.2.10
Host is up (0.0008s latency).

PORT    STATE SERVICE
80/tcp  open  http
443/tcp open  https

Nmap done: 1 IP address (1 host up) scanned in 0.08 seconds

SYN scanning does not create a complete TCP connection, meaning application daemons (such as Apache or Nginx) do not log spurious connection attempts in their access logs.

5. Check Remote UDP Ports Using Nmap

Inspect UDP ports (such as DNS, NTP, and SNMP) to identify listening connectionless services.

sudo nmap -sU -p 53,123,161 -n 192.0.2.10

# Illustrative output (reviewed against documentation)
Starting Nmap 7.94 ( https://nmap.org ) at 2026-10-22 20:02 UTC
Nmap scan report for 192.0.2.10
Host is up (0.0009s latency).

PORT    STATE         SERVICE
53/udp  open          domain
123/udp open|filtered ntp
161/udp closed        snmp

Nmap done: 1 IP address (1 host up) scanned in 1.45 seconds

Port 53 responded with a DNS reply (open), port 123 gave no response (open|filtered), and port 161 returned an ICMP Port Unreachable packet (closed).

6. Check Open Ports Using Native Bash /dev/tcp (Zero Dependencies)

In restricted container environments where neither nmap nor netcat is installed, test port connectivity using Bash's built-in socket pseudo-filesystem.

timeout 2 bash -c '</dev/tcp/192.0.2.10/22' && echo "Port 22 is OPEN" || echo "Port 22 is CLOSED/FILTERED"

# Illustrative output (reviewed against documentation)
Port 22 is OPEN

Bash opens a socket to the IP and port via /dev/tcp. The timeout command ensures that if a firewall silently drops packets, the script aborts after two seconds with a failure status.

Real-World Workflows, Pipelines, and Shell Automation

Automated Multi-Host Service Availability Verification Pipeline

Verify that critical cluster services (API gateways, database replicas, Redis caches) are accessible across a newly provisioned private subnet prior to routing user traffic.

#!/usr/bin/env bash
set -euo pipefail

TARGET_HOSTS=("10.0.1.10" "10.0.1.11" "10.0.1.12")
AUDIT_PORTS=(22 80 443 6379)
TIMEOUT=1

echo "=== Subnet Port Connectivity Audit ==="
for host in "${TARGET_HOSTS[@]}"; do
  echo "--- Testing Host: ${host} ---"
  for port in "${AUDIT_PORTS[@]}"; do
    if timeout "${TIMEOUT}" bash -c "</dev/tcp/${host}/${port}" 2>/dev/null; then
      printf "  [OPEN]   Port %-5d on %s\n" "${port}" "${host}"
    else
      printf "  [CLOSED] Port %-5d on %s\n" "${port}" "${host}"
    fi
  done
done

# Illustrative output (reviewed against documentation)
=== Subnet Port Connectivity Audit ===
--- Testing Host: 10.0.1.10 ---
  [OPEN]   Port 22    on 10.0.1.10
  [OPEN]   Port 80    on 10.0.1.10
  [OPEN]   Port 443   on 10.0.1.10
  [CLOSED] Port 6379  on 10.0.1.10
--- Testing Host: 10.0.1.11 ---
  [OPEN]   Port 22    on 10.0.1.11
  [CLOSED] Port 80    on 10.0.1.11
  [CLOSED] Port 443   on 10.0.1.11
  [OPEN]   Port 6379  on 10.0.1.11
--- Testing Host: 10.0.1.12 ---
  [OPEN]   Port 22    on 10.0.1.12
  [OPEN]   Port 80    on 10.0.1.12
  [OPEN]   Port 443   on 10.0.1.12
  [CLOSED] Port 6379  on 10.0.1.12

This production bash script audits a cluster subnet without third-party dependencies, identifying which nodes host Redis (6379) and which run web servers (80/443).

External vs. Internal Firewall Rule Verification Workflow

Validate security group isolation by scanning database ports from outside the VPC to ensure internal database ports are not inadvertently exposed to public ingress.

#!/usr/bin/env bash
set -euo pipefail

PUBLIC_IP="198.51.100.25"
CRITICAL_PORTS="22,80,443,3306,5432,6379,27017"

echo "=== Auditing Public IP Ingress Exposure: ${PUBLIC_IP} ==="
SCAN_RESULT=$(nmap -p "${CRITICAL_PORTS}" -n --open "${PUBLIC_IP}")

echo "${SCAN_RESULT}"

if echo "${SCAN_RESULT}" | grep -E -q "3306|5432|6379|27017"; then
  echo "CRITICAL ALERT: Internal database port exposed to public internet!"
  exit 1
else
  echo "SUCCESS: Database ports are properly filtered by security groups."
fi

# Illustrative output (reviewed against documentation)
=== Auditing Public IP Ingress Exposure: 198.51.100.25 ===
Starting Nmap 7.94 ( https://nmap.org ) at 2026-10-22 20:05 UTC
Nmap scan report for 198.51.100.25
Host is up (0.015s latency).

PORT    STATE SERVICE
22/tcp  open  ssh
80/tcp  open  http
443/tcp open  https

Nmap done: 1 IP address (1 host up) scanned in 0.42 seconds
SUCCESS: Database ports are properly filtered by security groups.

The script scans public IP endpoints and alerts immediately if sensitive database ports (MySQL 3306, PostgreSQL 5432, Redis 6379, MongoDB 27017) are reachable from external networks.

Pipelines, Redirection, Quoting, and Shell Expansion

When embedding nc inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.

Permissions, Security Implications, and Safe Execution

Executing advanced raw packet scans (such as nmap SYN scanning -sS or UDP scanning -sU) requires elevated privileges (root or the Linux CAP_NET_RAW capability) to craft raw Ethernet and IP frames. Standard unprivileged users must fall back to full TCP connect scans (-sT) or netcat, which invoke standard kernel connect(2) system calls and complete full handshakes.

Modern Intrusion Detection and Prevention Systems (IDS/IPS) like Suricata, Snort, and cloud Web Application Firewalls actively monitor for port scanning patterns. Rapid sequential port probes trigger automated rate-limiting, temporary IP blacklisting, and security event alerts in Security Information and Event Management (SIEM) systems.

GNU/Linux, BSD, and BusyBox Implementation Differences

Netcat implementations differ significantly across Linux distributions. Debian and Ubuntu default to netcat-openbsd, which supports the -z zero-I/O flag and standard timeout options. RHEL, Fedora, and Rocky Linux provide ncat from the Nmap project (nmap-ncat), which includes enhanced SSL/TLS capabilities (--ssl). Alpine Linux and embedded routers provide BusyBox nc, which omits the -z flag entirely and requires piping empty input (e.g., nc -w 1 host port < /dev/null).

The /dev/tcp/HOST/PORT pseudo-path feature is a proprietary compile-time extension of GNU Bash. It is not supported in POSIX sh, Debian Dash, Zsh, or BusyBox ash. In cross-platform shell scripts, verify whether /dev/tcp is functional before relying on it for health checks.

Troubleshooting Common Errors and Diagnostics

Connection refused when probing port

Root Cause: The destination host is reachable, but no application daemon is actively listening on that port, or the listening daemon is bound strictly to localhost (127.0.0.1) instead of 0.0.0.0.

Resolution: Log into the target server and run ss -tulpn to check whether the service is running and inspect its listening IP address binding.

ssh user@target-host "sudo ss -tulpn | grep :3306"

Connection timed out (port filtered)

Root Cause: An intermediate network firewall, cloud security group, or local iptables/nftables policy is silently dropping incoming SYN packets.

Resolution: Inspect cloud security group ingress rules, AWS VPC network ACLs, or local host firewall status (sudo ufw status or sudo iptables -L -n -v).

sudo iptables -L INPUT -n -v | grep DROP

nc: invalid option -- 'z'

Root Cause: The installed version of netcat is a minimal variant (such as BusyBox nc or traditional netcat) that does not support the -z zero-I/O option.

Resolution: Simulate zero-I/O scanning by redirecting /dev/null into netcat with a short wait timeout, or install netcat-openbsd.

nc -w 1 192.0.2.10 80 < /dev/null

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
An open port has an active application accepting connections (returns SYN-ACK). A closed port has no application listening, so the host rejects connections immediately (returns RST). A filtered port means a firewall is blocking packets, so no response is returned and the attempt times out.
Yes, pass the -u flag along with -z and -v (e.g., nc -zvu 192.0.2.10 53). However, because UDP is connectionless, netcat will report success unless an ICMP Port Unreachable packet is explicitly returned.
SYN scanning requires building and injecting raw TCP packets without completing the operating system's standard three-way handshake. Creating raw network sockets requires the CAP_NET_RAW Linux capability, typically reserved for root.
To check local ports without network latency or firewall interference, run sudo ss -tulpn or sudo lsof -i -n -P. These tools directly inspect the Linux kernel's internal socket tables.
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout