コンテンツにスキップ

Netstat Cheatsheet

Netstat - Network Connection Utility

Netstat is a command-line network utility that displays network connections, routing tables, interface statistics, masquerade connections, and multicast memberships. Essential for network troubleshooting, security analysis, and system administration.

Table of Contents

Installation

Linux (Built-in)

# Netstat is typically pre-installed on most Linux distributions
# If missing, install via package manager

# Ubuntu/Debian
sudo apt update
sudo apt install net-tools

# CentOS/RHEL/Fedora
sudo yum install net-tools
# or
sudo dnf install net-tools

# Arch Linux
sudo pacman -S net-tools

# Alpine Linux
sudo apk add net-tools

Windows (Built-in)

# Netstat is built into Windows
# Available in Command Prompt and PowerShell
netstat /?

# PowerShell equivalent
Get-NetTCPConnection
Get-NetUDPEndpoint

macOS (Built-in)

# Netstat is pre-installed on macOS
netstat -h

# Alternative: lsof for more detailed process information
brew install lsof

Alternative Tools

# Modern alternatives to netstat
# ss (socket statistics) - faster and more feature-rich
sudo apt install iproute2  # Ubuntu/Debian
sudo yum install iproute2  # CentOS/RHEL

# lsof - list open files and network connections
sudo apt install lsof     # Ubuntu/Debian
sudo yum install lsof      # CentOS/RHEL

Basic Usage

Display All Connections

# Show all active connections
netstat -a

# Show all TCP connections
netstat -at

# Show all UDP connections
netstat -au

# Show all listening ports
netstat -l

# Show all listening TCP ports
netstat -lt

# Show all listening UDP ports
netstat -lu

Common Options

# Show numerical addresses instead of resolving hosts
netstat -n

# Show process ID and name
netstat -p

# Continuous monitoring (refresh every 2 seconds)
netstat -c

# Show extended information
netstat -e

# Show multicast group memberships
netstat -g

# Show routing table
netstat -r

# Show interface statistics
netstat -i

Combined Options

# Most commonly used combination
netstat -tulpn

# Breakdown:
# -t: TCP connections
# -u: UDP connections
# -l: Listening ports only
# -p: Show process ID and name
# -n: Show numerical addresses

# Show all connections with process information
netstat -anp

# Show listening ports with process information
netstat -lnp

# Show TCP connections with process information
netstat -tnp

Connection Monitoring

TCP Connections

# Show all TCP connections
netstat -t

# Show TCP connections with numerical addresses
netstat -tn

# Show TCP listening ports
netstat -tl

# Show TCP connections with process information
netstat -tp

# Show TCP connections in specific states
netstat -t | grep ESTABLISHED
netstat -t | grep LISTEN
netstat -t | grep TIME_WAIT
netstat -t | grep CLOSE_WAIT

UDP Connections

# Show all UDP connections
netstat -u

# Show UDP connections with numerical addresses
netstat -un

# Show UDP listening ports
netstat -ul

# Show UDP connections with process information
netstat -up

Connection States

# Monitor connection states
netstat -t | awk '{print $6}' | sort | uniq -c

# Count connections by state
netstat -an | awk '/^tcp/ {print $6}' | sort | uniq -c

# Monitor specific connection state
watch -n 1 'netstat -t | grep ESTABLISHED | wc -l'

# Show connections to specific port
netstat -an | grep :80
netstat -an | grep :443
netstat -an | grep :22

Real-time Monitoring

# Continuous monitoring
netstat -c

# Monitor with custom interval (every 5 seconds)
watch -n 5 netstat -tulpn

# Monitor specific port continuously
watch -n 1 'netstat -an | grep :80'

# Monitor connection count
watch -n 1 'netstat -an | wc -l'

Routing Tables

Display Routing Information

# Show routing table
netstat -r

# Show routing table with numerical addresses
netstat -rn

# Show IPv4 routing table
netstat -r -4

# Show IPv6 routing table
netstat -r -6

# Show kernel routing table (Linux)
netstat -rn | grep '^0.0.0.0'

# Show default gateway
netstat -rn | grep '^default'

Route Analysis

