Mastering the Linux Netstat Command: From Basics to Advanced Network Monitoring

LightNode
By LightNode ·

Introduction

The netstat (network statistics) command is one of the most essential networking tools in the Linux system administrator's toolkit. This versatile command-line utility provides a comprehensive view of network connections, routing tables, interface statistics, and other crucial network-related information.

What is netstat?

netstat is a command-line network utility that displays various network-related information, including:

  • Network connections (both incoming and outgoing)
  • Routing tables
  • Network interface statistics
  • Masquerade connections
  • Multicast memberships
  • Protocol statistics

Why It's Important

System administrators and network engineers rely on netstat for several critical tasks:

  1. Troubleshooting network issues - Quickly identifying connection problems and network bottlenecks
  2. Security monitoring - Detecting unauthorized network connections and suspicious activities
  3. Performance analysis - Monitoring network traffic patterns and interface statistics
  4. System auditing - Reviewing active services and open ports

Brief History

The netstat command has been a part of the TCP/IP networking toolkit since the early days of Unix systems. While it originated in BSD Unix, it has evolved to become a standard tool across various Unix-like operating systems, including Linux. Despite being considered "deprecated" in favor of newer tools like ss, netstat remains widely used due to its:

  • Familiarity among system administrators
  • Broad availability across different Unix-like systems
  • Rich feature set and detailed output options
  • Extensive documentation and community support

Basic Syntax and Usage

Command Format

The basic syntax of the netstat command is:

netstat [options]

The command can be used with various options to customize the output based on your needs. Without any options, netstat will display a list of open sockets.

Common Options and Flags

Here are the most frequently used options:

OptionDescription
-aShows all listening ports and active connections
-tDisplays TCP connections
-uShows UDP connections
-nShows numerical addresses instead of resolving hosts and ports
-lShows only listening sockets
-pDisplays the PID and program name
-rShows the routing table
-iShows network interface statistics
-sShows protocol statistics

Basic Examples

  1. View all active connections
netstat -a
  1. Display all TCP connections
netstat -at
  1. Show listening ports with program information
sudo netstat -tulnp

This popular combination shows:

  • -t: TCP connections
  • -u: UDP connections
  • -l: Only listening ports
  • -n: Numerical addresses
  • -p: Program information
  1. Check routing table
netstat -r
  1. View interface statistics
netstat -i

Understanding the Output

A typical netstat output includes several columns:

  • Proto: Protocol (TCP, UDP)
  • Recv-Q: Data queued for receiving
  • Send-Q: Data queued for sending
  • Local Address: Local endpoint of the connection
  • Foreign Address: Remote endpoint of the connection
  • State: Connection state (LISTEN, ESTABLISHED, etc.)

Example output when using netstat -tan:

Proto Recv-Q Send-Q Local Address          Foreign Address        State
tcp        0      0 0.0.0.0:22            0.0.0.0:*             LISTEN
tcp        0      0 127.0.0.1:631         0.0.0.0:*             LISTEN
tcp        0      0 192.168.1.5:22        192.168.1.100:52614   ESTABLISHED

Key Features and Options

Display Options

Listing All Connections

The netstat command offers various ways to list network connections based on your specific needs:

  1. Show all protocols with numeric addresses
netstat -an
  1. Display extended information
netstat -ae

This adds additional information like user and inode

  1. Show timer information
netstat -o

Adds timing information useful for troubleshooting

Protocol-Specific Display

  1. TCP Only
# Show all TCP connections including listening ports
netstat -at

# Show only listening TCP ports
netstat -lt
  1. UDP Only
# Show all UDP connections
netstat -au

# Show only listening UDP ports
netstat -lu
  1. Unix Domain Sockets
# Display Unix domain sockets
netstat -x

Output Format Options

Numeric Display

# Full numeric output (no name resolution)
netstat -n

# Combine with other options
netstat -ant  # TCP connections with numeric addresses

Benefits of numeric display:

  • Faster execution
  • No DNS lookups
  • More reliable in case of DNS issues

Extended Information View

# Show process information
sudo netstat -p

# Show user and process information
sudo netstat -ep

# Show network interface statistics with extended info
netstat -ie

Continuous Display

# Update every 2 seconds
netstat -c

# Combine with other options for continuous monitoring
netstat -ct  # Continuous TCP monitoring

Statistics Display

  1. Protocol Statistics
