DEV Community

netstat vs ss Performance Benchmark on Busy Linux Hosts

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 pro

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.