---
title: "Netstat"
lang: "en"
author: "Mohammad Abu Mattar"
canonical: https://mkabumattar.com/netstat
---

[Home](/)›[Cheatsheets](/cheatsheets)

Cheatsheets

# Netstat

Complete netstat reference covering network connections, listening ports, routing tables, and network statistics with practical examples

6 Categories21 Sections42 ExamplesPublished: 01 Jan 2023Updated: 28 Feb 2025

NetstatNetworkConnectionsPortsLinuxNetworking

[Markdown for AI(opens in a new tab)](/netstat/index.md "Open the plain-Markdown version of this page, for pasting into an AI tool")

Series

[Linux & System Administration](/series/linux--system-administration)9/12

[PreviousNetcat](/cheatsheets/nc)[NextSed](/cheatsheets/sed)

All posts in this series (12)

Cheatsheets12

1.  [AWK](/cheatsheets/awk)
2.  [Bash](/cheatsheets/bash)
3.  [Chmod](/cheatsheets/chmod)
4.  [Cron](/cheatsheets/cron)
5.  [Curl](/cheatsheets/curl)
6.  [Find](/cheatsheets/find)
7.  [Grep](/cheatsheets/grep)
8.  [Netcat](/cheatsheets/nc)
9.  [NetstatYou are here](/cheatsheets/netstat)
10.  [Sed](/cheatsheets/sed)
11.  [SSH](/cheatsheets/ssh)
12.  [Linux Networking](/cheatsheets/linux-networking)

This netstat cheatsheet covers six categories, with worked examples and troubleshooting steps in each.