# Show summary statistics for all protocols
netstat -s

# Show TCP statistics only
netstat -st

# Show UDP statistics only
netstat -su
  1. Interface Statistics
# Display interface statistics
netstat -i

# Show extended interface information
netstat -ie

Example output of interface statistics:

Iface    MTU   RX-OK RX-ERR RX-DRP RX-OVR   TX-OK TX-ERR TX-DRP TX-OVR Flg
eth0    1500  158426      0      0      0   88573      0      0      0 BMRU
lo     65536   24846      0      0      0   24846      0      0      0 LRU

Where:

  • RX: Receive statistics
  • TX: Transmit statistics
  • OK: Successful packets
  • ERR: Error count
  • DRP: Dropped packets
  • OVR: Overrun events

Common Use Cases

Network Troubleshooting

Checking Open Ports

  1. Find all open ports on the system
sudo netstat -tulpn | grep LISTEN

This command helps identify:

  • Which services are running
  • What ports they're using
  • Which processes own these ports
  1. Check if a specific port is in use
sudo netstat -tulpn | grep ":80"    # Check for web server
sudo netstat -tulpn | grep ":3306"  # Check for MySQL

Identifying Active Connections

  1. Monitor current connections
# Show all established connections
netstat -nat | grep ESTABLISHED

# Count connections per IP address
netstat -nat | grep ESTABLISHED | awk '{print $5}' | cut -d: -f1 | sort | uniq -c
  1. Track connection states
# View connection states distribution
netstat -ant | awk '{print $6}' | sort | uniq -c

Monitoring Network Traffic

  1. Interface traffic analysis
# Watch interface statistics in real-time
netstat -i
watch -n 1 "netstat -i"
  1. Protocol-specific monitoring
# Monitor TCP traffic statistics
netstat -st

# Monitor UDP traffic statistics
netstat -su

Security Analysis

Finding Suspicious Connections

  1. Detect unusual ports
# List all non-standard listening ports
sudo netstat -tulpn | grep -v ":22\|:80\|:443"
  1. Check for suspicious connection patterns
# Look for connections from unexpected IPs
netstat -ant | grep ESTABLISHED | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -rn

Port Scanning Detection

# Look for multiple connection attempts
netstat -ant | grep SYN_RECV | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -nr

System Auditing

  1. Service verification
# Check which processes are listening on which ports
sudo netstat -tulpn | grep LISTEN | sort -k 4
  1. Connection logging
# Create a simple connection log
while true; do
    date >> connection_log.txt
    netstat -ant >> connection_log.txt
    sleep 60
done
  1. Resource usage monitoring
# Monitor connection count per service
netstat -ant | grep ESTABLISHED | awk '{print $4}' | cut -d: -f2 | sort | uniq -c

Common Troubleshooting Scenarios

  1. Web Server Issues
# Check web server connections
sudo netstat -ant | grep ":80\|:443" | awk '{print $6}' | sort | uniq -c
  1. Database Connection Problems
# Monitor database connections (MySQL example)
sudo netstat -ant | grep :3306 | awk '{print $6}' | sort | uniq -c
  1. Mail Server Analysis
# Check mail server connections
sudo netstat -ant | grep ":25\|:465\|:587" | awk '{print $6}' | sort | uniq -c

Advanced Usage

Combining with Other Commands

Using with grep and awk

  1. Complex filtering and analysis
# Count connections by state and port
netstat -ant | awk '{print $6, $4}' | sort | uniq -c | sort -rn

# Monitor specific service connections over time
watch -n 1 'netstat -ant | grep ":80" | wc -l'
  1. Advanced connection analysis
# Create a connection summary
netstat -ant | \
awk '{ip[$5]++} END {for (i in ip) print ip[i],i}' | \
sort -nr | head -n 10

Piping to other tools

# Using with tee for logging
netstat -ant | tee network_status.log

# Using with xargs for process management
netstat -tulpn | grep LISTEN | awk '{print $7}' | cut -d/ -f1 | xargs ps -f

Scripts and Automation

Basic Monitoring Script

#!/bin/bash

LOG_FILE="/var/log/network_monitor.log"

monitor_connections() {
    echo "=== Network Status Report ===" >> $LOG_FILE
    date >> $LOG_FILE
    echo "Active Connections:" >> $LOG_FILE
    netstat -ant | grep ESTABLISHED | wc -l >> $LOG_FILE
    echo "Listening Ports:" >> $LOG_FILE
    netstat -tulpn | grep LISTEN >> $LOG_FILE
    echo "=========================" >> $LOG_FILE
}