# Show routing table with interface information
netstat -rn | column -t

# Find routes to specific network
netstat -rn | grep "192.168.1"

# Show routing cache (if available)
netstat -C

# Display routing statistics
netstat -s | grep -i route

Interface Statistics

Network Interface Information

# Show interface statistics
netstat -i

# Show interface statistics with extended information
netstat -ie

# Show interface statistics continuously
netstat -ic

# Show specific interface
netstat -i eth0
netstat -i wlan0

Interface Monitoring

# Monitor interface packet counts
watch -n 1 'netstat -i'

# Show interface errors and drops
netstat -i | awk 'NR>2 {print $1, $4, $8}'

# Monitor specific interface traffic
watch -n 1 'netstat -i | grep eth0'

# Calculate interface utilization
netstat -i | awk 'NR>2 {print $1, "RX:", $3, "TX:", $7}'

Process Information

Process-to-Port Mapping

# Show processes using network connections
netstat -p

# Show processes listening on ports
netstat -lp

# Show processes using TCP connections
netstat -tp

# Show processes using UDP connections
netstat -up

# Find process using specific port
netstat -lnp | grep :80
netstat -lnp | grep :443
netstat -lnp | grep :22

Process Analysis

# Show all processes with network connections
netstat -anp | grep -v "0.0.0.0:*"

# Find processes by name
netstat -anp | grep nginx
netstat -anp | grep apache
netstat -anp | grep mysql

# Show connections for specific PID
netstat -anp | grep 1234

# Count connections per process
netstat -anp | awk '{print $7}' | sort | uniq -c | sort -nr

Advanced Filtering

Port-based Filtering

# Show connections on specific port
netstat -an | grep :80
netstat -an | grep :443
netstat -an | grep :22
netstat -an | grep :3306

# Show listening services on common ports
netstat -ln | grep :80
netstat -ln | grep :443
netstat -ln | grep :22

# Show connections from specific IP
netstat -an | grep 192.168.1.100

# Show connections to specific IP
netstat -an | grep "192.168.1.100:"

Protocol Filtering

# Show only TCP connections
netstat -t

# Show only UDP connections
netstat -u

# Show only Unix domain sockets
netstat -x

# Show only raw sockets
netstat -w

# Show IPv4 connections only
netstat -4

# Show IPv6 connections only
netstat -6

State-based Filtering

# Show established connections
netstat -t | grep ESTABLISHED

# Show listening ports
netstat -t | grep LISTEN

# Show connections in TIME_WAIT state
netstat -t | grep TIME_WAIT

# Show connections in CLOSE_WAIT state
netstat -t | grep CLOSE_WAIT

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

Security Analysis

Security Monitoring

# Monitor for suspicious connections
netstat -an | grep ESTABLISHED | grep -v "127.0.0.1\|::1"

# Check for unexpected listening services
netstat -ln | grep -v "127.0.0.1\|::1"

# Monitor for connections to unusual ports
netstat -an | grep -E ":(1234|4444|5555|6666|7777|8888|9999)"

# Check for connections from external IPs
netstat -an | grep ESTABLISHED | grep -v "192.168\|10\.\|172\."

Port Scanning Detection

# Monitor for port scanning attempts
netstat -an | grep SYN_RECV | wc -l

# Check for half-open connections
netstat -an | grep SYN_RECV

# Monitor connection attempts
watch -n 1 'netstat -an | grep SYN_RECV | wc -l'

# Detect potential DDoS
netstat -an | grep :80 | grep SYN_RECV | wc -l

Network Forensics

# Capture current network state
netstat -anp > network_state_$(date +%Y%m%d_%H%M%S).txt

# Monitor network changes
netstat -anp > /tmp/netstat_before.txt
# ... perform action ...
netstat -anp > /tmp/netstat_after.txt
diff /tmp/netstat_before.txt /tmp/netstat_after.txt

# Track connection history
while true; do
    echo "$(date): $(netstat -an | wc -l) connections" >> connection_log.txt
    sleep 60
done

Automation Scripts

Network Monitoring Script

#!/bin/bash
# network_monitor.sh - Comprehensive network monitoring

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