[Getting Started](#category-getting-started)

-   [What is Netstat](#section-what-is-netstat)
-   [Core Concepts](#section-netstat-concepts)
-   [Modern Alternatives](#section-modern-alternatives)

[Basic Usage](#category-basic-usage)

-   [Show All Connections](#section-show-all-connections)
-   [List Listening Ports](#section-list-listening-ports)
-   [Protocol-Specific Display](#section-protocol-specific-display)

[Finding Connections and Ports](#category-finding-connections-ports)

-   [Find Listening Port](#section-find-listening-port)
-   [Connections by Process](#section-connections-by-process)
-   [Established Connections](#section-established-connections)

[Connection States](#category-connection-states)

-   [TCP States Explained](#section-tcp-states-explained)
-   [Timeout and Waiting States](#section-timeout-waiting-states)
-   [Connection Flow Analysis](#section-connection-flow-analysis)

[Network Statistics and Analysis](#category-statistics-analysis)

-   [Network Statistics](#section-network-statistics)
-   [Routing Table](#section-routing-table)
-   [Interface Statistics](#section-interface-statistics)
-   [Continuous Monitoring](#section-continuous-monitoring)

[Practical Examples and Troubleshooting](#category-practical-examples)

-   [Find Process Using Port](#section-find-process-port)
-   [Monitor Port Changes Over Time](#section-monitor-port-changes)
-   [Diagnose Connection Hangs](#section-diagnose-hangs)
-   [Count Connections by State](#section-count-connections)
-   [Check for Zombie Connections](#section-zombie-connections)

No commands found

Try adjusting your search term

## Getting Started

What netstat is and the basics of network monitoring

### What is Netstat

Netstat and its capabilities for network diagnostics

#### Accessibility

Clear introduction to netstat capabilities and use cases

#### Keywords

introductionwhataboutnetstatnetworkdiagnostics

#### Install and verify netstat installation

Netstat is part of the net-tools package and is available on most Linux systems for network monitoring.

Code

Terminal window

```
# On Debian/Ubuntu systemssudo apt-get updatesudo apt-get install net-tools
# On CentOS/RHEL systemssudo yum install net-tools
# On Fedora systemssudo dnf install net-tools
# Verify installationwhich netstatnetstat --version
```

Execution

Terminal window

```
which netstat && echo "Netstat is installed"
```

Output

Terminal window

```
/usr/bin/netstatNetstat is installed
```

-   Netstat may not be installed by default on minimal Linux installations
-   Modern alternative is 'ss' command (comes with iproute2)
-   Both tools provide similar functionality
-   Some distributions are phasing out netstat in favor of ss

#### Netstat overview and capabilities

Netstat provides network diagnostics through various flags that show different network information.

Code

Terminal window

```
# Netstat displays:# - Active network connections# - Network interface statistics# - Routing tables# - Transport protocol statistics# - Per-protocol statistics
# Key features:# - Monitor network connections in real-time# - Find processes using specific ports# - Display listening ports and services# - Analyze network traffic patterns# - Troubleshoot connectivity issues
# Netstat is a diagnostic tool, not a monitoring daemon# Run it to get a snapshot of network state at that momentnetstat --help | head -20
```

Execution

Terminal window

```
netstat -h | grep -E "^  -[a-z]" | head -10
```

Output

Terminal window

```
-a, --all              show both listening and non-listening sockets-A, --family=FAMILY    Address family (inet|inet6|unix|ipx|ax25|netrom|rose|decnet|x25)-B, --sbufsize=SIZE    show both listening and non-listening sockets-c, --continuous       continuous listing-e, --extend           show additional information
```

-   Each flag can be combined with others for detailed analysis
-   Use -h or --help to see all available options
-   Netstat output can be very large on systems with many connections
-   Combine with grep for filtering results

### Core Concepts

Basic netstat terminology and network concepts

#### Accessibility

Explanation of key concepts for understanding netstat output

#### Keywords

conceptsterminologyconnectionsstatesprotocols

#### Understand netstat output columns and fields

Netstat column headers identify each part of a connection record.

Code

Terminal window

```
# Netstat output columns explained:# Proto: Protocol (tcp, udp, unix)# Recv-Q: Bytes in receive queue# Send-Q: Bytes in send queue# Local Address: Local IP:Port# Foreign Address: Remote IP:Port# State: Connection state# PID/Program name: Process using the connection
# Example interpretation:# tcp  0  0  127.0.0.1:3306  0.0.0.0:*  LISTEN  1234/mysqld# This means MySQL is listening on port 3306 (PID 1234)
netstat -tln | head -5
```

Execution

Terminal window

```
netstat -an | head -3 && echo "..." && netstat -an | tail -3
```

Output

Terminal window

```
Active Internet connections (servers and established)Proto Recv-Q Send-Q Local Address           Foreign Address         Statetcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN...tcp        0      0 192.168.1.100:55432    10.0.0.50:443           ESTABLISHED
```

-   Recv-Q and Send-Q show bytes waiting to be processed
-   State column shows connection lifecycle stage
-   PID/Program name requires root/sudo privileges with -p flag
-   Foreign Address shows remote connection endpoint

#### Understand connection states and transmission protocol

Connection states are part of the TCP state machine; UDP connections don't have states since it's connectionless.

Code

Terminal window

```
# Common connection states:# LISTEN - Socket is waiting for incoming connections# ESTABLISHED - Connection is active and data is flowing# SYN_SENT - Waiting for matching connection request# SYN_RECV - Received connection request, waiting for acknowledgment# TIME_WAIT - Connection closed, waiting for remaining packets# CLOSE_WAIT - Remote end closed, waiting for local close# LAST_ACK - Waiting for acknowledgment of connection close# CLOSED - Connection is closed# CLOSE - Initiating close on socket
# TCP provides reliable, ordered delivery (LISTEN, ESTABLISHED, etc)# UDP is connectionless (no STATE field in netstat -u output)
netstat -an | grep ESTABLISHED | head -3
```

Execution

Terminal window

```
netstat -an | grep -E "^tcp|^udp" | head -5
```

Output

Terminal window

```
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTENtcp        0      0 127.0.0.1:631          0.0.0.0:*               LISTENtcp6       0      0 :::22                   :::*                    LISTENudp        0      0 0.0.0.0:68              0.0.0.0:*udp        0      0 0.0.0.0:5353            0.0.0.0:*
```

-   Different states indicate different stages of connection lifecycle
-   TIME\_WAIT connections are normal and eventually expire
-   CLOSE\_WAIT can indicate zombie processes or unresponsive clients
-   UDP doesn't maintain connection state

### Modern Alternatives

Modern tools that replace netstat functionality

#### Accessibility

Information about netstat modern alternatives and when to use them

#### Best Practices

-   Install net-tools on systems that don't have netstat
-   Consider using ss instead of netstat on modern systems
-   Both tools read the same system data
-   Combine with other tools like grep and awk for filtering

#### Common Errors

-   **netstat: command not found:** Install net-tools package using apt/yum/dnf package manager
-   **No option: -p:** Run netstat with sudo for -p flag to show process information

#### Keywords

alternativesssmodernreplacementtools

[Learn more](https://man7.org/linux/man-pages/man8/netstat.8.html)

#### Use ss command instead of netstat

The ss command is the preferred modern alternative to netstat with better performance and features.

Code

Terminal window

```
# ss (socket statistics) is the modern replacement for netstat# ss is faster and provides more detailed information# ss comes with iproute2 package (usually pre-installed)
# Show all listening socketsss -tln
# Show all TCP connectionsss -ta
# Show specific portss -tln | grep :8080
# Show process names (requires sudo)sudo ss -tlnp | grep :80
```

Execution

Terminal window

```
which ss && echo "ss command is available"
```

Output

Terminal window

```
/usr/sbin/ssss command is available
```

-   ss uses the same flags as netstat
-   ss is faster because it reads from /proc/net directly
-   ss shows more detailed information (timer info, congestion window)
-   Both tools can be used interchangeably in most cases

#### Compare netstat and ss output

Both netstat and ss provide network statistics, with ss being the faster modern option.

Code

Terminal window

```
# Both commands show similar information# netstat output:# Proto Recv-Q Send-Q Local Address  Foreign Address  State# tcp   0      0      0.0.0.0:22     0.0.0.0:*        LISTEN
# ss output includes additional details:# State  Recv-Q Send-Q Local Address:Port  Peer Address:Port# LISTEN 0      128    0.0.0.0:22         0.0.0.0:*
# Performance comparison:# netstat scans /proc/net files# ss uses netlink sockets (faster)
echo "=== Using netstat ===" && netstat -tln | head -2echo "=== Using ss ===" && ss -tln | head -2
```

Execution

Terminal window

```
netstat -tln | head -2 && echo "---" && ss -tln | head -2
```

Output

Terminal window

```
Active Internet connections (only servers)Proto Recv-Q Send-Q Local Address           Foreign Address         State---State  Recv-Q Send-Q Local Address:Port              Peer Address:PortLISTEN 0      128    0.0.0.0:22                     0.0.0.0:*
```

-   ss is recommended for new scripts and tools
-   netstat is still useful for compatibility
-   Some systems only have ss installed
-   Learn both for well-rounded network administration

## Basic Usage

Core netstat commands for displaying connections

### Show All Connections

Display all network connections on the system

#### Accessibility

Commands to display all active network connections

#### Keywords

connectionsallactivelistingverbose

#### Display all network connections

The -a flag shows all connections (both listening and established), while -n displays numeric addresses.

Code

Terminal window

```
# Show all connections (listening and established)netstat -a
# Show only TCP connectionsnetstat -at
# Show only UDP connectionsnetstat -au
# Show all with numeric IP addressesnetstat -an
# Show all with program namessudo netstat -ap
```

Execution

Terminal window

```
netstat -an | head -5
```

Output

Terminal window

```
Active Internet connections (servers and established)Proto Recv-Q Send-Q Local Address           Foreign Address         Statetcp        0      0 127.0.0.1:631          0.0.0.0:*               LISTENtcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTENtcp6       0      0 :::22                   :::*                    LISTEN
```

-   Use -a to see complete network picture
-   \-n is faster than resolving hostnames
-   Combine -a with -n for numeric all connections
-   Output can be very large on systems with many connections

#### Show connections with detailed information

Extended flags provide additional details about connections, useful for diagnostics and analysis.

Code

Terminal window

```
# Extended information about all connectionsnetstat -ae
# Very detailed informationnetstat -aee
# All connections sorted by statenetstat -a | sort -k6
# Count connections by typenetstat -an | grep -c "ESTABLISHED"
# Show connections with timestampsnetstat -ae | grep -v "^Active"
```

Execution

Terminal window

```
netstat -a | wc -l
```

Output

Terminal window

```
18
```

-   \-e flag shows ethernet statistics
-   \-ee shows even more extended information
-   Useful for filtering and analyzing specific connection types
-   Can be piped to grep and other tools for filtering

### List Listening Ports

Display ports that are actively listening for connections

#### Accessibility

Commands to find listening ports and services

#### Keywords

listeningportsservicesopendaemons

#### Show all listening ports and services

The -l flag shows only listening sockets, useful for discovering what services are active on a system.

Code

Terminal window

```
# Show all listening sockets (listening only)netstat -l
# Show listening TCP portsnetstat -lt
# Show listening UDP portsnetstat -lu
# Show listening with numeric outputnetstat -ln
# Show listening with process informationsudo netstat -lnp
```

Execution

Terminal window

```
netstat -ln | grep -E "LISTEN|Proto"
```

Output

Terminal window

```
Proto Recv-Q Send-Q Local Address           Foreign Address         Statetcp        0      0 127.0.0.1:631          0.0.0.0:*               LISTENtcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTENtcp6       0      0 :::22                   :::*                    LISTENudp        0      0 0.0.0.0:68              0.0.0.0:*
```

-   \-l shows listening ports only
-   Combine with -n for numeric output
-   Use -p to see which process is listening
-   Requires sudo for -p flag to show all processes

#### Find specific listening services

Using grep with netstat helps identify specific listening services and their process IDs.

Code

Terminal window

```
# Show listening services with process namessudo netstat -lnp
# Show only HTTP and HTTPS listenerssudo netstat -lnp | grep -E ":80\s|:443\s"
# Show listening ports in numeric formnetstat -ln | grep -E "LISTEN|Proto"
# Check if specific port is listeningsudo netstat -lnp | grep ":8080"
# List all listening TCP ports sortednetstat -ln | grep tcp | grep LISTEN | sort -k4
```

Execution

Terminal window

```
sudo netstat -lnp | grep -E ":22 " | head -3
```

Output

Terminal window

```
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1234/sshdtcp6       0      0 :::22                   :::*                    LISTEN      1234/sshd
```

-   \-p flag requires root/sudo privileges
-   Useful for auditing open ports
-   Shows PID and program name for each service
-   Can be used for security verification

### Protocol-Specific Display

Show connections for specific network protocols

#### Accessibility

Commands to filter by network protocol type

#### Best Practices

-   Always use -n flag for faster output
-   Use -l to check available services
-   Combine -t and -n for TCP analysis
-   Use -p with sudo for process identification

#### Common Errors

-   **Too much output to parse:** Use grep to filter results or use less for pagination
-   **Permission denied:** Use sudo for -p flag to see process information

#### Keywords

protocoltcpudpfilteringspecific

[Learn more](https://man7.org/linux/man-pages/man8/netstat.8.html)

#### Display TCP and UDP connections separately

Filter connections by protocol type to focus on specific communication types (TCP for reliable, UDP for fast).

Code

Terminal window

```
# Show only TCP connectionsnetstat -t
# Show only TCP with numeric outputnetstat -tn
# Show only UDP connectionsnetstat -u
# Show only UDP with numeric outputnetstat -un
# Show TCP established connections onlynetstat -t | grep ESTABLISHED
# Show UDP with extended infonetstat -ue
```

Execution

Terminal window

```
netstat -tn | grep ESTABLISHED | wc -l
```

Output

Terminal window

```
8
```

-   TCP connections show state information
-   UDP is stateless (no connection states shown)
-   \-t flag for TCP, -u flag for UDP
-   Combine with -l for listening ports of specific protocol

#### Show both IPv4 and IPv6 connections

Different address families (inet/inet6) can be filtered separately to analyze specific connection types.

Code

Terminal window

```
# Show all internet connections (IPv4 and IPv6)netstat -A inet,inet6 -an
# Show IPv4 TCP onlynetstat -A inet -tn
# Show IPv6 TCP onlynetstat -A inet6 -tn
# Show connections and exclude IPv6netstat -A inet -an
# Show dual-stack listening (both IPv4 and IPv6)netstat -ln | grep -E "tcp|tcp6"
```

Execution

Terminal window

```
netstat -A inet -tn | head -4
```

Output

Terminal window

```
Active Internet connections (w/o servers)Proto Recv-Q Send-Q Local Address           Foreign Address         Statetcp        0      0 192.168.1.100:55432    203.0.113.50:443        ESTABLISHED
```

-   inet is IPv4, inet6 is IPv6
-   Some services listen on both IPv4 and IPv6
-   tcp6 indicates IPv6 TCP connections
-   Can be used for network troubleshooting

## Finding Connections and Ports

Locate specific connections, ports, and processes

### Find Listening Port

Discover which process is using a specific port

#### Accessibility

Commands to identify which process owns a port

#### Keywords

findportprocessspecificidentification

#### Find process listening on specific port

The -p flag shows process ID and name, allowing identification of services using specific ports.

Code

Terminal window

```
# Find what's listening on port 8080sudo netstat -tlnp | grep :8080
# Find what's listening on port 443sudo netstat -tlnp | grep :443
# Find process on any portsudo netstat -tlnp | grep -E ":80 |:443 |:3306 "
# Show all listening ports with processessudo netstat -tlnp | grep LISTEN
# Find IPv4 listeners on port 3000sudo netstat -tlnp | grep :3000
```

Execution

Terminal window

```
sudo netstat -tlnp | grep ssh | head -2
```

Output

Terminal window

```
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1234/sshdtcp6       0      0 :::22                   :::*                    LISTEN      1234/sshd
```

-   \-p flag requires sudo/root privileges
-   Useful for port conflict resolution
-   Shows both IPv4 and IPv6 listeners
-   PID can be used with kill to terminate the process

#### Find all connections from specific IP

Filtering netstat output by IP address helps locate connections from specific hosts or networks.

Code

Terminal window

```
# Find all connections to specific IPnetstat -an | grep 192.168.1.100
# Find connections to specific remote IPnetstat -an | grep 203.0.113.50
# Find all connections from specific portnetstat -an | grep ":8080 "
# Find connections to specific port on remotenetstat -an | grep " :443"
# Combine source and destination filtersnetstat -an | grep "192.168" | grep "ESTABLISHED"
```

Execution

Terminal window

```
netstat -an | grep 127.0.0.1 | head -3
```

Output

Terminal window

```
tcp        0      0 127.0.0.1:631          0.0.0.0:*               LISTENtcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTENunix  2      [ ]     DGRAM                    3456     @/tmp/var/run/user/1000
```

-   Use numeric output (-n) for faster filtering
-   Combine multiple grep conditions for precise filtering
-   Useful for security analysis and traffic auditing
-   Can identify unauthorized connections

### Connections by Process

Show all connections associated with specific processes

#### Accessibility

Commands to filter connections by process information

#### Keywords

processconnectionspidprogramapplication

#### Show connections for specific process

The -p flag allows filtering connections by process name or PID for application-specific analysis.

Code

Terminal window

```
# Show all nginx connectionssudo netstat -anp | grep nginx
# Show all MySQL database connectionssudo netstat -anp | grep mysql
# Show all SSH connectionssudo netstat -anp | grep sshd
# Show connections by PIDsudo netstat -anp | grep " 1234/
# List unique processes with connectionssudo netstat -anp | grep -oE '[0-9]+/[a-z]' | sort -u
```

Execution

Terminal window

```
sudo netstat -anp | grep sshd | head -2
```

Output

Terminal window

```
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1234/sshdtcp        0      128 192.168.1.100:22       192.168.1.50:55234     ESTABLISHED 1234/sshd
```

-   Requires sudo/root for -p flag
-   Useful for application performance analysis
-   Can identify connection leaks or excessive connections
-   Helps monitor multi-process applications

#### Analyze connection statistics by process

Using awk and sort with netstat helps aggregate statistics and identify problematic connection patterns.

Code

Terminal window

```
# Count connections per processsudo netstat -anp | tail -n +3 | awk '{print $NF}' | sort | uniq -c | sort -rn
# Find process with most connectionssudo netstat -anp | tail -n +3 | awk '{print $NF}' | sort | uniq -c | sort -rn | head -1
# Show established connections per processsudo netstat -anp | grep ESTABLISHED | awk '{print $NF}' | sort | uniq -c | sort -rn
# Find orphaned connectionssudo netstat -anp | grep "CLOSE_WAIT" | awk '{print $NF}' | sort -u
```

Execution

Terminal window

```
sudo netstat -anp 2>/dev/null | grep LISTEN | wc -l
```

Output

Terminal window

```
12
```

-   Useful for debugging connection leaks
-   Identifies most active processes
-   Can detect stuck connections
-   Helps optimize application performance

### Established Connections

Focus on active data-transfer connections

#### Accessibility

Commands to view and monitor active data transfers

#### Best Practices

-   Use -p with sudo for complete process information
-   Combine grep with awk for complex filtering
-   Use numeric output (-n) for consistent formatting
-   Regularly monitor for unexpected connections

#### Common Errors

-   **No results found when searching for port:** Check the service is running and listening
-   **awk/grep output not as expected:** Verify netstat output format matches your grep pattern

#### Keywords

establishedactivedata-transfermonitoringreal-time

[Learn more](https://man7.org/linux/man-pages/man8/netstat.8.html)

#### Show only established connections

Filtering for ESTABLISHED connections shows only active data-transfer connections, excluding listening sockets.

Code

Terminal window

```
# Show all established connectionsnetstat -an | grep ESTABLISHED
# Show established with process infosudo netstat -anp | grep ESTABLISHED
# Count established connectionsnetstat -an | grep ESTABLISHED | wc -l
# Show established TCP connections onlynetstat -tn | grep ESTABLISHED
# Monitor established connections to specific portsudo netstat -anp | grep ":443" | grep ESTABLISHED
```

Execution

Terminal window

```
netstat -an | grep ESTABLISHED | wc -l
```

Output

Terminal window

```
5
```

-   ESTABLISHED means active connection with data flowing
-   Useful for monitoring active connections
-   Helps identify connection hangs by their absence
-   Can be monitored continuously for real-time activity

#### Monitor active connections with details

Advanced filtering and awk processing allows detailed analysis of established connections by remote host.

Code

Terminal window

```
# Show established connections with full detailssudo netstat -anpe | grep ESTABLISHED
# Show established by remote hostnetstat -an | grep ESTABLISHED | awk '{print $5}' | cut -d: -f1 | sort | uniq -c
# List established connections with packet countssudo netstat -anp | grep ESTABLISHED | awk '{print $4, $5, $NF}'
# Monitor specific established connectionsudo netstat -anp | grep ESTABLISHED | grep 203.0.113.50
# Track connection duration (using state history)watch -n 1 'netstat -an | grep ESTABLISHED | wc -l'
```

Execution

Terminal window

```
netstat -an | grep ESTABLISHED | awk '{print $5}' | head -3
```

Output

Terminal window

```
203.0.113.50:443203.0.113.51:443203.0.113.52:443
```

-   Use awk for programmatic filtering
-   Can be piped to other commands for analysis
-   watch command enables real-time monitoring
-   Useful for identifying connection patterns

## Connection States

Understand and analyze TCP connection states

### TCP States Explained

Detailed explanation of TCP connection state lifecycle

#### Accessibility

Clear explanation of each TCP connection state

#### Keywords

statestcplifecyclestate-machinetransitions

#### Understand TCP connection states

TCP states represent different stages of connection lifecycle, from establishment to termination.

Code

Terminal window

```
# LISTEN - Waiting for incoming connections# Port is open and actively listening for connections# Used by server applications
# SYN_SENT - Initial connection request sent# Waiting for acknowledgment from remote host# Usually very brief state
# SYN_RECV - Connection request received and acknowledged# Waiting for acknowledgment back# Rare to see in netstat output
# ESTABLISHED - Active data transfer# Connection is open and both sides exchange data# Most common state for active connections
# FIN_WAIT_1 - Waiting for connection close# Local side initiated close# Waiting for acknowledgment
# FIN_WAIT_2 - Waiting for remote close# Local side closed sending# Waiting for remote side to close
netstat -an | grep -E "LISTEN|ESTABLISHED|TIME_WAIT" | head -10
```

Execution

Terminal window

```
netstat -an | grep -o -E "LISTEN|ESTABLISHED|TIME_WAIT" | sort | uniq -c
```

Output

Terminal window

```
3 ESTABLISHED5 LISTEN12 TIME_WAIT
```

-   Each state has specific meaning and transition rules
-   States are defined in TCP state machine (RFC 793)
-   Some states are transient and rarely seen
-   States narrow down where a connection stalled

#### Show connections in specific states

Specific state filtering reveals connection patterns and potential networking issues on the system.

Code

Terminal window

```
# Show TIME_WAIT connections (waiting to close)netstat -an | grep TIME_WAIT
# Show CLOSE_WAIT connections (remote closed)netstat -an | grep CLOSE_WAIT
# Show all non-listening connectionsnetstat -an | grep -v LISTEN | grep -v "^Proto"
# Show only listening portsnetstat -an | grep LISTEN
# Count connections by statenetstat -an | grep -oE "LISTEN|ESTABLISHED|TIME_WAIT|CLOSE_WAIT" | sort | uniq -c
```

Execution

Terminal window

```
netstat -an | grep CLOSE_WAIT | wc -l
```

Output

Terminal window

```
0
```

-   TIME\_WAIT connections are normal cleanup
-   CLOSE\_WAIT indicates unclosed sockets
-   Many TIME\_WAIT connections are worth investigating
-   Use for performance analysis

### Timeout and Waiting States

Analyze timeout and waiting connection states

#### Accessibility

Understanding and diagnosing timing-related connection issues

#### Keywords

timeoutwaitingstatescleanuplingering

#### Monitor TIME\_WAIT connections

TIME\_WAIT is a normal TCP state that completes connection termination and stops packets from an old connection being read by a new one.

Code

Terminal window

```
# TIME_WAIT is normal post-connection cleanup state# Connection is closed but local port still in use# Exists to prevent packet confusion
# Show all TIME_WAIT connectionsnetstat -an | grep TIME_WAIT
# Count TIME_WAIT by remote hostnetstat -an | grep TIME_WAIT | awk '{print $5}' | cut -d: -f1 | sort | uniq -c
# Show TIME_WAIT connections in detailssudo netstat -anp | grep TIME_WAIT
# Count TIME_WAIT per second (monitor trend)watch -n 1 'netstat -an | grep TIME_WAIT | wc -l'
```

Execution

Terminal window

```
netstat -an | grep TIME_WAIT | wc -l
```

Output

Terminal window

```
8
```

-   TIME\_WAIT lasts 2 MSL (Maximum Segment Lifetime)
-   Default is often 60 seconds
-   Many TIME\_WAIT is normal for servers
-   Can be tuned with kernel parameters if excessive

#### Identify and analyze CLOSE\_WAIT connections

CLOSE\_WAIT connections indicate the remote side closed but the local application hasn't closed its socket.

Code

Terminal window

```
# CLOSE_WAIT means remote closed but local still open# Usually indicates application bug with unclosed sockets# Can lead to resource leaks if not addressed
# Show all CLOSE_WAIT connectionsnetstat -an | grep CLOSE_WAIT
# Show CLOSE_WAIT with process infosudo netstat -anp | grep CLOSE_WAIT
# Find which application has CLOSE_WAITsudo netstat -anp | grep CLOSE_WAIT | awk '{print $NF}' | sort | uniq -c
# Monitor CLOSE_WAIT countwatch -n 5 'netstat -an | grep CLOSE_WAIT | wc -l'
# List all CLOSE_WAIT connections detailssudo netstat -anpe | grep CLOSE_WAIT
```

Execution

Terminal window

```
sudo netstat -anp | grep CLOSE_WAIT | head -2
```

Output

Terminal window

```
tcp        0      0 192.168.1.100:55432    203.0.113.60:3306     CLOSE_WAIT  5678/pythontcp        0      0 192.168.1.100:55433    203.0.113.61:3306     CLOSE_WAIT  5678/python
```

-   CLOSE\_WAIT accumulation suggests application bug
-   Applications should close sockets properly
-   Common in poorly-written database client code
-   Requires application fix, not system configuration

### Connection Flow Analysis

Analyze full connection flow and state transitions

#### Accessibility

Analyzing connection patterns and flow

#### Best Practices

-   Regularly monitor TCP connection states
-   Track trends in FIN\_WAIT and TIME\_WAIT counts
-   Investigate CLOSE\_WAIT accumulation
-   Use automated alerting for abnormal patterns

#### Common Errors

-   **Can't determine which process has CLOSE\_WAIT:** Use sudo with -p flag to see process information
-   **TIME\_WAIT connections growing indefinitely:** This is actually normal; TIME\_WAIT is automatic cleanup

#### Keywords

flowtransitionsanalysispatternsdiagnostics

[Learn more](https://man7.org/linux/man-pages/man8/netstat.8.html)

#### Analyze connection flow states

Analyzing the distribution of connection states reveals network health and potential bottlenecks.

Code

Terminal window

```
# Connections follow this general flow:# Client: CLOSED -> SYN_SENT -> ESTABLISHED -> FIN_WAIT_1 -> FIN_WAIT_2 -> CLOSED# Server: LISTEN -> SYN_RECV -> ESTABLISHED -> CLOSE_WAIT -> LAST_ACK -> CLOSED
# Normal healthy flow shows mostly LISTEN and ESTABLISHEDnetstat -an | awk '{print $NF}' | sort | uniq -c | sort -rn | head -10
# Check for abnormal accumulation of statesnetstat -an | grep -E "SYN_SENT|SYN_RECV" | wc -l
# Show connection setup ratewatch -n 1 'netstat -an | grep ESTABLISHED | wc -l'
```

Execution

Terminal window

```
netstat -an | tail -n +3 | awk '{print $NF}' | sort | uniq -c | sort -rn | head -5
```

Output

Terminal window

```
4 LISTEN3 ESTABLISHED2 TIME_WAIT1 CLOSE_WAIT
```

-   Mostly LISTEN and ESTABLISHED is healthy
-   Many SYN states indicates port scanning or DDoS
-   Many CLOSE\_WAIT indicates application bugs
-   Monitor trends over time for anomalies

#### Detect and diagnose connection issues

Investigating abnormal connection states helps identify attacks, bugs, or network issues.

Code

Terminal window

```
# Excessive SYN_SENT might indicate port scanning attacknetstat -an | grep SYN_SENT
# Excessive SYN_RECV indicates half-open connections (SYN flood)netstat -an | grep SYN_RECV | wc -l
# Stuck connections in FIN_WAIT statenetstat -an | grep FIN_WAIT
# Reset connections (LAST_ACK)netstat -an | grep LAST_ACK | wc -l
# Full diagnostic reportecho "=== Connection State Summary ===" && \netstat -an | tail -n +3 | awk '{print $NF}' | sort | uniq -c | sort -rn
```

Execution

Terminal window

```
netstat -an | grep SYN_SENT | wc -l
```

Output

Terminal window

```
0
```

-   SYN\_SENT indicates client attempting connection
-   Many SYN\_SENT from single source indicates attack
-   FIN\_WAIT indicates normal closure
-   Monitor for abnormal patterns

## Network Statistics and Analysis

Display and analyze network statistics and routing information

### Network Statistics

Show protocol-level statistics and metrics

#### Accessibility

Commands to display detailed network statistics

#### Keywords

statisticsstatsmetricsprotocolstraffic

#### Display protocol statistics

TCP statistics show connection attempts, retransmissions, and error rates for protocol-level diagnostics.

Code

Terminal window

```
# Show statistics for all protocolsnetstat -s
# Show TCP statistics onlynetstat -st
# Show UDP statistics onlynetstat -su
# Show ICMP statistics (ping errors)netstat -si
# Show statistics for specific protocolnetstat -sp tcp
```

Execution

Terminal window

```
netstat -st | head -15
```

Output

Terminal window

```
Tcp:    4567 active connections openings    1234 passive connection openings    89 failed connection attempts    2 connection resets received    5 connections established    234567 segments received    234567 segments sent out    45 segments retransmitted    0 bad segments received    89 resets sent    156 packets received    234 packets to unknown port received
```

-   Active openings = connections initiated by this system
-   Passive openings = connections received from others
-   Failed attempts indicate connection problems
-   Retransmissions indicate packet loss or latency

#### Analyze connection and packet statistics

Analyzing connection statistics helps understand network activity patterns and identify performance issues.

Code

Terminal window

```
# Show statistics for TCP connectionsnetstat -s | grep -A 20 "^Tcp:"
# Show packet loss indicatorsnetstat -s | grep -i "segment"
# Show connection attempt statisticsnetstat -s | grep -i "active\|passive\|failed"
# Show error statisticsnetstat -s | grep -i "error\|reset\|bad"
# Compare TCP vs UDP trafficecho "=== TCP ===" && netstat -st | grep packets \&& echo "=== UDP ===" && netstat -su | grep packets
```

Execution

Terminal window

```
netstat -s | grep "active connections"
```

Output

Terminal window

```
4567 active connections openings
```

-   High retransmission rates indicate network problems
-   Failed connection attempts suggest unreachable services
-   Compare statistics over time to detect trends
-   Use for performance baseline and anomaly detection

### Routing Table

Display and analyze network routing information

#### Accessibility

Commands to view and understand network routes

#### Keywords

routingtableroutesgatewaynetwork

#### Display system routing table

Routing table shows how packets are directed to their destinations based on destination IP address.

Code

Terminal window

```
# Show routing tablenetstat -r
# Show routing table with numeric outputnetstat -rn
# Show IPv4 routing table onlynetstat -rn -A inet
# Show IPv6 routing tablenetstat -rn -A inet6
# Show routing details with extended infonetstat -re
```

Execution

Terminal window

```
netstat -rn | head -8
```

Output

Terminal window

```
Kernel IP routing tableDestination     Gateway         Genmask         Flags Metric Ref    Use Ifacedefault         192.168.1.1     0.0.0.0         UG    100    0        0 eth0192.168.1.0     0.0.0.0         255.255.255.0   U     256    0        0 eth0172.17.0.0      0.0.0.0         255.255.0.0     U     0      0        0 docker0
```

-   Destination: Target network or 'default' for fallback
-   Gateway: Next hop router (0.0.0.0 means direct interface)
-   Genmask: Subnet mask for the route
-   Flags: U=up, G=gateway, H=host-specific

#### Analyze and troubleshoot routes

Default gateway and route analysis helps troubleshoot connectivity issues and understand network structure.

Code

Terminal window

```
# Show all routes with metricsnetstat -rn | grep -v "^Kernel"
# Show default gatewaynetstat -rn | grep "^default"
# Show specific network routesnetstat -rn | grep "192.168"
# Count routes per interfacenetstat -rn | awk '{print $NF}' | sort | uniq -c
# Show routes sorted by interfacenetstat -rn | sort -k 5
```

Execution

Terminal window

```
netstat -rn | grep "^default"
```

Output

Terminal window

```
default         192.168.1.1     0.0.0.0         UG    100    0        0 eth0
```

-   0.0.0.0 gateway means direct connection (no routing needed)
-   Multiple gateways indicate complex routing
-   Metric indicates route preference
-   Use for detecting misconfigured routes

### Interface Statistics

Display network interface statistics and metrics

#### Accessibility

Commands to view network interface metrics

#### Keywords

interfacestatisticseth0lopacketsbytes

#### Show network interface statistics

Interface statistics show packet counts, errors, and dropped packets for each network interface.

Code

Terminal window

```
# Show interface statisticsnetstat -i
# Show interface statistics with extended infonetstat -ie
# Show very detailed interface informationnetstat -iee
# Show interface MTU and other detailsnetstat -ie | head -10
# Format output for readabilitynetstat -i | column -t
```

Execution

Terminal window

```
netstat -i | head -5
```

Output

Terminal window

```
Kernel Interface tableIface      MTU    RX-OK RX-ERR RX-DRP RX-OVR    TX-OK TX-ERR TX-DRP TX-OVR Flgdocker0   1500 34567890      0      0      0  234567      0      0      0 BMRUeth0      1500 987654321      0      5      0 2345678      0      3      0 BMRU
```

-   RX-OK: Packets received successfully
-   TX-OK: Packets transmitted successfully
-   RX-ERR/TX-ERR: Transmission errors
-   RX-DRP/TX-DRP: Dropped packets

#### Analyze interface health and performance

Detailed analysis of per-interface statistics helps identify problematic network interfaces or links.

Code

Terminal window

```
# Show detailed interface informationnetstat -ie
# Extract interface errorsnetstat -i | awk '{print $1, $3, $4}'
# Check for packet lossnetstat -i | awk '{if (NR>2 && $4>0) print $1, "has errors"}'
# Show interfaces with dropped packetsnetstat -i | awk '{if (NR>2 && $5>0) print $1, "dropped:", $5}'
# Calculate error ratesnetstat -i | awk '{if (NR>2) print $1, "RX:", $3, "Errors:", $4}'
```

Execution

Terminal window

```
netstat -i | grep -E "^eth0|^Iface"
```

Output

Terminal window

```
Kernel Interface tableeth0      1500 987654321      0      5      0 2345678      0      3      0 BMRU
```

-   Any errors indicate potential network problems
-   Dropped packets suggest buffer overflow or network congestion
-   MTU mismatch can cause dropping
-   Monitor trends for early issue detection

### Continuous Monitoring

Monitor network statistics and connections in real-time

#### Accessibility

Commands for real-time network monitoring

#### Best Practices

-   Use -s flag for protocol statistics
-   Use -r flag to check routing configuration
-   Use -i flag to verify interface health
-   Monitor statistics periodically for trends

#### Common Errors

-   **netstat -c produces no output:** The -c flag may not be available on all systems
-   **Can't understand routing table output:** Use -n flag for numeric addresses instead of hostnames

#### Keywords

monitoringcontinuousreal-timewatchtrends

[Learn more](https://man7.org/linux/man-pages/man8/netstat.8.html)

#### Monitor network activity continuously

Continuous monitoring with netstat -c or watch reveals real-time network activity and trends.

Code

Terminal window

```
# Monitor connections with continuous updatesnetstat -c
# Monitor specific metric (using watch command)watch -n 1 'netstat -an | grep ESTABLISHED | wc -l'
# Watch listening ports for changeswatch -n 5 'netstat -tlnp'
# Monitor interface counterswatch -n 1 'netstat -i'
# Track connection count trendfor i in {1..5}; do echo "Count: $(netstat -an | grep ESTABLISHED | wc -l)"; sleep 1; done
```

Execution

Terminal window

```
netstat -c --count=3
```

Output

Terminal window

```
Active Internet connections (w/o servers)Proto Recv-Q Send-Q Local Address           Foreign Address         Statetcp        0      0 192.168.1.100:60123    203.0.113.5:443         ESTABLISHEDtcp        0      128 192.168.1.100:22       192.168.1.50:55234     ESTABLISHED
Active Internet connections (w/o servers)Proto Recv-Q Send-Q Local Address           Foreign Address         State
```

-   \-c flag causes netstat to refresh frequently
-   watch command provides nicer formatted output
-   Useful for performance testing and diagnostics
-   Can be combined with other tools for alerting

#### Create monitoring scripts

Custom monitoring scripts can automate tracking and alerting for connection anomalies.

Code

```
# Monitor and alert on connection count#!/bin/bashTHRESHOLD=1000while true; do  COUNT=$(netstat -an | grep ESTABLISHED | wc -l)  if [ $COUNT -gt $THRESHOLD ]; then    echo "Alert: $COUNT established connections (threshold: $THRESHOLD)"  fi  sleep 60done
# Log connection statistics hourly#!/bin/bashwhile true; do  echo "$(date): $(netstat -an | grep ESTABLISHED | wc -l) connections" >> connections.log  sleep 3600done
```

Execution

Terminal window

```
netstat -an 2>/dev/null | grep ESTABLISHED | wc -l
```

Output

Terminal window

```
5
```

-   Scripts can monitor thresholds and alert
-   Useful for production system monitoring
-   Can log data for capacity planning
-   Integrate with monitoring systems

## Practical Examples and Troubleshooting

Real-world use cases and troubleshooting techniques

### Find Process Using Port

Identify which process is bound to a specific port

#### Accessibility

Commands to identify process ownership of ports

#### Keywords

findprocessportidentifytroubleshooting

#### Find process listening on specific port

Using grep with specific port number finds the listening process, showing PID and program name.

Code

Terminal window

```
# Find what process is using port 8080sudo netstat -tlnp | grep :8080
# Alternative: Use grep to extract process namePROCESS=$(sudo netstat -tlnp | grep :8080 | awk '{print $NF}')echo "Port 8080 is used by: $PROCESS"
# Show complete process command linePID=$(sudo netstat -tlnp | grep :8080 | awk '{print $NF}' | cut -d/ -f1)ps aux | grep $PID
# List multiple ports at oncefor port in 80 443 3306 5432; do  echo -n "Port $port: "  sudo netstat -tlnp | grep ":$port " | awk '{print $NF}'done
```

Execution

Terminal window

```
sudo netstat -tlnp | grep 22 | head -1
```

Output

Terminal window

```
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1234/sshd
```

-   Requires sudo/root for -p flag
-   PID can be used with ps or ps aux for details
-   Useful for resolving port conflicts
-   Can be automated in scripts

#### Kill process using specific port

Extracting PID from netstat output allows programmatic process termination when needed.

Code

Terminal window

```
# Find and kill process on port 8080PID=$(sudo netstat -tlnp | grep :8080 | awk '{print $NF}' | cut -d/ -f1)if [ ! -z "$PID" ]; then  echo "Killing process $PID on port 8080"  sudo kill -9 $PIDelse  echo "No process found on port 8080"fi
# One-liner to kill process on portsudo kill -9 $(sudo netstat -tlnp | grep :8080 | awk '{print $NF}' | cut -d/ -f1)
# Graceful kill (SIGTERM first, then SIGKILL)PID=$(sudo netstat -tlnp | grep :8080 | awk '{print $NF}' | cut -d/ -f1)sudo kill $PID && sleep 2 && sudo kill -9 $PID 2>/dev/null
```

Execution

Terminal window

```
sudo netstat -tlnp | grep -E ":80 |:443 " | head -2
```

Output

Terminal window

```
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      5678/nginxtcp        0      0 0.0.0.0:443             0.0.0.0:*               LISTEN      5678/nginx
```

-   Send SIGTERM first so the process can shut down cleanly
-   SIGKILL (-9) should be last resort
-   Terminating the wrong process can cause data loss
-   Better to use service/systemctl commands when possible

### Monitor Port Changes Over Time

Track changes to listening ports and active connections

#### Accessibility

Methods to track network changes

#### Keywords

monitorchangestrendingbaselinecomparison

#### Track listening port changes

Comparing netstat snapshots over time helps detect unauthorized services or security changes.

Code

Terminal window

```
# Create initial port listsudo netstat -tlnp > /tmp/ports_before.txt
# After some time, comparesudo netstat -tlnp > /tmp/ports_after.txtdiff /tmp/ports_before.txt /tmp/ports_after.txt
# Monitor for new services appearingsudo netstat -tlnp | grep -v "LISTEN" | wc -l
# Create baseline of listening servicesecho "=== Baseline at $(date) ===" >> port_baseline.logsudo netstat -tlnp | grep LISTEN >> port_baseline.log
# Check for unexpected open portssudo netstat -tlnp | grep -v "ssh\|sshd"
```

Execution

Terminal window

```
sudo netstat -tlnp 2>/dev/null | wc -l
```

Output

Terminal window

```
8
```

-   Use cron to periodically capture port state
-   Baseline helps identify anomalies
-   Useful for security audits
-   Can trigger alerts on changes

#### Monitor connection count trends

Continuous tracking of connection counts reveals usage patterns and capacity planning needs.

Code

Terminal window

```
# Log connection counts hourly*/60 * * * * echo "$(date +\%Y-\%m-\%d\ \%H:\%M:\%S),$(netstat -an | grep ESTABLISHED | wc -l)" >> connections.csv
# Script to collect statistics over time#!/bin/bashfor i in {1..60}; do  ESTABLISHED=$(netstat -an | grep ESTABLISHED | wc -l)  TIME=$(date "+%Y-%m-%d %H:%M:%S")  echo "$TIME: $ESTABLISHED"  (( i < 60 )) && sleep 60done > connection_trends.log
# Analyze connection growthtail -50 connections.csv | awk -F',' '{print $NF}' | sort -n
```

Execution

Terminal window

```
netstat -an 2>/dev/null | grep ESTABLISHED | wc -l
```

Output

Terminal window

```
8
```

-   Use cron for automated periodic collection
-   Store in database or CSV for analysis
-   Identify peak times and growth trends
-   Use for performance tuning

### Diagnose Connection Hangs

Identify and analyze stuck or hanging connections

#### Accessibility

Troubleshooting techniques for connection problems

#### Keywords

diagnosehangstuckissuedebugging

#### Identify hanging connections

Analyzing non-standard states reveals connections stuck in cleanup or waiting states.

Code

Terminal window

```
# Show connections not in ESTABLISHED or LISTEN statenetstat -an | grep -v ESTABLISHED | grep -v LISTEN | grep -E "^tcp|^udp"
# Show CLOSE_WAIT connections (remote closed but local open)netstat -an | grep CLOSE_WAIT
# Show FIN_WAIT connections (waiting for close to complete)netstat -an | grep FIN_WAIT
# Identify which process has hanging connectionssudo netstat -anp | grep CLOSE_WAIT | awk '{print $NF}' | sort -u
# Check for TIME_WAIT accumulation (possible port exhaustion)netstat -an | grep TIME_WAIT | wc -l
```

Execution

Terminal window

```
sudo netstat -anp | grep -E "CLOSE_WAIT|FIN_WAIT" | head -3
```

Output

Terminal window

```
tcp        0      0 192.168.1.100:55234    203.0.113.100:3306     CLOSE_WAIT  5678/app
```

-   CLOSE\_WAIT indicates application bug
-   FIN\_WAIT is normal, but a large number of them is unusual
-   High TIME\_WAIT can indicate port exhaustion risk
-   Fix applications to properly close connections

#### Troubleshoot connection timeouts

Diagnosing timeouts involves checking connection states and using tools like nc for verification.

Code

Terminal window

```
# Test connectivity to specific hostnc -zv 203.0.113.50 443
# Check if port is accessible via netstatnetstat -an | grep 203.0.113.50
# Verify listening port with specific bindingsudo netstat -tlnp | grep ":8080"
# Check for firewall issues (look for many SYN_SENT)netstat -an | grep SYN_SENT | head -5
# Trace connection attempt stepssudo tcpdump -i any -n 'port 8080' &# Then attempt connection in another terminal# Use Ctrl+C to stop tcpdump
```

Execution

Terminal window

```
netstat -an | grep SYN_SENT | wc -l
```

Output

Terminal window

```
0
```

-   SYN\_SENT indicates connection attempt
-   Many SYN\_SENT from one source suggests blocked port
-   Check firewall rules with iptables or firewall-cmd
-   Use tcpdump for packet-level debugging

### Count Connections by State

Analyze connection distribution and statistics

#### Accessibility

Commands to analyze and report on connection counts

#### Keywords

countstatisticsdistributionanalysisreporting

#### Count connections by state

Aggregating connections by state provides overview of network health and connection patterns.

Code

Terminal window

```
# Show count of each connection statenetstat -an | tail -n +3 | awk '{print $NF}' | sort | uniq -c | sort -rn
# Show only unique states and their countsnetstat -an | grep -o -E "LISTEN|ESTABLISHED|TIME_WAIT|CLOSE_WAIT" | sort | uniq -c
# Count established connectionsnetstat -an | grep ESTABLISHED | wc -l
# Count listening socketsnetstat -an | grep LISTEN | wc -l
# Show breakdown with nice formattingecho "Connection Statistics ($(date))"echo "================================"netstat -an | tail -n +3 | awk '{s[$NF]++} END {for (state in s) print state, s[state]}' | sort -k2 -rn
```

Execution

Terminal window

```
netstat -an 2>/dev/null | tail -n +3 | awk '{s[$NF]++} END {for (state in s) print state, s[state]}' | sort -k2 -rn
```

Output

Terminal window

```
LISTEN 5ESTABLISHED 3TIME_WAIT 8
```

-   High LISTEN count is normal
-   High ESTABLISHED indicates heavy usage
-   High TIME\_WAIT is normal cleanup
-   Any CLOSE\_WAIT indicates application issues

#### Generate connection reports

Regular reporting provides visibility into network usage and health metrics.

Code

```
# Generate connection report#!/bin/bashecho "Network Connection Report - $(date)"echo "======================================"echo ""echo "Total connections:"netstat -an | tail -n +3 | wc -lecho ""echo "Connections by state:"netstat -an | tail -n +3 | awk '{s[$NF]++} END {for (state in s) printf "  %-15s %d\n", state, s[state]}' | sort -k2 -rnecho ""echo "Top ports in use:"netstat -an | tail -n +3 | awk '{print $4}' | cut -d: -f2 | sort | uniq -c | sort -rn | head -5echo ""echo "Connection by protocol:"netstat -an | tail -n +3 | awk '{print $1}' | sort | uniq -c
# Simpler versionnetstat -an | tail -n +3 | awk '{print $1}' | sort | uniq -c
```

Execution

Terminal window

```
netstat -an | tail -n +3 | awk '{print $1}' | sort | uniq -c
```

Output

Terminal window

```
5 tcp2 tcp63 udp
```

-   Useful for documentation and audits
-   Can be scheduled via cron for regular reports
-   Export to files for archival
-   Share with team or stakeholders

### Check for Zombie Connections

Identify and clean up orphaned or zombie connections

#### Accessibility

Identifying and managing zombie connections

#### Best Practices

-   Regularly monitor netstat output for anomalies
-   Create baseline snapshots for comparison
-   Use process identification (-p flag) to find culprits
-   Combine with other tools (grep, awk, watch) for analysis
-   Document findings and share with team

#### Common Errors

-   **Grep pattern doesn't match expected output:** Check netstat output format with cat, adjust grep pattern
-   **Can't kill process (permission denied):** Use sudo or run as appropriate user

#### Keywords

zombieorphanedcleanupmaintenancemonitoring

[Learn more](https://man7.org/linux/man-pages/man8/netstat.8.html)

#### Detect zombie and orphaned connections

Zombie/orphaned connections accumulate when applications don't properly close sockets.

Code

Terminal window

```
# Show CLOSE_WAIT connections (possible zombies)netstat -an | grep CLOSE_WAIT | wc -l
# Show LAST_ACK connections (connection cleanup)netstat -an | grep LAST_ACK | wc -l
# Show all non-standard connection statesnetstat -an | grep -v -E "LISTEN|ESTABLISHED|^Proto|^Active"
# Identify which application has most CLOSE_WAITsudo netstat -anp | grep CLOSE_WAIT | awk '{print $NF}' | cut -d/ -f2 | sort | uniq -c | sort -rn
# Monitor CLOSE_WAIT trendfor i in {1..5}; do  echo "Check $i: $(netstat -an | grep CLOSE_WAIT | wc -l) CLOSE_WAIT connections"  sleep 10done
```

Execution

Terminal window

```
netstat -an 2>/dev/null | grep CLOSE_WAIT | wc -l
```

Output

Terminal window

```
0
```

-   CLOSE\_WAIT indicates application bug
-   Not a system issue. The application must close its sockets properly
-   TIME\_WAIT is normal and automatic
-   Monitor trends to identify problem apps

#### Clean up zombie connections

Cleaning up zombie connections requires fixing the application code or restarting the service.

Code

Terminal window

```
# Show process with CLOSE_WAIT connectionssudo netstat -anp | grep CLOSE_WAIT
# Restart problematic application (best approach)# sudo systemctl restart service-name
# Force close connections if necessary (not recommended)# This forces the process to drop connections# sudo kill -9 <PID>
# Monitor after restartwatch -n 5 'sudo netstat -anp | grep CLOSE_WAIT | wc -l'
# Create alert scriptCLOSE_WAIT=$(netstat -an | grep CLOSE_WAIT | wc -l)if [ $CLOSE_WAIT -gt 50 ]; then  echo "Alert: $CLOSE_WAIT CLOSE_WAIT connections detected"  # Send alert, restart app, etcfi
```

Execution

Terminal window

```
sudo netstat -anp 2>/dev/null | grep CLOSE_WAIT | wc -l
```

Output

Terminal window

```
2
```

-   Restarting application is preferred solution
-   Killing process is last resort
-   Fix the application code to close sockets properly
-   Implement connection pooling and cleanup

Was this useful?

## Tags

#Netstat#Network#Connections#Ports#Linux#Networking

## Share

[Facebook](https://facebook.com/sharer/sharer.php?u=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fnetstat "Share on Facebook")[Twitter](https://twitter.com/intent/tweet/?text=Netstat&url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fnetstat "Share on Twitter")[LinkedIn](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fnetstat&title=Netstat&summary=Complete%20netstat%20reference%20covering%20network%20connections%2C%20listening%20ports%2C%20routing%20tables%2C%20and%20network%20statistics%20with%20practical%20examples&source=https://mkabumattar.com "Share on LinkedIn")[WhatsApp](https://wa.me/?text=Netstat%20https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fnetstat "Share on WhatsApp")[Telegram](https://t.me/share/url?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fnetstat&text=Netstat "Share on Telegram")[Reddit](https://www.reddit.com/submit?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fnetstat&title=Netstat "Share on Reddit")[Hacker News](http://news.ycombinator.com/submitlink?u=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fnetstat&t=Netstat "Share on Hacker News")[Pinterest](https://pinterest.com/pin/create/button/?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fnetstat&media=&description=Complete%20netstat%20reference%20covering%20network%20connections%2C%20listening%20ports%2C%20routing%20tables%2C%20and%20network%20statistics%20with%20practical%20examples "Share on Pinterest")[Email](<mailto:?subject=Netstat&body=Check out this article: https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fnetstat>)

## Comments

## You might also enjoy

More posts on similar topics

## [Netcat](/cheatsheets/nc)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   Networking
-   Tools
-   System Administration
-   Port Scanning

This netcat cheatsheet covers TCP/UDP connections, file transfers, port scanning, banner grabbing, and advanced network operations.

#Netcat#Nc#Network+4 tags

[read more](/cheatsheets/nc)

## [Cron](/cheatsheets/cron)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   System Administration
-   Linux
-   Scheduling
-   Automation
-   Tools

Quick reference Field layout Min Hour Day Month Weekday Command\* /path/to/command ┬ ┬ ┬ ┬ ┬ │ │ │ │ └───── Weekday (0=Sunday,

#Cron#Crontab#Scheduling+3 tags

[read more](/cheatsheets/cron)

## [Chmod](/cheatsheets/chmod)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   Programming
-   Linux
-   File Management
-   Tools

Complete chmod reference covering file permissions, recursive changes with -v and -c, reference mode, logical operators, batch operations, practical examples, and security best practices for Linux fil

#Chmod#Permissions#File Permissions+5 tags

[read more](/cheatsheets/chmod)

## [Find](/cheatsheets/find)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   Programming
-   Linux
-   File Operations
-   Tools

Best practices for find command usageAlways quote patterns to prevent shell expansion of special characters Use -type f first in find expressions for optimal performance \*\*Prune hea

#Find#File Search#Discovery+3 tags

[read more](/cheatsheets/find)

## [Grep](/cheatsheets/grep)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   Programming
-   Linux
-   Text Processing
-   Tools

Best practices for grep usageAlways quote patterns to prevent shell interpretation of special characters Use -E flag for complex patterns to avoid escaping issues with basic regex

#Grep#Search#Pattern Matching+3 tags

[read more](/cheatsheets/grep)

## [Sed](/cheatsheets/sed)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   Programming
-   Linux
-   Text Processing
-   Tools

This sed reference covers basic text substitution through advanced scripting techniques, with practical examples for text processing, file editing, and automation.

#Sed#Stream Editor#Text Transformation+3 tags

[read more](/cheatsheets/sed)

6 related posts