# Run every 5 minutes
while true; do
    monitor_connections
    sleep 300
done

Advanced Analysis Script

#!/bin/bash

analyze_network() {
    echo "=== Network Analysis ==="
    
    echo -e "\nTop 10 IP Connections:"
    netstat -ant | grep ESTABLISHED | \
    awk '{print $5}' | cut -d: -f1 | \
    sort | uniq -c | sort -rn | head -n 10
    
    echo -e "\nConnection States:"
    netstat -ant | awk '{print $6}' | \
    sort | uniq -c | sort -rn
    
    echo -e "\nPort Usage:"
    netstat -ant | awk '{print $4}' | \
    cut -d: -f2 | sort | uniq -c | sort -rn | head -n 10
}

# Save to file with timestamp
analyze_network | tee -a "network_analysis_$(date +%Y%m%d_%H%M%S).log"

Performance Monitoring

Resource Usage Tracking

  1. CPU and Memory Impact
# Monitor netstat's own resource usage
while true; do
    ps aux | grep netstat | grep -v grep
    sleep 1
done
  1. Network Interface Performance
#!/bin/bash
# Monitor interface throughput
INTERVAL=1
INTERFACE="eth0"

while true; do
    R1=$(cat /sys/class/net/$INTERFACE/statistics/rx_bytes)
    T1=$(cat /sys/class/net/$INTERFACE/statistics/tx_bytes)
    sleep $INTERVAL
    R2=$(cat /sys/class/net/$INTERFACE/statistics/rx_bytes)
    T2=$(cat /sys/class/net/$INTERFACE/statistics/tx_bytes)
    
    RBPS=$(( ($R2 - $R1) / $INTERVAL ))
    TBPS=$(( ($T2 - $T1) / $INTERVAL ))
    
    echo "Interface $INTERFACE:"
    echo "RX: $(($RBPS/1024)) KB/s"
    echo "TX: $(($TBPS/1024)) KB/s"
    echo "------------------------"
done

Long-term Monitoring Solutions

#!/bin/bash
# Create hourly network statistics report

LOGDIR="/var/log/netstat_reports"
mkdir -p $LOGDIR

generate_report() {
    TIMESTAMP=$(date +%Y%m%d_%H)
    REPORT="$LOGDIR/netstat_report_$TIMESTAMP.log"
    
    echo "Network Report - $(date)" > $REPORT
    echo "=========================" >> $REPORT
    
    echo "Connection Summary:" >> $REPORT
    netstat -s >> $REPORT
    
    echo "Interface Statistics:" >> $REPORT
    netstat -i >> $REPORT
    
    echo "Current Connections:" >> $REPORT
    netstat -ant >> $REPORT
}

# Run report generation
generate_report

Integration Tips

  1. Combining with System Monitoring
# Add to system monitoring scripts
if [ $(netstat -ant | grep ESTABLISHED | wc -l) -gt 100 ]; then
    echo "High connection count detected" | mail -s "Network Alert" [email protected]
fi
  1. Custom Reporting Functions
network_summary() {
    local port="$1"
    echo "Connections on port $port:"
    netstat -ant | grep ":$port" | awk '{print $6}' | sort | uniq -c
}

# Usage: network_summary 80

Alternatives to netstat

The ss Command

ss (Socket Statistics) is the modern replacement for netstat in Linux systems. It's generally faster and more feature-rich than netstat.

Key Advantages of ss

  • Faster execution, especially on systems with many connections
  • More detailed socket information
  • Better support for newer protocols
  • Lower system resource usage

Comparison with netstat

# netstat command vs ss equivalent

# List all connections
netstat -a
ss

# Show listening TCP ports
netstat -tln
ss -tln

# Display process information
netstat -p
ss -p

# Show statistics
netstat -s
ss -s

Example Usage of ss

# Show detailed socket information
ss -i

# Display timer information
ss -o

# Show memory usage
ss -m

# Filter by state
ss state established

# Filter by port
ss sport = :80

Modern Alternatives

lsof (List Open Files)

# Show network connections
lsof -i

# Show listening ports
lsof -i -P -n | grep LISTEN