log_message() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE"
}

check_connections() {
    local conn_count=$(netstat -an | wc -l)
    log_message "Total connections: $conn_count"

    if [ "$conn_count" -gt "$ALERT_THRESHOLD" ]; then
        log_message "ALERT: High connection count detected!"
        # Send alert (email, Slack, etc.)
    fi
}

check_listening_ports() {
    log_message "Listening ports:"
    netstat -ln | grep LISTEN | tee -a "$LOG_FILE"
}

check_established_connections() {
    local est_count=$(netstat -an | grep ESTABLISHED | wc -l)
    log_message "Established connections: $est_count"
}

check_suspicious_activity() {
    # Check for connections to unusual ports
    local suspicious=$(netstat -an | grep -E ":(1234|4444|5555|6666|7777|8888|9999)" | wc -l)
    if [ "$suspicious" -gt 0 ]; then
        log_message "WARNING: Suspicious connections detected!"
        netstat -an | grep -E ":(1234|4444|5555|6666|7777|8888|9999)" | tee -a "$LOG_FILE"
    fi
}

main() {
    log_message "Starting network monitoring"
    check_connections
    check_listening_ports
    check_established_connections
    check_suspicious_activity
    log_message "Network monitoring completed"
}

# Run monitoring
main

Port Scanner Detection

#!/bin/bash
# port_scan_detector.sh - Detect potential port scanning

SCAN_LOG="/var/log/port_scan.log"
THRESHOLD=10

detect_syn_flood() {
    local syn_count=$(netstat -an | grep SYN_RECV | wc -l)

    if [ "$syn_count" -gt "$THRESHOLD" ]; then
        echo "$(date): ALERT - Potential SYN flood detected! Count: $syn_count" >> "$SCAN_LOG"

        # Log source IPs
        echo "Source IPs:" >> "$SCAN_LOG"
        netstat -an | grep SYN_RECV | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -nr >> "$SCAN_LOG"

        # Optional: Block suspicious IPs
        # netstat -an | grep SYN_RECV | awk '{print $5}' | cut -d: -f1 | sort | uniq | while read ip; do
        #     iptables -A INPUT -s "$ip" -j DROP
        # done
    fi
}

monitor_connection_attempts() {
    # Monitor for rapid connection attempts
    netstat -an | grep SYN_RECV | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | while read count ip; do
        if [ "$count" -gt 5 ]; then
            echo "$(date): Suspicious activity from $ip - $count connection attempts" >> "$SCAN_LOG"
        fi
    done
}

# Run detection
detect_syn_flood
monitor_connection_attempts

Connection Analyzer

#!/usr/bin/env python3
# connection_analyzer.py - Advanced connection analysis

import subprocess
import re
import json
from collections import defaultdict, Counter
from datetime import datetime

