Verifying port status is a fundamental task for Linux administrators and developers. Whether you're troubleshooting network services or securing your system, knowing how to check port availability is essential.
The traditional netstat
command provides comprehensive network connection information:
netstat -tulnp | grep :80
This checks if port 80 is listening. Breakdown of flags:
-t
: TCP ports-u
: UDP ports-l
: Listening ports-n
: Show numeric addresses-p
: Show process/PID
For newer Linux distributions, ss
replaces netstat
with better performance:
ss -tuln | grep :22
This checks SSH port (22) status with similar flags to netstat.
To test connectivity to a remote port:
telnet example.com 443
Successful connection indicates an open port. Install telnet if not available:
sudo apt install telnet # Debian/Ubuntu
sudo yum install telnet # RHEL/CentOS
nmap provides detailed port scanning capabilities:
nmap -sT -p 80 localhost
Example output:
Starting Nmap 7.80 ( https://nmap.org ) Nmap scan report for localhost (127.0.0.1) PORT STATE SERVICE 80/tcp open http
A simple bash method without additional tools:
if echo >/dev/null >/dev/tcp/localhost/80; then
echo "Port 80 is open"
else
echo "Port 80 is closed"
fi
Remember to verify firewall rules that might block ports:
sudo iptables -L -n -v # Traditional iptables
sudo ufw status verbose # For Ubuntu UFW firewall
Create a reusable bash function for port checking:
check_port() {
if nc -z -w 3 "$1" "$2" >/dev/null; then
echo "Port $2 on $1 is open"
else
echo "Port $2 on $1 is closed"
fi
}
# Usage: check_port localhost 3306
Checking whether a port is open or listening on a Linux server is a common task for system administrators and developers. Whether you're troubleshooting network issues, verifying service availability, or securing your system, knowing how to inspect port status is essential.
The netstat
command is a traditional tool for network connections inspection. Here's how to use it:
netstat -tulnp | grep ':PORT_NUMBER'
For example, to check if port 80 is listening:
netstat -tulnp | grep ':80'
The ss
command is a modern replacement for netstat with faster performance:
ss -tulnp | grep ':PORT_NUMBER'
Example for checking port 22 (SSH):
ss -tulnp | grep ':22'
lsof
(List Open Files) can also show listening ports:
lsof -i :PORT_NUMBER
Example for MySQL port (3306):
lsof -i :3306
To test if a port is open on a remote server:
telnet SERVER_IP PORT_NUMBER
Example:
telnet 192.168.1.100 443
For comprehensive port scanning:
nmap -p PORT_NUMBER SERVER_IP
Example scanning ports 80 and 443:
nmap -p 80,443 192.168.1.100
Here's a simple bash script to check multiple ports:
#!/bin/bash
ports=(22 80 443 3306)
for port in "${ports[@]}"
do
if ss -tulnp | grep -q ":$port "; then
echo "Port $port is listening"
else
echo "Port $port is not listening"
fi
done
Remember that a listening port might be blocked by firewall rules. Check iptables/ufw:
sudo iptables -L -n
sudo ufw status