# Show established connections
lsof -i | grep ESTABLISHED

nmap

# Scan open ports
nmap localhost

# Detailed port scan
nmap -sV localhost

iptraf-ng

  • Real-time IP traffic monitor
  • Detailed protocol statistics
  • Interface statistics
  • LAN station monitor

When to Use What

Use netstat when:

  • Working on older systems
  • Need cross-platform compatibility
  • Following established documentation
  • Running simple network diagnostics

Use ss when:

  • Working on modern Linux systems
  • Need faster execution
  • Dealing with many connections
  • Require detailed socket information

Use lsof when:

  • Need to see file descriptor information
  • Want to correlate network connections with processes
  • Troubleshooting application issues

Use nmap when:

  • Performing security audits
  • Need detailed port scanning
  • Analyzing network services

Migration Guide

Moving from netstat to ss

netstat commandss equivalentDescription
netstat -tss -tShow TCP connections
netstat -uss -uShow UDP connections
netstat -lss -lShow listening sockets
netstat -pss -pShow process information
netstat -nss -nDon't resolve names
netstat -assShow all sockets
netstat -rip routeShow routing table

Script Migration Example

# Old netstat script
#!/bin/bash
netstat -tulpn | grep LISTEN > listening_ports.log

# New ss equivalent
#!/bin/bash
ss -tulpn | grep LISTEN > listening_ports.log

Tool Selection Tips

  1. Performance Considerations
  • For large-scale systems: Use ss
  • For basic checks: Either tool works fine
  • For detailed analysis: Combine multiple tools
  1. Compatibility Issues
# Check if ss is available
if command -v ss >/dev/null 2>&1; then
    ss -tulpn
else
    netstat -tulpn
fi
  1. Feature Requirements
  • Basic monitoring: netstat/ss
  • Security analysis: nmap
  • Process correlation: lsof
  • Real-time monitoring: iptraf-ng

Best Practices and Tips

Performance Considerations

Optimizing Command Usage

  1. Use Numeric Output When Possible
# Slower (with DNS resolution)
netstat -ta

# Faster (without DNS resolution)
netstat -tan
  1. Limit Output Size
# Instead of showing all connections
netstat -a

# Filter for specific information
netstat -an | grep ':80'
  1. Avoid Continuous Polling
# Not recommended for busy systems
netstat -c

# Better approach with controlled interval
while true; do
    netstat -an | grep ESTABLISHED
    sleep 5
done

Common Pitfalls

Resource Usage Issues

  • Problem: Excessive CPU usage during name resolution
# Problematic command
watch -n 1 'netstat -ta'

# Better alternative
watch -n 1 'netstat -tan'

Permission Issues

  • Problem: Missing process information
# Will show incomplete information
netstat -p

# Correct usage
sudo netstat -p

Output Interpretation

  • Problem: Misinterpreting connection states
# Common misunderstanding with TIME_WAIT
netstat -ant | grep TIME_WAIT

# Better analysis with context
netstat -ant | awk '{print $6}' | sort | uniq -c

Tips for Daily Usage

Creating Useful Aliases

# Add to ~/.bashrc
alias ns='netstat -tulpn'
alias nsc='netstat -ant | grep ESTABLISHED'
alias nsl='sudo netstat -tulpn | grep LISTEN'

Quick Security Checks

# Check for unusual listening ports
check_ports() {
    echo "Known ports:"
    sudo netstat -tulpn | grep -E ':22|:80|:443'
    echo -e "\nUnknown ports:"
    sudo netstat -tulpn | grep -vE ':22|:80|:443'
}

Monitoring Templates

# Connection monitoring template
monitor_connections() {
    local port=$1
    local threshold=$2
    
    count=$(netstat -an | grep ":$port" | grep ESTABLISHED | wc -l)
    if [ $count -gt $threshold ]; then
        echo "Alert: $count connections on port $port exceed threshold of $threshold"
    fi
}

# Usage: monitor_connections 80 100

Documentation and Logging

Creating Useful Logs

#!/bin/bash
# Network status logger

log_network_status() {
    local logfile="/var/log/network_status.log"
    local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
    
    {
        echo "=== Network Status at $timestamp ==="
        echo "Listening Ports:"
        netstat -tulpn | grep LISTEN
        echo "Current Connections:"
        netstat -ant | awk '{print $6}' | sort | uniq -c
        echo "=================================="
    } >> "$logfile"
}

