Overview
Network monitoring is essential for diagnosing connectivity issues, analyzing performance bottlenecks, and understanding traffic patterns. These bash-based tools provide low-level access to network statistics without requiring complex monitoring solutions.
Socket and Connection Monitoring
Understanding Socket States
Sockets represent endpoints for network communication. The Linux kernel maintains various states for TCP connections (ESTABLISHED, TIME_WAIT, CLOSE_WAIT, etc.) which are crucial for diagnosing connection issues.
Key socket states to monitor:
- ESTABLISHED: Active connection with data transfer
- TIME_WAIT: Connection closed but waiting to ensure remote TCP received acknowledgment
- CLOSE_WAIT: Remote end has closed the connection, waiting for local application to close
- SYN_SENT/SYN_RECV: Connection establishment in progress
- FIN_WAIT: Connection termination in progress
1# Check active connections and socket states2ss -ant3ss -s4netstat -tapn | wc -l5
6# Monitor network bandwidth7iftop -i eth08
9# Capture packets for inspection10tcpdump -i eth0 -n -c 10011
12# View kernel logs for network errors13dmesg | grep TCP14
15# View connection and error metrics16cat /proc/net/snmp17cat /proc/net/netstatTool Explanations
ss (Socket Statistics)
The ss command is the modern replacement for netstat, providing faster socket statistics from kernel space.
ss -ant: Shows all (-a) numeric (-n) TCP (-t) sockets, avoiding DNS resolution for faster outputss -s: Displays summary statistics including total sockets, TCP connections in various states, UDP sockets, and raw sockets
netstat
Legacy but still widely used tool for network statistics. The pipe to wc -l counts total active connections, useful for detecting connection leaks or DDoS attacks.
iftop (Interface TOP)
Real-time bandwidth monitoring tool that displays current bandwidth usage on a network interface. Essential for:
- Identifying bandwidth-heavy connections
- Detecting unexpected traffic patterns
- Monitoring upload/download rates per connection
- The
-i eth0flag specifies the interface to monitor (replace with your interface name likeenp0s3,wlan0, etc.)
tcpdump
Powerful packet analyzer that captures raw network traffic at the data link layer. The command shown:
-i eth0: Captures on ethernet interface eth0-n: Disables name resolution for faster capture-c 100: Limits capture to 100 packets
Use cases: Protocol analysis, debugging application-level issues, security investigation, verifying packet delivery
dmesg (Diagnostic Message)
Kernel ring buffer contains low-level system messages. Filtering for TCP messages reveals:
- Connection timeouts
- TCP retransmission issues
- Socket buffer overflows
- Network driver errors
- Kernel-level connection problems
/proc/net/ Statistics
These pseudo-files expose kernel network stack statistics:
/proc/net/snmp: SNMP MIB-II statistics including:
- IP packet counts (received, delivered, forwarded, discarded)
- ICMP message types and counts
- TCP segments (sent, received, retransmitted)
- UDP datagram statistics
/proc/net/netstat: Extended TCP/IP statistics including:
- SYN cookies usage
- TCP Fast Open statistics
- Packet loss and recovery metrics
- Memory pressure indicators
- TCP congestion control events
Best Practices
- Baseline your metrics: Run these tools during normal operation to establish baseline values
- Combine tools: Use
ssfor quick state checks,tcpdumpfor deep packet inspection, andiftopfor bandwidth analysis - Time correlation: When investigating issues, correlate timestamps across different tools
- Interface selection: Always verify you're monitoring the correct network interface
- Privilege requirements: Most tools require root/sudo for full functionality
Common Diagnostic Scenarios
- High TIME_WAIT states: May indicate application not reusing connections properly
- Growing CLOSE_WAIT: Application not closing sockets after remote disconnect
- Retransmission spikes in
/proc/net/netstat: Network quality issues or congestion - Bandwidth saturation in
iftop: Need for QoS or capacity planning
Advanced Connection Analysis
Monitoring Specific Applications and Ports
Track network activity for specific applications using process IDs and port numbers:
1# Find connections by process name2ss -tnp | grep nginx3lsof -i -n | grep ESTABLISHED4
5# Monitor specific port6ss -tnp state established '( dport = :80 or sport = :80 )'7netstat -an | grep :443 | grep ESTABLISHED | wc -l8
9# Check which process is listening on a port10lsof -i :808011ss -tlnp | grep :330612
13# List all listening ports with process info14ss -tulpn15netstat -tulpnContinuous Monitoring and Alerting
Set up continuous monitoring with thresholds for anomaly detection:
1# Watch connection count in real-time (refreshes every 2 seconds)2watch -n 2 'ss -s'3
4# Monitor connections exceeding threshold5while true; do6 COUNT=$(ss -tan state established | wc -l)7 if [ $COUNT -gt 1000 ]; then8 echo "$(date): High connection count: $COUNT" >> /var/log/conn_monitor.log9 fi10 sleep 1011done12
13# Track TIME_WAIT accumulation14watch -n 1 'ss -tan state time-wait | wc -l'15
16# Monitor packet drops on interface17watch -n 1 'ethtool -S eth0 | grep -i drop'Traffic Analysis and Packet Inspection
Protocol-Specific Monitoring
Deep dive into specific protocols for troubleshooting:
1# Capture HTTP traffic with headers2tcpdump -i eth0 -A -s 0 'tcp port 80 and (((ip[2:2] - ((ip[0]&0xf)<<2)) - ((tcp[12]&0xf0)>>2)) != 0)'3
4# Monitor DNS queries and responses5tcpdump -i eth0 -n port 536
7# Capture HTTPS handshake (TLS/SSL)8tcpdump -i eth0 -n port 443 -w https_capture.pcap9
10# Monitor ICMP (ping) packets11tcpdump -i eth0 icmp12
13# Filter by IP address14tcpdump -i eth0 host 192.168.1.10015
16# Capture traffic between two hosts17tcpdump -i eth0 'host 192.168.1.10 and host 192.168.1.20'Network Performance Metrics
Measure latency, throughput, and packet loss:
1# Check network interface statistics2ip -s link show eth03cat /sys/class/net/eth0/statistics/rx_bytes4cat /sys/class/net/eth0/statistics/tx_bytes5
6# Monitor packet errors and drops7netstat -i8ip -s -s link show eth09
10# Continuous bandwidth measurement11nload eth012bmon -p eth013
14# Network throughput testing15iperf3 -s # On server16iperf3 -c server_ip -t 30 # On client17
18# Measure latency continuously19ping -i 0.2 -c 100 8.8.8.8 | tail -n 3System-Level Network Diagnostics
Kernel and Driver Information
Check low-level network configuration and performance:
1# View network device driver info2ethtool eth03ethtool -i eth0 # Driver details4ethtool -g eth0 # Ring buffer parameters5ethtool -k eth0 # Offload settings6
7# Check interrupt handling8cat /proc/interrupts | grep eth09mpstat -I ALL 1 510
11# Monitor network buffer usage12sysctl net.core.rmem_max13sysctl net.core.wmem_max14sysctl net.ipv4.tcp_rmem15sysctl net.ipv4.tcp_wmem16
17# Check routing table and ARP cache18ip route show19ip neigh show20arp -anConnection State Monitoring Scripts
Automated analysis of connection patterns:
1# Count connections by state2ss -tan | awk '{print $1}' | sort | uniq -c | sort -rn3
4# Top IPs by connection count5ss -tan state established | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -rn | head -106
7# Monitor new connections per second8for i in {1..60}; do9 echo "$(date +%T): $(ss -tan state syn-sent,syn-recv | wc -l) new connections"10 sleep 111done12
13# Detect potential port scans14netstat -tan | grep SYN_RECV | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -rn15
16# Connection duration analysis17ss -tno state established | grep timer | wc -lReal-Time Network Event Monitoring
Using nethogs and vnstat
Track bandwidth by process and historical data:
1# Real-time per-process bandwidth monitoring2sudo nethogs eth03
4# Historical network statistics5vnstat -i eth06vnstat -i eth0 -h # Hourly stats7vnstat -i eth0 -d # Daily stats8vnstat -i eth0 -m # Monthly stats9
10# Live traffic rates11vnstat -i eth0 -lNetwork Flow Analysis
Monitor network flows for traffic pattern analysis:
1# Count active flows2ss -tan state established | awk '{print $4" "$5}' | sort | uniq -c | sort -rn | head -203
4# Track connection establishment rate5sar -n TCP 1 106
7# Monitor network device queues8tc -s qdisc show dev eth09
10# Check conntrack table (for NAT/firewall)11conntrack -L | wc -l12cat /proc/sys/net/netfilter/nf_conntrack_count13cat /proc/sys/net/netfilter/nf_conntrack_maxPerformance Troubleshooting Commands
Identifying Bottlenecks
Diagnose network stack performance issues:
1# Check for TCP retransmissions2ss -ti | grep -i retrans3
4# Monitor socket receive queue depth5ss -tnm | grep -i rcv6
7# Check for window scaling issues8cat /proc/net/netstat | grep TcpExt | grep -i window9
10# View TCP congestion control algorithm11sysctl net.ipv4.tcp_congestion_control12ss -i | grep -i cubic13
14# Check for SYN flood protection15netstat -s | grep -i listen16cat /proc/sys/net/ipv4/tcp_max_syn_backlog17
18# Monitor socket memory pressure19cat /proc/net/sockstat20cat /proc/net/sockstat6