class ConnectionAnalyzer:
    def __init__(self):
        self.connections = []
        self.stats = defaultdict(int)

    def get_connections(self):
        """Get current network connections"""
        try:
            result = subprocess.run(['netstat', '-anp'], 
                                  capture_output=True, text=True)
            return result.stdout.split('\n')
        except Exception as e:
            print(f"Error getting connections: {e}")
            return []

    def parse_connections(self, lines):
        """Parse netstat output"""
        connections = []

        for line in lines:
            if 'tcp' in line or 'udp' in line:
                parts = line.split()
                if len(parts) >= 6:
                    connection = {
                        'protocol': parts[0],
                        'local_address': parts[3],
                        'remote_address': parts[4],
                        'state': parts[5] if len(parts) > 5 else 'N/A',
                        'process': parts[6] if len(parts) > 6 else 'N/A'
                    }
                    connections.append(connection)

        return connections

    def analyze_connections(self):
        """Analyze network connections"""
        lines = self.get_connections()
        self.connections = self.parse_connections(lines)

        # Count by protocol
        protocols = Counter(conn['protocol'] for conn in self.connections)

        # Count by state
        states = Counter(conn['state'] for conn in self.connections)

        # Count by remote IP
        remote_ips = Counter(
            conn['remote_address'].split(':')[0] 
            for conn in self.connections 
            if ':' in conn['remote_address']
        )

        # Count by local port
        local_ports = Counter(
            conn['local_address'].split(':')[-1] 
            for conn in self.connections 
            if ':' in conn['local_address']
        )

        return {
            'total_connections': len(self.connections),
            'protocols': dict(protocols),
            'states': dict(states),
            'top_remote_ips': dict(remote_ips.most_common(10)),
            'top_local_ports': dict(local_ports.most_common(10))
        }

    def detect_anomalies(self):
        """Detect potential security issues"""
        anomalies = []

        # Check for excessive connections from single IP
        remote_ips = Counter(
            conn['remote_address'].split(':')[0] 
            for conn in self.connections 
            if ':' in conn['remote_address'] and not conn['remote_address'].startswith('127.')
        )

        for ip, count in remote_ips.items():
            if count > 50:  # Threshold for suspicious activity
                anomalies.append(f"High connection count from {ip}: {count}")

        # Check for unusual ports
        unusual_ports = ['1234', '4444', '5555', '6666', '7777', '8888', '9999']
        for conn in self.connections:
            for port in unusual_ports:
                if f":{port}" in conn['remote_address']:
                    anomalies.append(f"Connection to unusual port {port}: {conn['remote_address']}")

        return anomalies

    def generate_report(self):
        """Generate comprehensive report"""
        analysis = self.analyze_connections()
        anomalies = self.detect_anomalies()

        report = {
            'timestamp': datetime.now().isoformat(),
            'analysis': analysis,
            'anomalies': anomalies,
            'recommendations': self.get_recommendations(analysis, anomalies)
        }

        return report

    def get_recommendations(self, analysis, anomalies):
        """Generate security recommendations"""
        recommendations = []

        if analysis['total_connections'] > 1000:
            recommendations.append("High connection count detected - monitor for potential DDoS")

        if len(anomalies) > 0:
            recommendations.append("Security anomalies detected - investigate immediately")

        if 'SYN_RECV' in analysis['states'] and analysis['states']['SYN_RECV'] > 100:
            recommendations.append("High SYN_RECV count - potential SYN flood attack")

        return recommendations

def main():
    analyzer = ConnectionAnalyzer()
    report = analyzer.generate_report()

    print(json.dumps(report, indent=2))

    # Save report to file
    with open(f"network_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json", 'w') as f:
        json.dump(report, f, indent=2)

if __name__ == "__main__":
    main()

Performance Monitoring

Connection Performance

# Monitor connection establishment rate
watch -n 1 'netstat -s | grep "connections established"'

# Monitor TCP retransmissions
netstat -s | grep -i retrans

# Monitor packet drops
netstat -s | grep -i drop

# Monitor buffer usage
netstat -s | grep -i buffer

Bandwidth Monitoring

# Monitor interface throughput
watch -n 1 'netstat -i | grep -v "Kernel\|Iface\|lo"'

# Calculate bandwidth utilization
netstat -i | awk 'NR>2 && $1!="lo" {
    rx_bytes=$3; tx_bytes=$7;
    print $1, "RX:", rx_bytes, "TX:", tx_bytes
}'

# Monitor network statistics
netstat -s | grep -E "(packets|bytes)"

System Resource Usage

# Monitor socket usage
netstat -s | grep -i socket

# Check for memory issues
netstat -s | grep -i memory

# Monitor connection limits
ulimit -n  # Check file descriptor limit
cat /proc/sys/net/core/somaxconn  # Check socket backlog limit

Troubleshooting

Common Issues

High Connection Count

# Identify processes with most connections
netstat -anp | awk '{print $7}' | sort | uniq -c | sort -nr | head -10

# Check for connection leaks
netstat -an | grep TIME_WAIT | wc -l

# Monitor connection states over time
watch -n 5 'netstat -an | awk "{print \$6}" | sort | uniq -c'

Port Binding Issues

# Check if port is already in use
netstat -ln | grep :80

# Find process using specific port
netstat -lnp | grep :80

# Check for port conflicts
netstat -ln | sort -k4

Network Connectivity Issues

# Check routing table
netstat -rn

