ss usually wins the bulk-enumeration benchmark on Linux, but "usually" is not a migration plan. On a host with thousands of sockets, ss -tan can finish quickly while ss -tanp spends much longer resolving process ownership. On a custom kernel, ss can fall back to the same /proc files that make netstat slow. This tutorial shows you how to run a controlled netstat vs ss performance benchmark, separate DNS and process-lookup costs from socket enumeration, and choose a default based on your own numbers. The goal is not to crown a universal winner; it is to produce a result you can defend for your workload.
Table of Contents
- What actually makes one command faster?
- Step 1: Record the workload and environment
- Step 2: Build the netstat vs ss benchmark matrix
- Step 3: Generate a repeatable socket load
- Step 4: Run the benchmark harness
- Step 5: Separate DNS, process lookup, and output costs
- Step 6: Compare like-for-like tasks
- Step 7: Interpret results and pick a default
- Conclusion
What actually makes one command faster?
The Linux netstat manual calls the program "mostly obsolete" and names ss as its replacement. That recommendation covers maintenance and capability, but it also reflects an architectural difference. netstat traditionally reads procfs — the kernel's pseudo-filesystem interface — including tables such as /proc/net/tcp. ss was written around the kernel's diagnostic netlink interface, a socket-based channel that lets a user-space tool request structured socket data directly.
The iproute2 ss documentation is candid about why the older path struggles: when the socket count is large, netstat or even cat /proc/net/tcp causes "nothing but pains and curses," and ss was designed to scale better. The sock_diag manual explains the netlink side: a caller can ask the kernel for a socket list and apply a state filter before the data is returned. It also confirms that sock_diag reports the same set of named sockets as /proc/net/tcp, which is what makes a fair comparison possible.
But architecture only sets the ceiling. Four costs determine the actual time:
- Collection — reading the socket table.
- Resolution — turning addresses, ports, and user IDs into names.
-
Attribution — matching sockets to processes when you add
-p. - Presentation — formatting and writing output to a terminal, file, or pipe.
A benchmark that only times ss -tn against netstat -tn measures the best case for ss and misses the case that breaks migrations: process attribution. Measure each cost separately.
Step 1: Record the workload and environment
A timing without a socket count and a version is an anecdote. Before you run anything, record the variables that can change the result.
| Item | Command | Record |
|---|---|---|
| Kernel release | uname -r |
|
| iproute2 version | ss -V |
|
| net-tools version | netstat --version |
|
| CPU count | nproc |
|
| User | id -un |
|
| Total TCP sockets | `ss -Htan \ | wc -l` |
| Established TCP sockets | `ss -Htan state established \ | wc -l` |
| Diagnostic module | `lsmod \ | grep -E 'tcp_diag\ |
Then decide what the command must answer. "Which ports are open?" needs a numeric inventory. "Which process owns this socket?" needs {% raw %}-p. Those are different benchmarks, and the second one is where the ranking can change.
Run the checks with a stable locale so state names and number formatting do not shift between runs:
export LC_ALL=C
uname -r
ss -V
netstat --version
nproc
id -un
ss -Htan | wc -l
ss -Htan state established | wc -l
ss -s
sudo modprobe tcp_diag 2>/dev/null || true
lsmod | grep -E 'tcp_diag|inet_diag' || true
ss -H suppresses the header, which makes the line count usable in a script. ss -s prints a summary without parsing the full socket list, so it is a quick way to size the host; the ss manual notes that -s obtains its summary from various sources rather than walking every socket.
Two cautions. First, modprobe tcp_diag may fail because the kernel built the diagnostic support in rather than providing a module; that is not a problem. Second, run the benchmark as the same user for both commands. Process attribution with -p depends on permissions, and a root run can see sockets that a normal user cannot.
Verify which path ss is taking
The iproute2 documentation warns that without the tcp_diag module, ss falls back to /proc and becomes "slow like netstat." On current kernels the diagnostic support is usually built in, but custom or minimal kernels can lack it. If strace is available, confirm the mechanism rather than guessing:
strace -f -e trace=socket,open,openat ss -tan 2>&1 \
| grep -m3 -E 'NETLINK_SOCK_DIAG|/proc/net/tcp'
strace -f -e trace=open,openat,read netstat -tan 2>&1 \
| grep -m1 '/proc/net/tcp'
The first command should show a NETLINK_SOCK_DIAG socket; the second should show netstat opening a procfs table. If the ss run shows /proc/net/tcp instead, you are measuring the fallback, not the netlink path. Use this only to verify the mechanism. strace adds substantial overhead, so never benchmark under it.
Step 2: Build the netstat vs ss benchmark matrix
One command pair is not a benchmark. Build a matrix that keeps the task constant while varying the costs that matter.
| ID | Question |
ss command |
netstat command |
Controls |
|---|---|---|---|---|
| A | All TCP sockets, numeric | ss -tan |
netstat -tan |
Same scope, same sink |
| B | All TCP sockets with process | ss -tanp |
netstat -tanp |
Same user, same scope |
| C | Established only | ss -tan state established |
`netstat -tan \ | grep -w ESTABLISHED` |
| D | Listening TCP with process | ss -tlnp |
netstat -tlnp |
Same scope |
| E | Summary | ss -s |
netstat -s |
Not equivalent; see below |
The ss manual documents the flags used here: -a includes listening and non-listening sockets, -n suppresses service-name resolution, -p shows processes, -l limits output to listeners, and -H removes the header. It also documents the state filter, which accepts standard TCP state names such as established. netstat has no equivalent state filter, so test C is deliberately a kernel-side filter versus a userspace pipe.
Keep both commands in the same network namespace. ss -N can target another namespace, but netstat has no equivalent, so a mismatch would compare different socket sets.
Test E is a trap. ss -s reports socket counts by state; netstat -s reports per-protocol SNMP counters. They are both summaries, but they answer different questions. Do not use their timings to rank the tools.
Run each row at several socket counts. If you cannot generate load, run the matrix on the real host and repeat at different times of day, recording the socket count each time.
For every command, record output volume as well as time:
printf 'ss '; ss -tan | wc -lc
printf 'netstat '; netstat -tan | wc -lc
A one- or two-line difference is usually just headers. A large difference means the commands are not doing the same job, and the timing comparison is meaningless until you fix the scope. netstat also truncates long addresses unless you add -W; if you compare byte counts, add -W so its output scope is closer to ss.
Use the same output sink for both commands in a pair. Measuring ss to /dev/null while netstat writes to a terminal measures your terminal, not the tools.
Step 3: Generate a repeatable socket load
You need a stable socket count that does not change during the run. A disposable Linux VM or container is the right place; do not generate thousands of connections on a production host.
Save this as hold_sockets.py:
#!/usr/bin/env python3
import socket
import sys
import threading
import time
count = int(sys.argv[1])
port = int(sys.argv[2]) if len(sys.argv) > 2 else 9999
dest = ("127.0.0.1", port)
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(dest)
server.listen(4096)
accepted = []
def accept_loop():
while len(accepted) < count:
conn, _ = server.accept()
accepted.append(conn)
threading.Thread(target=accept_loop, daemon=True).start()
clients = [] # keep references so the sockets stay open
for i in range(count):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Linux treats the whole 127.0.0.0/8 block as local, so these
# source addresses let us open many connections without exhausting
# the ephemeral port range on a single address.
s.bind((f"127.0.0.{2 + i % 250}", 0))
s.connect(dest)
clients.append(s)
deadline = time.time() + 60
while len(accepted) < count and time.time() < deadline:
time.sleep(0.05)
if len(accepted) < count:
print(f"only {len(accepted)} of {count} connections were accepted",
file=sys.stderr)
sys.exit(1)
print(f"{count} connections open on port {port}. Press Enter to close.")
input()
Raise the file-descriptor limit first, because the script holds both ends of every loopback connection:
ulimit -Hn # check the hard limit
ulimit -n 65535 # for 10,000 connections; scale with 2N
python3 hold_sockets.py 1000 10000
If you run this in a container, raise the container's file-descriptor limit as well; ulimit inside the container may be capped by the runtime.
In another terminal, verify the load:
ss -Htan | wc -l
ss -Htan state established | wc -l
Each loopback connection contributes two sockets, so the total is roughly twice the connection count. Repeat the benchmark at 100, 1,000, and 10,000 connections.
Run each level from a clean state. TIME_WAIT sockets from the previous level will inflate the next count, so wait for them to drain — typically up to a minute — or run each level in a fresh VM or container. Record the socket count before and after each run; a drifting count invalidates the comparison.
The script intentionally holds every socket in one process. That is a useful stress test for -p, because process attribution has to walk a large file-descriptor table. If your production host spreads sockets across many processes, run the client and server as separate processes or benchmark a real workload; the relative cost of -p may change.
If you cannot generate load, skip this step and benchmark the host you have.
Step 4: Run the benchmark harness
hyperfine handles warmup, repetition, and statistics. Install it from your package manager or with cargo install hyperfine, then start with the baseline pair:
hyperfine --shell=bash \
--warmup 3 \
--min-runs 10 \
--export-json baseline.json \
'ss -tan > /dev/null' \
'netstat -tan > /dev/null'
Warmup matters even though the socket table lives in kernel memory. The first run pays page faults for the binary and libraries, and CPU frequency may still be ramping up. Three warmup runs remove most of that noise. The hyperfine manual documents --warmup for filling caches and --prepare for per-run setup such as clearing disk caches; do not reach for --prepare with drop_caches here. Dropping caches does not clear socket data, it penalizes unrelated I/O, and it needs root.
Recent hyperfine releases can report CPU, user, and system time alongside wall-clock time with --metrics time. If your version does not support it, use the default wall-clock output and measure the CPU split separately.
Repeat the same pattern for the rest of the matrix:
hyperfine --shell=bash --warmup 3 --min-runs 10 \
'ss -tanp > /dev/null' \
'netstat -tanp > /dev/null'
hyperfine --shell=bash --warmup 3 --min-runs 10 \
'ss -tan state established > /dev/null' \
'netstat -tan | grep -w ESTABLISHED > /dev/null'
Process-attribution runs can be much slower. Bound the time with --runs 5 or --max-runs 10 instead of letting hyperfine run a ten-second command ten times.
A long benchmark gives the host time to change. Run the whole invocation three times and check that the ranking is stable; if it is not, find out what else is running before you trust the numbers.
For a single-run CPU breakdown, use /usr/bin/time rather than the shell builtin, which does not accept the same format flags:
/usr/bin/time -f 'elapsed=%e user=%U sys=%S cpu=%P maxrss=%MKB' \
ss -tanp > /dev/null
Wall-clock time is how long you wait. User and system time tell you where the work went. The time manual defines %P as (%U + %S) / %E, which is a quick way to spot a run that is blocked rather than busy.
Step 5: Separate DNS, process lookup, and output costs
A single "ss is faster" number hides three very different effects. Isolate them.
DNS and service-name resolution
The baseline uses -n on both commands. Without it, netstat resolves host, port, and user names, and ss resolves service names; the iproute2 documentation notes that unknown ports can even trigger an rpcbind query. That cost depends on your resolver and NSS configuration, not on the socket table.
Test one non-numeric run with a timeout, and keep it out of the main benchmark if it takes minutes:
timeout 60 ss -tan > /dev/null
timeout 60 netstat -tan > /dev/null
If the non-numeric run is slow, you have a name-resolution problem. Fixing it with -n is usually the right operational answer, but do not let it decide the ss versus netstat question.
Process attribution
Adding -p asks the tool to associate each socket with a process. That means matching socket inodes — the kernel's identifiers for sockets — to process file descriptors, which is extra work on top of enumeration. The iproute2 history shows how much this can matter: a 2010 commit fixed a quadratic scan in ss -p that repeatedly rescanned /proc/*/fd/*, storing the results in a hash table instead. The fix is old, but the commit is a reminder that -p performance is an implementation detail that has changed across versions. Record ss -V so your results are attributable to a specific release.
The quadratic behavior was fixed long ago, but -p still pays for process attribution. The cost scales with the number of processes and file descriptors, not just the number of sockets. That is why a host with 10,000 sockets spread across 20 processes can behave differently from one with 10,000 sockets in a single process. Depending on the iproute2 version and the process layout, ss -p can be slower than netstat -p; that is exactly why row B exists in the matrix.
If -p dominates, narrow the query before you give up on ss. State filters can be applied by the kernel; address and port expressions trim what is printed. Test a filtered variant:
ss -tanp state established 'dport = :443'
For a single socket, a two-step lookup is often more practical: use ss -tan to find the local and remote address, then run a targeted lsof -i or ss -tanp query for that port. Measure the two-step version if latency matters.
netstat -p is not free either, and its own manual calls the PID and program output "not trustworthy." If the PID is the reason you are running the command, that caveat matters as much as the timing.
Output volume and sink
A terminal can be the slowest component in the pipeline. Ten thousand lines of formatted text scrolling through a terminal emulator can easily dominate the measurement. Redirect to /dev/null to measure collection, redirect to a file to measure write cost, and pipe to wc -l to model a script. Use the same sink for both commands in a pair.
Record lines and bytes for every run. If ss emits significantly more rows than netstat, you are not comparing the same task, and the faster command may simply be doing less work.
| Cost center | Symptom | How to isolate |
|---|---|---|
| Collection | High system time in both tools | Compare -tan runs at the same socket count |
| Name resolution | Wall time far above CPU time; variable results | Add -n; test non-numeric separately with timeout
|
| Process attribution |
-p much slower than the same command without -p
|
Compare -tan and -tanp; record process and FD counts |
| Output | Wall time grows with terminal or parser speed | Redirect to /dev/null, a file, and wc -l
|
Step 6: Compare like-for-like tasks
Once you have timings, the next risk is comparing mismatched flags. A command mapping table keeps the task constant. Before translating an existing script flag by flag, use a netstat-to-ss command-equivalent table to map the job rather than the letters.
| Task | netstat |
ss |
Equivalence note |
|---|---|---|---|
| All TCP sockets, numeric | netstat -tan |
ss -tan |
Same named-socket set; output formats differ |
| Listening TCP with PID | netstat -tlnp |
ss -tlnp |
Both pay the -p attribution cost |
| Established TCP only | `netstat -tan \ | grep -w ESTABLISHED` | ss -tan state established |
| Socket counts by state | No direct equivalent | ss -s |
netstat -s reports SNMP counters, not socket counts |
| Routing table | netstat -rn |
ip route |
Different iproute2 tool |
| Interface statistics | netstat -i |
ip -s link |
Different iproute2 tool |
| Multicast memberships | netstat -g |
ip maddr |
Different iproute2 tool |
Three traps deserve special attention:
-
ss -sis notnetstat -s. The ss manual says-sprints summary statistics without parsing the socket list. The netstat manual says-sprints SNMP statistics for each protocol. They are not interchangeable, even though many migration tables pair them. -
-pchanges the workload. A row without-pand a row with-panswer different questions. Do not use the first to justify migrating the second. -
Output is not the same as work.
ss -Hremoves the header for scripts, but it does not make the collection faster.netstat | grepadds a process to the pipeline, but it also forcesnetstatto enumerate every socket before the filter sees a line.
Step 7: Interpret results and pick a default
Fill in a results table rather than eyeballing individual runs:
| Test | Command | Mean wall | Std dev | Mean CPU | Output lines | Ratio vs netstat |
|---|---|---|---|---|---|---|
| A | ss -tan |
|||||
| A | netstat -tan |
|||||
| B | ss -tanp |
|||||
| B | netstat -tanp |
|||||
| C | ss -tan state established |
|||||
| C | `netstat -tan \ | grep -w ESTABLISHED` |
Calculate the ratio as netstat mean divided by ss mean; a value above 1 means ss was faster. For test C, the netstat side includes the grep process, which is part of the pipeline you would actually run.
Then match the pattern to a cause:
| Pattern | Likely cause | Next check |
|---|---|---|
ss much faster, lower system time |
Netlink path is working; less data copied and parsed | None; record the result |
ss and netstat nearly equal at low socket counts |
Process startup and output dominate | Increase socket count before drawing a conclusion |
ss not faster at high socket counts |
ss may be falling back to /proc, or the output sink dominates |
strace the ss run; check tcp_diag; redirect to /dev/null
|
ss -p slower than netstat -p, or much slower than ss without -p
|
Process attribution is the bottleneck | Record process and FD counts; test a state or port filter |
| `netstat \ | grep slower than ss state` at high counts |
Userspace filtering versus kernel-side filtering |
Both slow without -n
|
DNS or service-name resolution | Fix the resolver or use -n
|
| Wall time far above CPU time | Blocking on DNS, terminal, or a pipe consumer | Change the sink; test with -n
|
A few rules of thumb:
- Treat differences under roughly 10–20% as noise unless the standard deviation is small and the ranking repeats across runs.
- If the ranking changes between repetitions, the host is not quiet enough for a microbenchmark. Fix that before optimizing the command.
- If
ss -pis slower on your host, that does not invalidatessfor inventory work. It means you have two workloads and may need two defaults.
A decision rule you can defend
| Situation | Default | Reason |
|---|---|---|
| Interactive triage with many sockets, no PID needed |
ss -tan or ss -tan state established
|
Netlink collection with kernel-side state filtering |
| PID needed, latency budget is tight |
ss -tanp, filtered by state or port |
-p is the expensive part; narrow the set first |
ss -p still too slow on your version |
ss -tan then a targeted lsof or ss -tanp query |
Avoid full attribution when you only need one socket |
| Script inventory |
ss -H -tn with explicit field parsing |
No header, numeric output; test on your oldest supported iproute2 |
| Windows | netstat -ano |
ss is a Linux tool; Windows netstat uses its own flags |
| macOS or BSD | netstat |
ss is not available; BSD flag meanings differ |
| Legacy Linux without iproute2 | netstat |
Fallback, not a performance choice |
| Per-protocol SNMP counters | netstat -s |
ss -s reports socket counts, not protocol counters |
On Windows, netstat -ano shows all connections, numeric addresses, and owning PIDs; the Windows netstat reference documents those flags and warns that -b, which adds the executable name, can be time-consuming and requires sufficient permissions. Do not assume Linux flags such as -t and -l carry over.
Migration checklist
- Benchmark the high-frequency inventory query first; that is where the architectural difference is largest.
- Benchmark every
-pquery separately; do not inherit the inventory result. - Add a fallback path for hosts where
ssis missing, and detect the/procfallback so you know when the performance assumption no longer holds. - Verify that
netstatexists on the images where you plan to use it as a fallback; do not assume net-tools is installed everywhere. - Test
ss -Hparsing against the oldest iproute2 version you support. - Keep a
netstatpath for Windows, macOS, BSD, and legacy Linux. - Re-run the benchmark after kernel or iproute2 upgrades;
-pbehavior is an implementation detail.
Conclusion
The netstat vs ss performance benchmark usually favors ss for bulk socket enumeration: netlink avoids the procfs text generation and parsing that make netstat slow at scale, and state filters can be applied inside the kernel. But the advantage is not unconditional. Process attribution with -p, name resolution without -n, a /proc fallback on a minimal kernel, and a terminal or slow parser can each erase or reverse the ranking.
Measure the workload you actually run. Record the kernel and iproute2 versions, the socket count, the user, and the output volume. Compare like-for-like tasks rather than matching flags. Then make the migration decision: ss for state-filtered and high-socket-count queries, a measured -p policy, and a netstat fallback where portability or a specific result wins.
Top comments (0)