15%

Save 15% on All Hosting Services

Test your skills and get Discount on any hosting plan

Use code:

Skills
Get Started
30.10.2024
1 +1

Checking Open and Listening Ports on Linux Using netstat and ss

Monitoring open and listening ports on a Linux system is one of the most critical practices for maintaining server security, diagnosing network issues, and managing your infrastructure effectively. By regularly auditing which ports are open and which services are bound to them, you can proactively identify unauthorized access attempts, detect misconfigurations, and eliminate unnecessary attack surfaces before they become serious vulnerabilities.

Whether you're running a high-traffic application on a VPS Hosting plan or managing a fleet of bare-metal machines, understanding the network exposure of your Linux server is non-negotiable. This guide provides a comprehensive, technically accurate walkthrough of how to use both netstat and ss — the two most widely used command-line tools for port inspection on Linux — along with supplementary tools and real-world best practices.

Table of Contents

  1. Understanding Ports and Their Types
  2. Checking Ports with netstat
  3. Checking Ports with ss
  4. Comparing netstat vs. ss
  5. Other Tools for Checking Open Ports
  6. Security Best Practices for Open Port Management
  7. Conclusion

1. Understanding Ports and Their Types {#understanding-ports}

Before diving into the tools themselves, it's important to establish a clear understanding of what ports are, how they're categorized, and why monitoring them matters.

What Is a Network Port?

A network port is a logical communication endpoint associated with a specific process or service on a host. Ports allow a single server with one IP address to run multiple networked services simultaneously — for example, a web server on port 80, an SSH daemon on port 22, and a database on port 3306.

Port Categories

RangeCategoryDescription
0–1023Well-Known PortsReserved for standard system services (HTTP, SSH, FTP, etc.)
1024–49151Registered PortsUsed by applications and middleware (MySQL, PostgreSQL, etc.)
49152–65535Dynamic/Ephemeral PortsTemporarily assigned for outbound client connections

Port States You'll Encounter

  • LISTEN — The port is open and a service is actively waiting for incoming connections.
  • ESTABLISHED — An active connection exists between two endpoints.
  • TIME_WAIT — The connection is closing; the system is waiting to ensure the remote end received the final acknowledgment.
  • CLOSE_WAIT — The remote end has closed the connection; the local application hasn't closed its side yet.

Transport Protocols

  • TCP (Transmission Control Protocol): Connection-oriented, reliable, with error checking and guaranteed delivery. Used by HTTP, HTTPS, SSH, FTP, and most application-layer protocols.
  • UDP (User Datagram Protocol): Connectionless, faster, but without delivery guarantees. Used by DNS, NTP, DHCP, and streaming services.

2. Checking Ports with netstat {#netstat}

What Is netstat?

netstat (network statistics) is a classic command-line utility that displays active network connections, routing tables, interface statistics, and listening ports. Although it has been officially deprecated in favor of ss on modern Linux distributions, netstat remains widely deployed — especially on legacy systems and in environments where administrators are deeply familiar with its syntax.

Installing netstat

netstat is part of the net-tools package, which is no longer installed by default on many modern distributions. Install it as follows:

Debian / Ubuntu:

sudo apt update && sudo apt install net-tools -y

CentOS / RHEL / AlmaLinux / Rocky Linux:

sudo yum install net-tools -y
# or on newer versions:
sudo dnf install net-tools -y

Arch Linux:

sudo pacman -S net-tools

Core netstat Syntax

sudo netstat [options]

Checking All Listening TCP and UDP Ports

sudo netstat -tuln

Flag breakdown:

FlagMeaning
-tDisplay TCP connections and ports
-uDisplay UDP connections and ports
-lShow only listening sockets (ports awaiting connections)
-nDisplay numerical IP addresses and port numbers (skip DNS resolution for speed)

Example output:

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN
tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN
tcp6       0      0 :::443                  :::*                    LISTEN
udp        0      0 0.0.0.0:68              0.0.0.0:*

Reading the output:

  • Proto — The protocol in use (tcp, udp, tcp6, udp6).
  • Local Address — The IP address and port number on which the service is listening. 0.0.0.0 means the service listens on all available interfaces; 127.0.0.1 means it's only accessible locally.
  • Foreign Address — The remote client's address (shown as 0.0.0.0:* for listening ports with no active connection).
  • State — The connection state (LISTEN, ESTABLISHED, TIME_WAIT, etc.).

Including Process Information

To see which process owns each listening port, add the -p flag:

sudo netstat -tulnp

Example output with process info:

Proto Recv-Q Send-Q Local Address    Foreign Address  State   PID/Program name
tcp        0      0 0.0.0.0:22       0.0.0.0:*        LISTEN  1023/sshd
tcp        0      0 0.0.0.0:80       0.0.0.0:*        LISTEN  2847/nginx
tcp        0      0 127.0.0.1:3306   0.0.0.0:*        LISTEN  3102/mysqld

> Note: You must run this command with sudo to see process names for all users, not just your own.

Filtering Output for Specific Ports or Services

Use grep to narrow down results to a specific port or service:

# Check if anything is listening on port 80
sudo netstat -tuln | grep ":80"

# Check for SSH (port 22)
sudo netstat -tuln | grep ":22"

# Check for MySQL (port 3306)
sudo netstat -tuln | grep ":3306"

# Check for HTTPS (port 443)
sudo netstat -tuln | grep ":443"

Viewing All Active Connections (Not Just Listening)

To see all active connections, including established ones, drop the -l flag:

sudo netstat -tunp

Displaying Routing Table

sudo netstat -r

Displaying Network Interface Statistics

sudo netstat -i

3. Checking Ports with ss {#ss}

What Is ss?

ss (socket statistics) is the modern replacement for netstat, developed as part of the iproute2 package. It communicates directly with the Linux kernel via Netlink sockets, making it significantly faster and more efficient than netstat — particularly on systems with thousands of concurrent connections.

ss is installed by default on virtually all modern Linux distributions, including Ubuntu 18.04+, CentOS 7+, Debian 9+, and their derivatives.

Core ss Syntax

ss [options] [filter]

Checking All Listening TCP and UDP Ports

ss -tuln

The flags are identical in meaning to netstat:

FlagMeaning
-tShow TCP sockets
-uShow UDP sockets
-lShow only listening sockets
-nShow numerical addresses (no DNS resolution)

Example output:

Netid  State   Recv-Q  Send-Q   Local Address:Port    Peer Address:Port
tcp    LISTEN  0       128      0.0.0.0:22             0.0.0.0:*
tcp    LISTEN  0       511      0.0.0.0:80             0.0.0.0:*
tcp    LISTEN  0       128      127.0.0.1:3306         0.0.0.0:*
tcp    LISTEN  0       511         [::]:443            [::]:*
udp    UNCONN  0       0        0.0.0.0:68             0.0.0.0:*

Including Process Information

sudo ss -tulnp

Example output:

Netid  State   Recv-Q  Send-Q  Local Address:Port  Peer Address:Port  Process
tcp    LISTEN  0       128     0.0.0.0:22           0.0.0.0:*          users:(("sshd",pid=1023,fd=3))
tcp    LISTEN  0       511     0.0.0.0:80           0.0.0.0:*          users:(("nginx",pid=2847,fd=6))
tcp    LISTEN  0       128     127.0.0.1:3306       0.0.0.0:*          users:(("mysqld",pid=3102,fd=21))

Filtering by Protocol

Show only listening TCP ports:

ss -tl

Show only listening UDP ports:

ss -ul

Show all TCP connections (including established):

ss -t

Advanced Filtering with ss

One of ss's most powerful features is its built-in expression-based filtering, which allows you to filter by port, address, state, and more — without relying on grep.

Filter by specific port number:

ss -tuln sport = :80
ss -tuln sport = :443
ss -tuln sport = :22

Filter by destination port:

ss -tuln dport = :3306

Show all sockets in ESTABLISHED state:

ss -t state established

Show all sockets in LISTEN state:

ss -t state listening

Filter by source IP address:

ss -tuln src 192.168.1.100

Show connections to a specific remote host:

ss -t dst 203.0.113.50

Combine multiple filters:

ss -t state established '( dport = :443 or sport = :443 )'

Displaying Socket Memory Usage

ss can also show detailed memory usage per socket, which is useful for diagnosing performance issues:

ss -tm

Displaying Timer Information

ss -to

This shows retransmission timers and keepalive timers for TCP connections, which is invaluable for diagnosing connection stability issues.

4. Comparing netstat vs. ss {#comparison}

Both tools accomplish the same fundamental goal, but there are meaningful differences that should guide your choice:

Featurenetstatss
Packagenet-tools (often not pre-installed)iproute2 (pre-installed on modern distros)
SpeedSlower (reads from /proc/net/)Faster (uses Netlink kernel interface)
Performance at scaleDegrades with thousands of connectionsHandles large connection counts efficiently
Advanced filteringRequires piping to grepBuilt-in expression-based filtering
Output detailGoodMore detailed (memory, timers, etc.)
IPv6 supportAdequateExcellent
Maintenance statusDeprecatedActively maintained
Learning curveFamiliar to long-time adminsSlightly different syntax but well-documented

When to Use netstat

  • When administering older Linux systems (CentOS 6, Debian 7, etc.) where ss may not be available.
  • When working with scripts or documentation that already use netstat syntax.
  • When you're more comfortable with its output format and don't need advanced filtering.

When to Use ss

  • On any modern Linux distribution (Ubuntu 18.04+, CentOS 7+, Debian 9+, and newer).
  • When managing servers with a high volume of concurrent connections — such as those running on Dedicated Servers under heavy load.
  • When you need advanced filtering, timer information, or socket memory statistics.
  • For automation and scripting where performance matters.

5. Other Tools for Checking Open Ports {#other-tools}

Beyond netstat and ss, several other utilities are useful for port inspection and network analysis on Linux.

lsof — List Open Files (Including Sockets)

lsof (List Open Files) treats network sockets as files (consistent with Linux's "everything is a file" philosophy) and can display which process has a specific port open.

Install lsof:

# Debian/Ubuntu
sudo apt install lsof -y

# CentOS/RHEL
sudo yum install lsof -y

Check which process is using port 80:

sudo lsof -i :80

Check which process is using port 443:

sudo lsof -i :443

List all network connections:

sudo lsof -i

List all TCP listening sockets:

sudo lsof -i TCP -s TCP:LISTEN

Example output:

COMMAND   PID     USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
nginx    2847     root    6u  IPv4  23456      0t0  TCP *:http (LISTEN)
nginx    2848 www-data    6u  IPv4  23456      0t0  TCP *:http (LISTEN)

nmap — Network Mapper

nmap is a powerful network scanning tool used for security auditing, network discovery, and port scanning. Unlike ss and netstat (which inspect the local system), nmap can scan both local and remote hosts.

Install nmap:

# Debian/Ubuntu
sudo apt install nmap -y

# CentOS/RHEL
sudo yum install nmap -y

Scan all TCP ports on localhost:

sudo nmap -sT localhost

Scan for open ports with OS detection:

sudo nmap -sT -O localhost

Scan a specific port range:

sudo nmap -p 1-1024 localhost

Scan UDP ports (requires root):

sudo nmap -sU localhost

Scan a remote server:

sudo nmap -sT 203.0.113.50

> Important: Only scan systems you own or have explicit permission to scan. Unauthorized port scanning may violate laws and terms of service.

fuser — Identify Processes Using Files or Sockets

# Find which process is using port 80 (TCP)
sudo fuser 80/tcp

# Find which process is using port 53 (UDP)
sudo fuser 53/udp

/proc/net/ — Direct Kernel Interface

For scripting purposes, you can read port information directly from the Linux kernel's virtual filesystem:

# View raw TCP socket table
cat /proc/net/tcp

# View raw UDP socket table
cat /proc/net/udp

Note that addresses and ports in /proc/net/tcp are displayed in hexadecimal and require conversion for human readability. Tools like ss and netstat parse this data automatically.

6. Security Best Practices for Open Port Management {#security}

Knowing how to check open ports is only half the battle. Acting on that information is what keeps your server secure. Here are actionable best practices every Linux administrator should follow:

Principle of Least Exposure

Only expose ports that are absolutely necessary for your application to function. Every open port is a potential attack vector. Regularly audit your listening ports and close or firewall anything that doesn't need to be publicly accessible.

Bind Services to Specific Interfaces

Avoid binding services to 0.0.0.0 (all interfaces) unless required. For example, a MySQL database server should only listen on 127.0.0.1 if it's only accessed locally:

# In /etc/mysql/mysql.conf.d/mysqld.cnf
bind-address = 127.0.0.1

Use a Firewall

Use ufw (Ubuntu) or firewalld / iptables (CentOS/RHEL) to restrict access to open ports by IP address, subnet, or network interface:

# Allow SSH only from a specific IP (ufw)
sudo ufw allow from 203.0.113.10 to any port 22

# Deny all other access to port 22
sudo ufw deny 22

Regularly Audit Listening Ports

Schedule regular port audits using cron jobs or monitoring tools. A sudden new listening port can indicate a compromised service, a misconfiguration, or — in the worst case — malware:

# Quick audit command — save output and compare over time
sudo ss -tulnp > /var/log/port_audit_$(date +%F).txt

Secure Services with SSL/TLS

Any service exposed to the internet — web servers, mail servers, control panels — should use encrypted connections. Pair your open ports with valid SSL Certificates to protect data in transit and prevent man-in-the-middle attacks.

Monitor for Unexpected Changes

Use intrusion detection tools like AIDE, Tripwire, or auditd to alert you when new processes start listening on ports. Integrate with centralized logging (e.g., ELK Stack, Graylog) for comprehensive visibility.

Disable Unused Services

If a service is not needed, stop it and disable it from starting at boot:

# Stop and disable a service (systemd)
sudo systemctl stop <service-name>
sudo systemctl disable <service-name>

Quick Reference: Most Useful Commands

Tasknetstat Commandss Command
All listening TCP/UDP portssudo netstat -tulnsudo ss -tuln
All listening ports with PIDssudo netstat -tulnpsudo ss -tulnp
Only listening TCP portssudo netstat -tlnsudo ss -tl
Only listening UDP portssudo netstat -ulnsudo ss -ul
Filter by port 80`sudo netstat -tulngrep ":80"`sudo ss -tuln sport = :80
All established connectionssudo netstat -tunpsudo ss -t state established
Show routing tablesudo netstat -rip route show

Conclusion {#conclusion}

Monitoring open and listening ports is a foundational skill for any Linux system administrator or DevOps engineer. Whether you're securing a production web server, troubleshooting a connectivity issue, or performing a routine security audit, netstat and ss give you immediate, actionable visibility into your system's network exposure.

To summarize the key takeaways:

  • Use ss as your primary tool on any modern Linux distribution — it's faster, more feature-rich, and actively maintained.
  • Use netstat when working on legacy systems or when existing scripts and workflows depend on it.
  • Supplement with lsof and nmap for deeper process-level inspection and external port scanning.
  • Always act on your findings — close unnecessary ports, bind services to the correct interfaces, and enforce firewall rules.
  • Secure exposed services with proper SSL Certificates and access controls.

If you're looking for a hosting environment that gives you full root access to implement these security practices, AlexHost's VPS Hosting plans provide complete control over your Linux server configuration — including firewall management, service hardening, and network monitoring. For teams that need maximum performance and dedicated resources, our Dedicated Servers deliver the raw power and isolation required for enterprise-grade security operations. And if you prefer a managed environment with a familiar interface, explore our VPS with cPanel options for streamlined server management without sacrificing control.

Regular port auditing, combined with a hardened server configuration, is one of the most effective defenses against unauthorized access and data breaches. Make it a routine part of your system administration practice.

15%

Save 15% on All Hosting Services

Test your skills and get Discount on any hosting plan

Use code:

Skills
Get Started