# Verify interface status
netstat -i

# Check for dropped packets
netstat -i | grep -v "0.*0.*0.*0"

# Monitor interface errors
watch -n 1 'netstat -i | awk "NR>2 {print \$1, \$4, \$8}"'

Diagnostic Commands

# Comprehensive network state dump
netstat -anp > netstat_full.txt

# Quick connection summary
netstat -s | head -20

# Check for unusual activity
netstat -an | grep -v "127.0.0.1\|::1" | grep ESTABLISHED

# Monitor real-time changes
watch -d -n 1 'netstat -tulpn | head -20'

Performance Optimization

# Tune TCP parameters (Linux)
echo 'net.core.somaxconn = 65535' >> /etc/sysctl.conf
echo 'net.ipv4.tcp_max_syn_backlog = 65535' >> /etc/sysctl.conf
echo 'net.core.netdev_max_backlog = 5000' >> /etc/sysctl.conf

# Apply changes
sysctl -p

# Monitor the effect
netstat -s | grep -i listen

Best Practices

Security Best Practices

# Regular security audits
netstat -ln | grep -v "127.0.0.1\|::1" > listening_services.txt

# Monitor for unauthorized services
diff previous_services.txt current_services.txt

# Check for backdoors
netstat -anp | grep -E ":(1234|4444|5555|6666|7777|8888|9999)"

# Verify expected services only
netstat -lnp | awk '{print $4, $7}' | sort

Monitoring Best Practices

# Automated monitoring
*/5 * * * * /usr/local/bin/network_monitor.sh

# Log rotation for network logs
logrotate -f /etc/logrotate.d/network

# Baseline establishment
netstat -anp > /var/baseline/network_baseline_$(date +%Y%m%d).txt

# Regular comparison
diff /var/baseline/network_baseline_*.txt current_state.txt

Performance Best Practices

# Use ss instead of netstat for better performance
ss -tulpn

# Limit output for large systems
netstat -an | head -100

# Use specific filters
netstat -tn | grep :80

# Avoid DNS resolution in scripts
netstat -n

Documentation Best Practices

# Document network configuration
netstat -rn > network_routes.txt
netstat -i > network_interfaces.txt
netstat -ln > listening_services.txt

# Create network inventory
netstat -anp | awk '{print $7}' | sort | uniq > network_processes.txt

# Regular snapshots
mkdir -p /var/log/network_snapshots
netstat -anp > "/var/log/network_snapshots/netstat_$(date +%Y%m%d_%H%M%S).txt"

Integration Examples

SIEM Integration

# Syslog format for SIEM
netstat -anp | logger -t netstat -p local0.info

# JSON format for modern SIEM
netstat -anp | awk '{print "{\"timestamp\":\"" strftime("%Y-%m-%d %H:%M:%S") "\",\"connection\":\"" $0 "\"}"}'

# Send to remote syslog
netstat -anp | logger -n siem.company.com -P 514 -t netstat

Monitoring Integration

# Prometheus metrics format
echo "network_connections_total $(netstat -an | wc -l)" | curl -X POST http://pushgateway:9091/metrics/job/netstat

# Nagios check
if [ $(netstat -an | wc -l) -gt 1000 ]; then
    echo "CRITICAL - Too many connections"
    exit 2
fi

Automation Integration

# Ansible playbook task
- name: Check network connections
  shell: netstat -anp
  register: netstat_output

# Terraform provisioner
provisioner "local-exec" {
  command = "netstat -ln > network_state.txt"
}

Summary

Netstat is an essential network diagnostic tool that provides comprehensive information about network connections, routing tables, and interface statistics. Key capabilities include:

  • Connection Monitoring: Track TCP/UDP connections and their states
  • Process Identification: Map network connections to specific processes
  • Security Analysis: Detect suspicious network activity and potential threats
  • Performance Monitoring: Analyze network performance and identify bottlenecks
  • Troubleshooting: Diagnose network connectivity and configuration issues

For modern systems, consider using ss (socket statistics) as a faster alternative to netstat, especially for large-scale environments. Regular monitoring and analysis of network connections are crucial for maintaining system security and performance.