Linux netstat Command Deep Dive: From Network Connections to Port Monitoring
Linux netstat Command Deep Dive: From Network Connections to Port Monitoring#
When troubleshooting server network issues recently, I noticed many developers have a superficial understanding of the netstat command. Today, let’s explore this network diagnostic powerhouse, from implementation principles to practical techniques.
The Core Value of netstat#
The essence of netstat is reading kernel network stack information. In Linux systems, all network connection data is stored in the /proc filesystem:
# TCP connection information
/proc/net/tcp
/proc/net/tcp6
# UDP connection information
/proc/net/udp
/proc/net/udp6
# Unix domain sockets
/proc/net/unix
# Routing table
/proc/net/route
# Network interface statistics
/proc/net/dev
The netstat command is essentially a formatted output tool for these files. Understanding this makes many output fields clear.
Deep Dive into Common Parameters#
1. The -tunlp Parameter Combination#
This is the most common combination, each letter has a specific meaning:
netstat -tunlp
-t: Display TCP connections-u: Display UDP connections-n: Show addresses and ports numerically (no DNS resolution, 10x faster)-l: Show only listening sockets-p: Show process ID and program name (requires root privileges)
Sample output:
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 1234/nginx
tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN 5678/mysqld
tcp6 0 0 :::443 :::* LISTEN 1234/nginx
2. The -an Parameter Combination#
Shows all connections (including established ones):
netstat -an | grep ESTABLISHED
Output field explanation:
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 192.168.1.100:22 203.0.113.5:52341 ESTABLISHED
- Recv-Q: Bytes in receive queue waiting for application to read (should be near 0)
- Send-Q: Bytes in send queue not yet ACKed (high value may indicate network congestion)
- Local Address: Local IP:port
- Foreign Address: Remote IP:port
- State: TCP connection state
3. TCP States Explained#
One of netstat’s most powerful features is viewing TCP states:
netstat -ant | awk '{print $6}' | sort | uniq -c
Sample output:
12 CLOSE_WAIT
3 ESTABLISHED
45 TIME_WAIT
2 LISTEN
Key state meanings:
| State | Meaning | Troubleshooting Significance |
|---|---|---|
LISTEN |
Server waiting for connection | Normal listening state |
ESTABLISHED |
Connection established | Active connections |
TIME_WAIT |
Active closer waiting 2MSL | Large accumulation may cause port exhaustion |
CLOSE_WAIT |
Passive closer waiting for app to close | Large accumulation indicates program bug |
SYN_SENT |
Actively initiating connection | Large values may indicate SYN Flood attack |
FIN_WAIT1/2 |
Close handshake in progress | Stuck state may indicate network issues |
Practical Cases: Troubleshooting Connection Issues#
Case 1: Port Occupation Investigation#
# Check port 8080 usage
netstat -tunlp | grep :8080
# Or more precise search
netstat -tunlp | awk '$4 ~ /:8080$/'
Output:
tcp 0 0 0.0.0.0:8080 0.0.0.0:* LISTEN 12345/java
Case 2: TIME_WAIT Causing Port Exhaustion#
# Count TIME_WAIT connections
netstat -ant | grep TIME_WAIT | wc -l
# If exceeding thousands, adjust kernel parameters
echo "net.ipv4.tcp_tw_reuse = 1" >> /etc/sysctl.conf
echo "net.ipv4.tcp_max_tw_buckets = 5000" >> /etc/sysctl.conf
sysctl -p
Case 3: CLOSE_WAIT Accumulation#
CLOSE_WAIT accumulation means the remote side closed the connection, but the local program didn’t call close():
# See which programs are generating CLOSE_WAIT
netstat -antp | grep CLOSE_WAIT
This is usually a program bug - check if the code properly closes sockets.
Case 4: Count Concurrent Connections#
# Count connections per IP
netstat -ant | grep ESTABLISHED | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -nr | head -10
# Sample output
125 192.168.1.100
45 10.0.0.5
12 203.0.113.10
Quickly identify abnormal IPs (possible DDoS attack).
Performance: netstat vs ss#
netstat reads /proc files by iterating all sockets, performing poorly on high-concurrency servers:
# Performance comparison (100k connections)
time netstat -ant | wc -l # ~2-3 seconds
time ss -ant | wc -l # ~0.1 seconds
ss reads kernel netlink sockets directly, 20x faster. However, netstat is sufficient for low-concurrency scenarios with more readable output.
Advanced Techniques: Continuous Monitoring#
1. Real-time Connection Monitoring#
# Refresh every second
watch -n 1 'netstat -ant | grep ESTABLISHED | wc -l'
2. Monitor Specific Port#
# Monitor connection changes on port 80
watch -n 1 'netstat -ant | grep ":80 "'
3. Export Network Statistics to CSV#
netstat -i | awk 'NR>2 {print $1","$4","$5","$6","$7}' > network_stats.csv
Web Implementation: Browser-side “netstat”#
Browsers can’t directly access system network stacks, but can get local IPs via WebRTC:
async function getLocalIP(): Promise<string[]> {
return new Promise((resolve) => {
const ips: string[] = []
const pc = new RTCPeerConnection({ iceServers: [] })
pc.createDataChannel('')
pc.createOffer().then(offer => pc.setLocalDescription(offer))
pc.onicecandidate = (event) => {
if (!event?.candidate?.candidate) return
const match = event.candidate.candidate.match(/(\d+\.\d+\.\d+\.\d+)/)
if (match && !ips.includes(match[1])) {
ips.push(match[1])
}
if (pc.connectionState === 'closed') {
resolve(ips)
}
}
setTimeout(() => {
pc.close()
resolve(ips)
}, 1000)
})
}
// Usage
const localIPs = await getLocalIP()
console.log('Local IPs:', localIPs) // ['192.168.1.100', '10.0.0.5']
While limited in functionality, it demonstrates how to obtain network information on the frontend.
Common Pitfalls#
1. DNS Resolution Slows Things Down#
# Slow: performs DNS reverse lookup
netstat -a
# Fast: numeric display
netstat -an
2. -p Parameter Requires Root Privileges#
# Regular user: PID/Program name shows empty
netstat -tunlp
# Needs sudo
sudo netstat -tunlp
3. Network Namespaces in Containers#
Docker containers have independent network namespaces - host’s netstat can’t see container connections:
# Enter container's network namespace
docker exec <container_id> netstat -tunlp
netstat Online Tool#
For quick network connection information, try Linux netstat Command Reference, providing command details and common parameter explanations.
Summary#
netstat is a fundamental network diagnostic tool. Mastering it allows quick identification of most network issues. Key points:
- Understand
/procfilesystem as the data source - Master
-tunlpand-anparameter combinations - Familiarize with TCP states and their meanings
- Use
ssfor high-concurrency scenarios - Combine with
watchand pipes for continuous monitoring
Next time you encounter network connection issues, don’t just use ping and telnet - try netstat for more insights.
Related Tools: Port Checker | IP Query