How to show network connections → netstat
How to Show Network Connections → netstat
Table of Contents
1. [Introduction](#introduction)
2. [Prerequisites](#prerequisites)
3. [Understanding netstat](#understanding-netstat)
4. [Basic netstat Commands](#basic-netstat-commands)
5. [Advanced netstat Options](#advanced-netstat-options)
6. [Practical Examples and Use Cases](#practical-examples-and-use-cases)
7. [Platform-Specific Variations](#platform-specific-variations)
8. [Troubleshooting Common Issues](#troubleshooting-common-issues)
9. [Best Practices and Professional Tips](#best-practices-and-professional-tips)
10. [Alternative Tools](#alternative-tools)
11. [Conclusion](#conclusion)
Introduction
Network connectivity monitoring is a fundamental skill for system administrators, network engineers, and cybersecurity professionals. The `netstat` (network statistics) command is one of the most essential tools for displaying network connections, routing tables, interface statistics, masquerade connections, and multicast memberships on Unix-like systems and Windows.
This comprehensive guide will teach you how to effectively use netstat to monitor active network connections, identify listening ports, troubleshoot connectivity issues, and analyze network traffic patterns. Whether you're diagnosing network problems, performing security audits, or simply understanding your system's network behavior, mastering netstat is crucial for effective network administration.
By the end of this article, you'll understand how to use netstat's various options, interpret its output, and apply this knowledge to real-world scenarios ranging from basic connectivity checks to advanced network troubleshooting.
Prerequisites
Before diving into netstat usage, ensure you have:
System Requirements
- Access to a command line interface (Terminal on Linux/macOS, Command Prompt or PowerShell on Windows)
- Basic understanding of networking concepts (TCP/UDP, IP addresses, ports)
- Familiarity with command-line operations
- Administrative privileges (for some advanced operations)
Knowledge Prerequisites
- Basic understanding of network protocols (TCP, UDP, ICMP)
- Familiarity with IP addressing and port numbers
- Understanding of client-server architecture
- Basic knowledge of operating system concepts
Tools and Access
- Terminal or command prompt access
- Network connectivity (for testing examples)
- Optional: Text editor for saving output
- Optional: Administrative/root access for comprehensive monitoring
Understanding netstat
What is netstat?
Netstat is a command-line network utility that displays network connections for Transmission Control Protocol (both incoming and outgoing), routing tables, and network interface statistics. It's available on most operating systems and provides valuable insights into network activity.
Key Functions of netstat
1. Display Active Connections: Shows current TCP and UDP connections
2. List Listening Ports: Identifies services waiting for connections
3. Show Network Statistics: Provides protocol-specific statistics
4. Display Routing Tables: Shows network routing information
5. Monitor Network Interfaces: Displays interface statistics and status
Common Output Fields
When you run netstat, you'll typically see these columns:
- Proto: The protocol used (TCP, UDP, etc.)
- Local Address: The local IP address and port
- Foreign Address: The remote IP address and port
- State: The connection state (for TCP connections)
- PID/Program: Process ID and program name (when available)
Basic netstat Commands
Display All Connections
The most basic netstat command shows all active connections:
```bash
netstat -a
```
This command displays:
- All TCP connections
- All UDP connections
- All listening ports
Example Output:
```
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 192.168.1.100:22 192.168.1.50:54321 ESTABLISHED
udp 0 0 0.0.0.0:68 0.0.0.0:*
```
Show Only TCP Connections
To display only TCP connections:
```bash
netstat -t
```
Linux/Unix Example:
```bash
netstat -at # All TCP connections including listening
netstat -t # Only established TCP connections
```
Show Only UDP Connections
To display only UDP connections:
```bash
netstat -u
```
Example:
```bash
netstat -au # All UDP connections
```
Display Listening Ports Only
To show only ports that are listening for connections:
```bash
netstat -l
```
Combined Examples:
```bash
netstat -tl # TCP listening ports
netstat -ul # UDP listening ports
netstat -al # All listening ports
```
Show Numerical Addresses
By default, netstat may resolve IP addresses to hostnames. To show numerical addresses:
```bash
netstat -n
```
Example:
```bash
netstat -an # All connections with numerical addresses
netstat -tn # TCP connections with numerical addresses
```
Advanced netstat Options
Display Process Information
To show which process is using each connection:
Linux/Unix:
```bash
netstat -p
```
Combined Example:
```bash
netstat -tulpn
t = TCP
u = UDP
l = listening
p = process
n = numerical addresses
```
Example Output:
```
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 1234/nginx
tcp 0 0 0.0.0.0:443 0.0.0.0:* LISTEN 1234/nginx
tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN 5678/mysqld
```
Show Network Statistics
To display protocol statistics:
```bash
netstat -s
```
This shows detailed statistics for:
- IP packets
- TCP segments
- UDP datagrams
- ICMP messages
- Error counts
Example Output Snippet:
```
Tcp:
1500 active connections openings
800 passive connection openings
50 failed connection attempts
200 connection resets received
5 connections established
```
Display Routing Table
To show the routing table:
```bash
netstat -r
```
Alternative (more common):
```bash
netstat -rn # Numerical format
```
Example Output:
```
Destination Gateway Genmask Flags MSS Window irtt Iface
0.0.0.0 192.168.1.1 0.0.0.0 UG 0 0 0 eth0
192.168.1.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0
```
Show Interface Statistics
To display network interface statistics:
```bash
netstat -i
```
Example Output:
```
Iface MTU Met RX-OK RX-ERR RX-DRP RX-OVR TX-OK TX-ERR TX-DRP TX-OVR Flg
eth0 1500 0 125643 0 0 0 98234 0 0 0 BMRU
lo 65536 0 1234 0 0 0 1234 0 0 0 LRU
```
Continuous Monitoring
To continuously monitor connections (update every few seconds):
```bash
netstat -c
```
With interval specification:
```bash
netstat -c 5 # Update every 5 seconds
```
Practical Examples and Use Cases
Example 1: Finding Which Process is Using a Specific Port
To find what's running on port 80:
```bash
netstat -tulpn | grep :80
```
Expected Output:
```
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 1234/nginx: master
```
Example 2: Checking for Suspicious Connections
To look for unusual outbound connections:
```bash
netstat -tupln | grep ESTABLISHED
```
Analysis Script:
```bash
#!/bin/bash
echo "Checking for suspicious outbound connections..."
netstat -tupln | grep ESTABLISHED | while read line; do
echo "$line"
# Add logic to check against known good connections
done
```
Example 3: Monitoring Database Connections
To monitor MySQL connections:
```bash
netstat -an | grep :3306
```
Enhanced version:
```bash
netstat -tupln | grep :3306 | wc -l
echo "Total MySQL connections: $(netstat -an | grep :3306 | grep ESTABLISHED | wc -l)"
```
Example 4: Network Troubleshooting Script
```bash
#!/bin/bash
echo "=== Network Connection Summary ==="
echo "Listening TCP ports:"
netstat -tln | grep LISTEN | awk '{print $4}' | sort
echo -e "\nEstablished connections:"
netstat -tn | grep ESTABLISHED | wc -l
echo -e "\nTop 5 most connected remote hosts:"
netstat -tn | grep ESTABLISHED | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -nr | head -5
```
Example 5: Web Server Connection Analysis
For analyzing web server connections:
```bash
Count connections by state
netstat -an | grep :80 | awk '{print $6}' | sort | uniq -c
Show top connecting IPs
netstat -an | grep :80 | grep ESTABLISHED | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -nr | head -10
```
Example 6: Security Audit - Open Ports Check
```bash
#!/bin/bash
echo "=== Open Ports Security Audit ==="
echo "TCP Listening Ports:"
netstat -tln | grep LISTEN | awk '{print $4}' | cut -d: -f2 | sort -n
echo -e "\nUDP Listening Ports:"
netstat -uln | awk '{print $4}' | cut -d: -f2 | sort -n | grep -v "^$"
echo -e "\nServices with external access:"
netstat -tln | grep -v "127.0.0.1\|::1" | grep LISTEN
```
Platform-Specific Variations
Linux netstat
Linux netstat supports the most comprehensive set of options:
```bash
Most useful Linux combination
netstat -tulpn
Show extended information
netstat -ee
Show timer information
netstat -o
```
macOS netstat
macOS has some differences in options:
```bash
Show all connections with process info (requires sudo)
sudo netstat -anvp tcp
Show listening ports
netstat -an | grep LISTEN
Show routing table
netstat -rn
```
Windows netstat
Windows netstat syntax differs slightly:
```cmd
Show all connections with process IDs
netstat -ano
Show only TCP connections
netstat -an -p tcp
Show statistics
netstat -s
Show routing table
netstat -r
```
Windows-specific example:
```cmd
netstat -ano | findstr :80
netstat -ano | findstr LISTENING
```
FreeBSD/OpenBSD netstat
BSD variants have unique options:
```bash
Show network memory usage
netstat -m
Show multicast group memberships
netstat -g
Show protocol control blocks
netstat -A
```
Troubleshooting Common Issues
Issue 1: "netstat: command not found"
Problem: netstat is not installed or not in PATH.
Solutions:
Linux (Ubuntu/Debian):
```bash
sudo apt-get install net-tools
```
Linux (CentOS/RHEL):
```bash
sudo yum install net-tools
or for newer versions
sudo dnf install net-tools
```
Alternative: Use `ss` command (modern replacement):
```bash
ss -tulpn # Similar to netstat -tulpn
```
Issue 2: Permission Denied for Process Information
Problem: Cannot see process names/PIDs.
Solution: Run with elevated privileges:
```bash
sudo netstat -tulpn # Linux/macOS
```
Windows: Run Command Prompt as Administrator.
Issue 3: Output Too Long to Read
Problem: Too much output to analyze effectively.
Solutions:
Filter specific ports:
```bash
netstat -tulpn | grep :80
netstat -tulpn | grep :443
```
Save to file:
```bash
netstat -tulpn > network_connections.txt
```
Use pagination:
```bash
netstat -tulpn | less
netstat -tulpn | more
```
Issue 4: Resolving Hostnames Takes Too Long
Problem: netstat is slow due to DNS lookups.
Solution: Use `-n` flag to show numerical addresses:
```bash
netstat -tuln # Much faster
```
Issue 5: Understanding Connection States
Problem: Confusion about TCP connection states.
Connection States Explained:
- `LISTEN`: Port is open and listening for connections
- `ESTABLISHED`: Active connection is established
- `TIME_WAIT`: Connection is closed but waiting for remote acknowledgment
- `CLOSE_WAIT`: Remote end has closed the connection
- `FIN_WAIT1/FIN_WAIT2`: Local end is closing the connection
- `SYN_SENT`: Attempting to establish connection
- `SYN_RECV`: Received connection request
Issue 6: High Number of TIME_WAIT Connections
Problem: Too many connections in TIME_WAIT state.
Investigation:
```bash
netstat -an | grep TIME_WAIT | wc -l
```
Analysis:
```bash
Show which ports have most TIME_WAIT connections
netstat -an | grep TIME_WAIT | awk '{print $4}' | cut -d: -f2 | sort | uniq -c | sort -nr
```
Best Practices and Professional Tips
1. Regular Monitoring Practices
Create monitoring scripts:
```bash
#!/bin/bash
Daily network connection report
DATE=$(date +%Y%m%d)
REPORT_FILE="network_report_$DATE.txt"
{
echo "=== Network Connection Report - $(date) ==="
echo "Listening services:"
netstat -tln | grep LISTEN
echo -e "\nConnection summary:"
netstat -an | awk '/^tcp/ {print $6}' | sort | uniq -c
echo -e "\nTop 10 connected IPs:"
netstat -tn | grep ESTABLISHED | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -nr | head -10
} > "$REPORT_FILE"
```
2. Security Monitoring
Port scan detection:
```bash
Monitor for port scanning attempts
netstat -an | grep SYN_RECV | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -nr
```
Unusual connection monitoring:
```bash
Check for connections to unusual ports
netstat -tn | grep ESTABLISHED | awk '{print $3}' | cut -d: -f2 | sort -n | uniq
```
3. Performance Analysis
Connection counting by service:
```bash
#!/bin/bash
echo "Connection count by service port:"
netstat -tn | grep ESTABLISHED | awk '{print $4}' | cut -d: -f2 | sort | uniq -c | sort -nr
```
Network load analysis:
```bash
Monitor network statistics over time
while true; do
echo "$(date): $(netstat -i | grep eth0 | awk '{print "RX: " $3 " TX: " $7}')"
sleep 60
done
```
4. Automation and Scripting
Automated alerting:
```bash
#!/bin/bash
MAX_CONNECTIONS=1000
CURRENT_CONNECTIONS=$(netstat -an | grep ESTABLISHED | wc -l)
if [ $CURRENT_CONNECTIONS -gt $MAX_CONNECTIONS ]; then
echo "ALERT: High connection count: $CURRENT_CONNECTIONS" | mail -s "Network Alert" admin@company.com
fi
```
5. Documentation and Reporting
Generate network inventory:
```bash
#!/bin/bash
{
echo "=== Network Service Inventory ==="
echo "Listening TCP Services:"
netstat -tln | grep LISTEN | awk '{print $4}' | sort
echo -e "\nListening UDP Services:"
netstat -uln | awk '{print $4}' | sort
echo -e "\nActive Network Interfaces:"
netstat -i | grep -v "Kernel\|Iface"
} > network_inventory.txt
```
6. Professional Tips
- Use consistent flags: Develop muscle memory with common flag combinations like `-tulpn`
- Combine with other tools: Use with `grep`, `awk`, `sort` for powerful analysis
- Regular baselines: Establish normal connection patterns for your systems
- Monitor trends: Track connection counts and patterns over time
- Security focus: Regularly audit listening services and external connections
- Documentation: Document expected connections and services
7. Modern Alternatives
While netstat is still widely used, consider these modern alternatives:
ss command (Linux):
```bash
ss -tulpn # Faster and more detailed than netstat
ss -s # Socket statistics
```
lsof for process-specific analysis:
```bash
lsof -i :80 # Show what's using port 80
lsof -i tcp # Show all TCP connections
```
Alternative Tools
ss (Socket Statistics)
The `ss` command is the modern replacement for netstat on Linux systems:
```bash
Basic usage similar to netstat
ss -tulpn
ss -s # Summary statistics
ss -o # Show timer information
ss -e # Show extended socket information
```
Advantages of ss:
- Faster than netstat
- More detailed information
- Better filtering capabilities
- Active development and support
lsof (List Open Files)
For process-specific network analysis:
```bash
lsof -i # All network connections
lsof -i :80 # Specific port
lsof -i tcp # TCP connections only
lsof -i udp # UDP connections only
lsof -u username # Connections by user
```
nmap for Port Scanning
For external port verification:
```bash
nmap -sT localhost # TCP scan of localhost
nmap -sU localhost # UDP scan
nmap -p 80,443 target_host # Specific ports
```
tcpdump for Packet Analysis
For detailed network traffic analysis:
```bash
tcpdump -i eth0 port 80 # Monitor HTTP traffic
tcpdump -i any host 8.8.8.8 # Monitor specific host
```
Conclusion
Mastering the netstat command is essential for effective network administration, security monitoring, and troubleshooting. This comprehensive guide has covered everything from basic usage to advanced techniques, providing you with the knowledge and tools needed to effectively monitor and analyze network connections.
Key Takeaways
1. Basic Proficiency: Understanding fundamental netstat options (`-a`, `-t`, `-u`, `-l`, `-n`, `-p`) forms the foundation of network monitoring
2. Practical Application: Combining netstat with other command-line tools creates powerful analysis capabilities
3. Security Awareness: Regular monitoring of network connections is crucial for identifying security issues
4. Platform Differences: While core functionality is similar, each operating system has unique netstat features
5. Modern Alternatives: Tools like `ss` and `lsof` complement or replace netstat in modern environments
Next Steps
To further develop your network monitoring skills:
1. Practice Regularly: Use netstat daily to monitor your systems
2. Create Scripts: Develop automated monitoring and alerting scripts
3. Learn Complementary Tools: Master `ss`, `lsof`, `tcpdump`, and `nmap`
4. Study Network Protocols: Deepen your understanding of TCP/UDP and network communication
5. Implement Monitoring: Set up comprehensive network monitoring for your infrastructure
6. Security Focus: Integrate netstat into your security monitoring and incident response procedures
Professional Development
Consider these areas for continued learning:
- Network security monitoring and analysis
- Advanced scripting and automation
- Enterprise network monitoring solutions
- Network troubleshooting methodologies
- Performance optimization techniques
With the knowledge gained from this guide, you're well-equipped to use netstat effectively for network administration, security monitoring, and troubleshooting tasks. Remember that network monitoring is an ongoing process, and regular practice with these tools will make you more proficient in identifying and resolving network issues quickly and effectively.
The combination of understanding network fundamentals, mastering command-line tools like netstat, and developing good monitoring practices will serve you well in any network administration or cybersecurity role. Keep practicing, stay curious about network behavior, and always maintain a security-focused mindset when analyzing network connections.