Standard Operating Procedures

# Template for regular checks
daily_network_check() {
    echo "1. Checking listening ports..."
    sudo netstat -tulpn | grep LISTEN
    
    echo "2. Checking established connections..."
    netstat -ant | grep ESTABLISHED | wc -l
    
    echo "3. Checking connection states..."
    netstat -ant | awk '{print $6}' | sort | uniq -c
    
    echo "4. Checking interface statistics..."
    netstat -i
}

Troubleshooting Guidelines

  1. Connection Issues
connection_troubleshoot() {
    local port=$1
    echo "=== Connection Troubleshooting for Port $port ==="
    echo "1. Checking if port is listening:"
    sudo netstat -tulpn | grep ":$port"
    
    echo "2. Checking active connections:"
    netstat -ant | grep ":$port" | awk '{print $6}' | sort | uniq -c
    
    echo "3. Checking connection states:"
    netstat -ant | grep ":$port" | awk '{print $6}' | sort | uniq -c
}
  1. System Resource Monitoring
resource_check() {
    echo "=== System Resource Check ==="
    echo "1. Total connections:"
    netstat -ant | wc -l
    
    echo "2. Connections per IP:"
    netstat -ant | grep ESTABLISHED | \
    awk '{print $5}' | cut -d: -f1 | \
    sort | uniq -c | sort -nr | head -5
    
    echo "3. Memory usage of network processes:"
    ps aux | grep -E 'netstat|ss' | grep -v grep
}

Linux Netstat Command

Frequently Asked Questions (FAQ)

Q: Why can't I see the process information (PID)?

A: This is usually due to permissions. Run the command with sudo:
sudo netstat -tulpn

The -p option requires root privileges to show process information.

Q: What's the difference between LISTEN and ESTABLISHED states?

A: 
- LISTEN: Indicates a service is listening on that port, waiting for connections
- ESTABLISHED: Represents an active, currently connected session

Q: How do I check connections for a specific port?

A: You can use grep to filter port-specific connections:

# Check all connections on port 80
netstat -an | grep ":80"

# Check only listening ports
netstat -tunl | grep ":80"

Q: Why is my netstat command running slowly?

A: Two main reasons:
1. DNS resolution - Use -n option to avoid name resolution
2. Too many connections - Use filtering or consider switching to ss

# Faster command example
netstat -tan | grep ESTABLISHED

Q: Will netstat affect system performance?

A: Frequent polling can impact performance. Best practices:
1. Increase polling intervals
2. Use filtering to reduce output
3. Consider ss for large-scale systems
4. Avoid continuous mode (-c) on busy systems

Q: How do I identify which application is using a specific port?

A: Use these commands:
# Show process using port 80
sudo netstat -tulpn | grep ":80"

# Alternative using lsof
sudo lsof -i :80

Q: How can I monitor connection states?

A: Several approaches:

# Count connections by state
netstat -ant | awk '{print $6}' | sort | uniq -c

# Monitor established connections
watch -n 1 'netstat -ant | grep ESTABLISHED | wc -l'

Q: How can I check for suspicious connections?

A: Look for:
1. Unusual ports:
netstat -tulpn | grep -vE ':22|:80|:443'

2. High number of connections from single IP:
netstat -ant | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -nr

Q: How do I detect port scanning attempts?

A: Monitor SYN_RECV connections:
netstat -ant | grep SYN_RECV | awk '{print $5}' | cut -d: -f1 | sort | uniq -c

Q: What's the difference between -t and -u options?

A:
-t : Shows TCP connections only
-u : Shows UDP connections only

You can combine them:
netstat -tu : Shows both TCP and UDP

Q: How do I save netstat output to a file?

A: Several methods:

# Basic output to file
netstat -ant > network_status.log

# With timestamp
(date; netstat -ant) > network_status.log

# Continuous logging
while true; do
    netstat -ant >> network_log.txt
    sleep 300
done

Q: What does "Address already in use" mean in netstat output?

A: This indicates a port is already being used by another process. To find it:
sudo netstat -tulpn | grep "<port_number>"

Q: Why do I see many TIME_WAIT connections?

A: TIME_WAIT is normal after connections close. However, too many might indicate:
1. High connection turnover
2. Possible network issues
3. Application not reusing connections

Monitor with:
netstat -ant | grep TIME_WAIT | wc -l