Website Vidya
Linux & ServersStep-by-Step Guide

Check Listening Ports in Linux: ss, netstat & lsof Guide

Complete guide to check listening ports in linux: syntax, options, practical examples, real-world Linux workflows, security considerations, and troubleshooting.

RR
Rajesh RayLead Systems Educator
Published:
10 min read
PDF Cheat Sheet
Check Listening Ports in Linux: ss, netstat & lsof Guide
AI Executive SummaryWebsiteVidya AI

10 min read

Complete guide to check listening ports in linux: syntax, options, practical examples, real-world Linux workflows, security considerations, and troubleshooting.

Key Highlights
  • What ss 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

When provisioning web services, configuring reverse proxies, or securing network perimeters, learning how to check listening ports in linux is an indispensable operational skill for every system administrator and DevOps engineer. Listening ports represent active network sockets opened by server daemons awaiting incoming client connections.

For over a decade, Linux administrators relied on the netstat command from the net-tools package. However, netstat was officially deprecated because it iterated slowly through virtual /proc/net/tcp files. The modern iproute2 suite provides ss (Socket Statistics), which interfaces directly with kernel netlink subsystem (sock_diag) to dump socket tables instantaneously even on heavily loaded servers hosting tens of thousands of active connections.

In this practical reference guide, we examine the socket architecture of the Linux networking stack, break down the classic ss -tulpn flag combination, contrast ss with netstat and lsof, walk through terminal examples, and establish automated port auditing pipelines.

Advertisement
Check Listening Ports in Linux: ss, netstat & lsof Guide — syntax, flags, and practical terminal workflow diagram
Check Listening Ports in Linux: ss, netstat & lsof Guide — command syntax, key options, and production workflow reference.

What ss Does and When to Use It

At the kernel level, a listening port corresponds to a socket created with socket(2), bound to a local IP address and port with bind(2), and placed into the passive TCP LISTEN state with listen(2). In this state, the kernel TCP/IP stack maintains two queues for incoming handshakes: the SYN Queue (for half-open connections undergoing the 3-way handshake) and the Accept Queue (for fully established connections waiting for the userland application to call accept(2)).

The ss utility retrieves socket telemetry directly from the kernel via the sock_diag netlink subsystem (AF_NETLINK with NETLINK_INET_DIAG protocol). Unlike legacy netstat, which parsed ASCII text in /proc/net/tcp and /proc/net/udp (requiring expensive kernel string formatting and linear scans), sock_diag returns binary data structures over netlink sockets, enabling ss to filter and display thousands of sockets in milliseconds with negligible CPU overhead.

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

Availability and Installation Across Linux Distributions

The ss utility is packaged in iproute2 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 ss is installed and inspect which binary path and version your shell resolves:

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

# Illustrative output (reviewed against documentation)
ss is /usr/bin/ss
ss (iproute2)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y iproute2

# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y iproute

# Arch Linux
sudo pacman -S --noconfirm iproute2

# Alpine Linux
sudo apk add --no-cache iproute2

Command Syntax, Arguments, and Exit Status Codes

ss [options] [FILTER]

The syntax for ss is ss [options] [FILTER]. When executed with no options, ss displays a list of open, non-listening established sockets. To view ports waiting for incoming connections, pass -l (or --listening). Common protocol selectors include -t for TCP, -u for UDP, -x for Unix domain stream sockets, and -w for raw sockets.

To obtain actionable operational diagnostics, administrators combine flags into the standard mnemonic ss -tulpn: -t (TCP), -u (UDP), -l (listening only), -p (process name and PID), and -n (numeric IP and port numbers). Using -n is critical because it prevents ss from performing slow reverse DNS lookups and /etc/services port-name translations (e.g., displaying :80 instead of :http and :22 instead of :ssh).

  • 0 — Command completed successfully and socket tables were displayed.
  • 1 — Operational failure during socket retrieval or netlink communication.
  • 2 — Invalid filter syntax or malformed command-line option.
  • 130 — Process interrupted by user signal (SIGINT, Ctrl+C).

Important Options and Flags Reference

Option / FlagLong Form / ArgumentTechnical Behavior and Purpose
-t--tcpDisplays TCP sockets.
-u--udpDisplays UDP sockets.
-l--listeningDisplays only listening sockets (which are omitted by default).
-p--processesShows the process name and PID owning each socket (requires root/sudo).
-n--numericPrevents resolution of service names and hostnames, displaying raw numeric ports.
-a--allDisplays both listening and non-listening (established, time-wait) sockets.
-4--ipv4Restricts display strictly to IPv4 sockets.
-6--ipv6Restricts display strictly to IPv6 sockets.
-s--summaryPrints high-level summary statistics of total sockets across all protocol families.

