Netstat
Complete netstat reference covering network connections, listening ports, routing tables, and network statistics with practical examples
No commands found
Try adjusting your search term
Getting Started
Learn what netstat is and understand the basics of network monitoring
What is Netstat
Understand netstat and its capabilities for network diagnostics
Install and verify netstat installation
Netstat is part of the net-tools package and is available on most Linux systems for network monitoring.
# 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 --versionwhich netstat && echo "Netstat is installed"/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 comprehensive network diagnostics with various flags to show different network information.
# 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 -20netstat -h | grep -E "^ -[a-z]" | head -10-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
Understand basic netstat terminology and network concepts
Understand netstat output columns and fields
Understanding netstat column headers helps interpret network connection details accurately.
# 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 -5netstat -an | head -3 && echo "..." && netstat -an | tail -3Active 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.
# 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 -3netstat -an | grep -E "^tcp|^udp" | head -5tcp 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
Use ss command instead of netstat
The ss command is the preferred modern alternative to netstat with better performance and features.
# 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 :80which ss && echo "ss command is available"/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.
# 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 -2netstat -tln | head -2 && echo "---" && ss -tln | head -2Active 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 comprehensive network administration
Basic Usage
Master essential netstat commands for displaying connections
Show All Connections
Display all network connections on the system
Display all network connections
The -a flag shows all connections (both listening and established), while -n displays numeric addresses.
# 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 -apnetstat -an | head -5Active 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.
# 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"netstat -a | wc -l18- -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
Show all listening ports and services
The -l flag shows only listening sockets, useful for discovering what services are active on a system.
# 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 -lnpnetstat -ln | grep -E "LISTEN|Proto"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.
# 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 -k4sudo netstat -lnp | grep -E ":22 " | head -3tcp 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
Display TCP and UDP connections separately
Filter connections by protocol type to focus on specific communication types (TCP for reliable, UDP for fast).
# 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 -uenetstat -tn | grep ESTABLISHED | wc -l8- 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.
# 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"netstat -A inet -tn | head -4Active 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
Find process listening on specific port
The -p flag shows process ID and name, allowing identification of services using specific ports.
# 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 :3000sudo netstat -tlnp | grep ssh | head -2tcp 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.
# 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"netstat -an | grep 127.0.0.1 | head -3tcp 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
Show connections for specific process
The -p flag allows filtering connections by process name or PID for application-specific analysis.
# 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 -usudo netstat -anp | grep sshd | head -2tcp 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.
# 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 -usudo netstat -anp 2>/dev/null | grep LISTEN | wc -l12- 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
Show only established connections
Filtering for ESTABLISHED connections shows only active data-transfer connections, excluding listening sockets.
# 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 ESTABLISHEDnetstat -an | grep ESTABLISHED | wc -l5- 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.
# 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'netstat -an | grep ESTABLISHED | awk '{print $5}' | head -3203.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
Understand TCP connection states
TCP states represent different stages of connection lifecycle, from establishment to termination.
# 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 -10netstat -an | grep -o -E "LISTEN|ESTABLISHED|TIME_WAIT" | sort | uniq -c3 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
- Understanding states helps with network troubleshooting
Show connections in specific states
Specific state filtering reveals connection patterns and potential networking issues on the system.
# 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 -cnetstat -an | grep CLOSE_WAIT | wc -l0- TIME_WAIT connections are normal cleanup
- CLOSE_WAIT indicates unclosed sockets
- Many TIME_WAIT connections can be investigation point
- Use for performance analysis
Timeout and Waiting States
Analyze timeout and waiting connection states
Monitor TIME_WAIT connections
TIME_WAIT is a normal TCP state for graceful connection termination and preventing packet confusion.
# 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'netstat -an | grep TIME_WAIT | wc -l8- 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.
# 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_WAITsudo netstat -anp | grep CLOSE_WAIT | head -2tcp 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
Analyze connection flow states
Analyzing the distribution of connection states reveals network health and potential bottlenecks.
# 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'netstat -an | tail -n +3 | awk '{print $NF}' | sort | uniq -c | sort -rn | head -54 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.
# 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 -rnnetstat -an | grep SYN_SENT | wc -l0- 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
Display protocol statistics
TCP statistics show connection attempts, retransmissions, and error rates for protocol-level diagnostics.
# 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 tcpnetstat -st | head -15Tcp: 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.
# 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 packetsnetstat -s | grep "active connections"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
Display system routing table
Routing table shows how packets are directed to their destinations based on destination IP address.
# 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 -renetstat -rn | head -8Kernel 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.
# 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 5netstat -rn | grep "^default"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
Show network interface statistics
Interface statistics show packet counts, errors, and dropped packets for each network interface.
# 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 -tnetstat -i | head -5Kernel 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.
# 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}'netstat -i | grep -E "^eth0|^Iface"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
Monitor network activity continuously
Continuous monitoring with netstat -c or watch reveals real-time network activity and trends.
# 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; donenetstat -c --count=3Active 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.
# 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 3600donenetstat -an 2>/dev/null | grep ESTABLISHED | wc -l5- 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
Find process listening on specific port
Using grep with specific port number finds the listening process, showing PID and program name.
# 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}'donesudo netstat -tlnp | grep 22 | head -1tcp 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.
# 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/nullsudo netstat -tlnp | grep -E ":80 |:443 " | head -2tcp 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- Always use graceful shutdown first (SIGTERM)
- SIGKILL (-9) should be last resort
- Terminate 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
Track listening port changes
Comparing netstat snapshots over time helps detect unauthorized services or security changes.
# 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"sudo netstat -tlnp 2>/dev/null | wc -l8- 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.
# 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 -nnetstat -an 2>/dev/null | grep ESTABLISHED | wc -l8- 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
Identify hanging connections
Analyzing non-standard states reveals connections stuck in cleanup or waiting states.
# 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 -lsudo netstat -anp | grep -E "CLOSE_WAIT|FIN_WAIT" | head -3tcp 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 excessive amount 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.
# 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 tcpdumpnetstat -an | grep SYN_SENT | wc -l0- 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
Count connections by state
Aggregating connections by state provides overview of network health and connection patterns.
# 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 -rnnetstat -an 2>/dev/null | tail -n +3 | awk '{s[$NF]++} END {for (state in s) print state, s[state]}' | sort -k2 -rnLISTEN 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
Comprehensive reporting provides visibility into network usage and health metrics.
# 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 -cnetstat -an | tail -n +3 | awk '{print $1}' | sort | uniq -c5 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
Detect zombie and orphaned connections
Zombie/orphaned connections accumulate when applications don't properly close sockets.
# 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 10donenetstat -an 2>/dev/null | grep CLOSE_WAIT | wc -l0- CLOSE_WAIT indicates application bug
- Not system issue - application must close 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.
# 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, etcfisudo netstat -anp 2>/dev/null | grep CLOSE_WAIT | wc -l2- Restarting application is preferred solution
- Killing process is last resort
- Fix application code to proper close sockets
- Implement connection pooling and cleanup