The combination sudo ss -tulpn is the gold standard for daily server administration because it provides an exhaustive, uncluttered table of all listening ports across both IPv4 and IPv6 without stalling on DNS timeouts.

Advertisement

Advanced ss filter expressions allow targeted querying without piping to grep. For example, ss -tln 'sport = :http or sport = :https' or ss -tln 'sport >= :8000 and sport <= :9000' instructs the kernel to filter matching sockets before returning data to userland.

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. List All Active Listening TCP Sockets with Numeric Ports

Display all TCP ports waiting for inbound connections, using numeric addresses to avoid DNS lookup delays.

ss -tln

# Illustrative output (reviewed against documentation)
State   Recv-Q  Send-Q     Local Address:Port      Peer Address:Port  Process
LISTEN  0       511              0.0.0.0:80             0.0.0.0:*             
LISTEN  0       128            127.0.0.1:3306           0.0.0.0:*             
LISTEN  0       128              0.0.0.0:22             0.0.0.0:*             
LISTEN  0       511                 [::]:443               [::]:*             
LISTEN  0       128                 [::]:22                [::]:*

State LISTEN confirms active listening sockets. Port 80 and 22 listen on all interfaces (0.0.0.0), while 3306 (MySQL) listens securely only on 127.0.0.1.

2. List Listening TCP and UDP Sockets with Process Names and PIDs

Run ss with root privileges to correlate listening network sockets with their owning daemon process names.

sudo ss -tulpn

# Illustrative output (reviewed against documentation)
Netid State  Recv-Q Send-Q Local Address:Port  Peer Address:PortProcess                                
tcp   LISTEN 0      511          0.0.0.0:80         0.0.0.0:*    users:(("nginx",pid=1240,fd=6))
tcp   LISTEN 0      128          0.0.0.0:22         0.0.0.0:*    users:(("sshd",pid=842,fd=3))
tcp   LISTEN 0      511             [::]:443           [::]:*    users:(("nginx",pid=1240,fd=7))
udp   UNCONN 0      0            0.0.0.0:53         0.0.0.0:*    users:(("named",pid=710,fd=512))

The Process column reveals that PID 1240 (nginx) owns ports 80 and 443, PID 842 (sshd) owns port 22, and named owns UDP port 53.

3. Filter Listening Sockets by Specific Port Using ss State Filters

Check whether a specific port (such as 443) is actively listening without piping through grep.

ss -tln 'sport = :443'

# Illustrative output (reviewed against documentation)
State   Recv-Q  Send-Q     Local Address:Port      Peer Address:Port  Process
LISTEN  0       511                 [::]:443               [::]:*

The sport filter expression instructs the kernel to return only sockets whose source port matches port 443 (HTTPS).

4. Identify Process on a Specific Port with lsof

Use lsof to pinpoint the executable path, working directory, and PID bound to a specific network port.

sudo lsof -i :8080

# Illustrative output (reviewed against documentation)
COMMAND   PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
node    14209 node   22u  IPv6  48201      0t0  TCP *:8080 (LISTEN)

The lsof command inspects open file descriptors, identifying that the node process (PID 14209) is listening on TCP port 8080.

5. Check Listening Ports Using Legacy netstat

Execute the classic netstat command on older distributions where net-tools remains deployed.

netstat -tuln

# Illustrative output (reviewed against documentation)
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN     
tcp6       0      0 :::443                  :::*                    LISTEN

Passing -tuln to netstat displays active listening TCP and UDP sockets with numeric addresses on legacy Linux systems.

6. Display High-Level Socket Summary Statistics

Check the total count of open, listening, and established sockets across all protocols.

ss -s

# Illustrative output (reviewed against documentation)
Total: 184
TCP:   42 (estab 14, closed 18, orphaned 0, timewait 12)

Transport Total     IP        IPv6
RAW       1         0         1   
UDP       8         5         3   
TCP       24        14        10  
INET      33        19        14  
FRAG      0         0         0

The -s flag generates a concise summary showing established connections, timewait sockets, and protocol breakdown.

Real-World Workflows, Pipelines, and Shell Automation

Security Audit Workflow: Detecting Rogue Publicly Bound Services

Audit listening ports to identify any database or internal service mistakenly bound to public interfaces rather than localhost.

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

echo "=== AUDITING PUBLICLY BOUND LISTENING PORTS ==="
sudo ss -tulpn | awk '
NR>1 && $5 ~ /^(0\.0\.0\.0|::|\[::\]):/ {
  split($5, a, ":");
  port = a[length(a)];
  print "[EXPOSED] Port: " port "\tProtocol: " $1 "\tDetails: " $0
}'

# Illustrative output (reviewed against documentation)
=== AUDITING PUBLICLY BOUND LISTENING PORTS ===
[EXPOSED] Port: 80	Protocol: tcp	Details: tcp LISTEN 0 511 0.0.0.0:80 ... nginx
[EXPOSED] Port: 22	Protocol: tcp	Details: tcp LISTEN 0 128 0.0.0.0:22 ... sshd

Parsing the 5th column (Local Address:Port) catches services bound to 0.0.0.0 or [::] before external port scanners discover them.

Deployment Health-Check Pipeline: Verifying Application Port Binding

Wait in deployment scripts until a newly started container or microservice binds to its target port before routing traffic.

#!/usr/bin/env bash
PORT=3000
TIMEOUT=30

echo "[DEPLOY] Waiting for service to bind on port $PORT..."
for ((i=1; i<=TIMEOUT; i++)); do
  if ss -tln | grep -q ":$PORT "; then
    echo "[SUCCESS] Service listening on port $PORT after ${i}s."
    exit 0
  fi
  sleep 1
done
echo "[TIMEOUT] Service failed to bind to port $PORT!"
exit 1

# Illustrative output (reviewed against documentation)
[DEPLOY] Waiting for service to bind on port 3000...
[SUCCESS] Service listening on port 3000 after 3s.

Polling ss -tln provides an instantaneous, zero-latency health check confirming socket readiness before updating load balancer pools.

Pipelines, Redirection, Quoting, and Shell Expansion

When embedding ss 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

The bind address of a listening socket determines its network exposure. A socket bound to 127.0.0.1 (or ::1) is bound to the loopback interface and can only be accessed by local processes on the same host, which is the secure default for databases and caching engines. In contrast, a socket bound to 0.0.0.0 (or :::) listens on all network interfaces, exposing the service to local networks and the public internet unless restricted by a firewall.

Viewing process names and PIDs with the -p flag requires root privileges or CAP_NET_ADMIN capabilities. If executed by an unprivileged user, ss displays the socket state, IP, and port number, but the users:(...) process column will be empty because Linux security restrictions prevent unprivileged users from inspecting file descriptors belonging to other system accounts.

GNU/Linux, BSD, and BusyBox Implementation Differences

The ss utility is specific to Linux systems because it depends on the Linux kernel's sock_diag netlink interface. BSD operating systems (FreeBSD, OpenBSD) and macOS do not have ss; instead, administrators on those platforms use netstat, fstat, or lsof to inspect open listening sockets.

On minimal Linux distributions like Alpine, BusyBox provides a lightweight netstat applet supporting netstat -tuln. However, for full ss functionality with process resolution and sock_diag performance on Alpine, the iproute2 package must be installed (apk add iproute2).

Troubleshooting Common Errors and Diagnostics

Process name and PID missing in ss -tulpn output

Root Cause: You executed ss as an unprivileged user, and the Linux kernel prevents non-root accounts from reading other processes' file descriptors.

Resolution: Run the command with sudo to grant permission to inspect the /proc/[pid]/fd directories.

sudo ss -tulpn

bind: Address already in use error when starting a service

Root Cause: Another process is already bound to and listening on the designated TCP or UDP port number.

Resolution: Use sudo lsof -i :<port> or sudo ss -tulpn to find the conflicting process PID and terminate or reconfigure it.

sudo ss -tulpn 'sport = :80'
sudo kill -15 <PID>

netstat command not found on modern minimal distros

Root Cause: The net-tools package has been deprecated in modern Ubuntu, Debian, RHEL, and Fedora in favor of iproute2.

Resolution: Use the modern replacement command ss -tulpn, or install net-tools if legacy script compatibility is required.

ss -tulpn
# Or install legacy netstat:
sudo apt install -y net-tools

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
The ss command communicates directly with the kernel using binary netlink structures (sock_diag), making it orders of magnitude faster than netstat, which must parse ASCII text in /proc/net/tcp. On servers with tens of thousands of connections, netstat can hang or cause high CPU load, while ss completes in milliseconds.
For sockets in the LISTEN state, Send-Q indicates the maximum size of the accept backlog queue (established TCP connections waiting for the application to call accept()), while Recv-Q indicates the current number of established connections currently waiting in the queue. If Recv-Q equals Send-Q, the application is overloaded and dropping incoming connections.
127.0.0.1 is the local loopback address, meaning the service is only reachable by programs running on the same physical host. 0.0.0.0 represents INADDR_ANY (all IPv4 addresses), meaning the service listens on all network interfaces and can accept traffic from external computers across the network.
Use sudo lsof -i :<port> or sudo ss -tulpne. The -e (extended) flag in ss displays the socket UID, which you can resolve to a username using getent passwd <UID>.
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