How to monitor network usage with iftop
How to Monitor Network Usage with iftop
Network monitoring is a critical aspect of system administration and network management. Whether you're troubleshooting performance issues, identifying bandwidth-hungry applications, or simply keeping track of network activity, having the right tools is essential. One of the most powerful and user-friendly command-line tools for real-time network monitoring is iftop.
This comprehensive guide will walk you through everything you need to know about using iftop to monitor network usage effectively. You'll learn how to install, configure, and master this versatile tool, along with practical examples and troubleshooting techniques that will help you become proficient in network monitoring.
Table of Contents
1. [What is iftop?](#what-is-iftop)
2. [Prerequisites and Requirements](#prerequisites-and-requirements)
3. [Installation Guide](#installation-guide)
4. [Basic Usage and Interface](#basic-usage-and-interface)
5. [Command-Line Options](#command-line-options)
6. [Interactive Commands](#interactive-commands)
7. [Practical Examples and Use Cases](#practical-examples-and-use-cases)
8. [Configuration and Customization](#configuration-and-customization)
9. [Advanced Features](#advanced-features)
10. [Troubleshooting Common Issues](#troubleshooting-common-issues)
11. [Best Practices and Tips](#best-practices-and-tips)
12. [Conclusion](#conclusion)
What is iftop?
iftop is a command-line network monitoring tool that displays real-time bandwidth usage on network interfaces. Similar to how the `top` command shows running processes, iftop provides a live view of network connections and their associated bandwidth consumption.
Key features of iftop include:
- Real-time monitoring: Live display of network traffic with automatic updates
- Connection-based view: Shows individual connections between hosts
- Bandwidth measurement: Displays current, peak, and cumulative bandwidth usage
- Port resolution: Can display service names instead of port numbers
- Filtering capabilities: Supports network filters for focused monitoring
- Interactive interface: Provides keyboard shortcuts for real-time configuration
- Multiple display modes: Various sorting and display options
Prerequisites and Requirements
Before installing and using iftop, ensure your system meets the following requirements:
System Requirements
- Operating System: Linux, macOS, or Unix-like systems
- Root privileges: Required for monitoring network interfaces
- Network interface: At least one active network interface
- Terminal access: Command-line interface capability
Technical Prerequisites
- Basic understanding of networking concepts (IP addresses, ports, protocols)
- Familiarity with command-line operations
- Knowledge of your system's network interface names
- Understanding of bandwidth measurement units (Kb, Mb, GB)
Dependencies
Most modern Linux distributions include the necessary libraries, but you may need:
- libpcap: Packet capture library
- ncurses: Terminal interface library
- Development tools: If compiling from source
Installation Guide
Ubuntu/Debian Systems
```bash
Update package repository
sudo apt update
Install iftop
sudo apt install iftop
Verify installation
iftop --version
```
CentOS/RHEL/Fedora Systems
```bash
For CentOS/RHEL with EPEL repository
sudo yum install epel-release
sudo yum install iftop
For Fedora
sudo dnf install iftop
For newer RHEL versions
sudo dnf install iftop
```
macOS Systems
```bash
Using Homebrew
brew install iftop
Using MacPorts
sudo port install iftop
```
Arch Linux
```bash
Install from official repositories
sudo pacman -S iftop
```
Compiling from Source
If iftop isn't available in your distribution's repositories:
```bash
Download source code
wget http://www.ex-parrot.com/pdw/iftop/download/iftop-1.0pre4.tar.gz
Extract archive
tar -xzf iftop-1.0pre4.tar.gz
cd iftop-1.0pre4
Configure and compile
./configure
make
Install (requires root privileges)
sudo make install
```
Basic Usage and Interface
Starting iftop
The simplest way to start iftop is with root privileges:
```bash
sudo iftop
```
This command will automatically detect and monitor the default network interface.
Understanding the Interface
When iftop starts, you'll see a screen divided into several sections:
Header Section
- Shows the monitored interface name
- Displays current time and running duration
- Shows peak traffic rates
Connection List
The main area displays active connections with columns showing:
- Source and destination hosts: IP addresses or hostnames
- Traffic direction: Arrows indicating data flow
- Bandwidth rates: Current, 2-second average, 10-second average, and 40-second average
Footer Section
- TX: Total transmitted data
- RX: Total received data
- TOTAL: Combined transmitted and received data
- Peak rates: Maximum observed rates
- Cumulative totals: Total data transferred since monitoring began
Basic Navigation
Once iftop is running, you can use these essential keys:
- q: Quit iftop
- h: Display help
- n: Toggle DNS resolution
- s: Toggle source host display
- d: Toggle destination host display
- p: Toggle port display
Command-Line Options
iftop offers numerous command-line options for customization:
Interface Selection
```bash
Monitor specific interface
sudo iftop -i eth0
Monitor wireless interface
sudo iftop -i wlan0
List available interfaces
ip link show
```
Display Options
```bash
Don't resolve hostnames (faster performance)
sudo iftop -n
Don't resolve port numbers to service names
sudo iftop -N
Show ports by default
sudo iftop -p
Use bits instead of bytes
sudo iftop -b
Show bars instead of text
sudo iftop -B
```
Filtering Options
```bash
Monitor specific host
sudo iftop -f "host 192.168.1.100"
Monitor specific port
sudo iftop -f "port 80"
Monitor specific network
sudo iftop -f "net 192.168.1.0/24"
Exclude specific traffic
sudo iftop -f "not port 22"
```
Configuration Options
```bash
Use alternative configuration file
sudo iftop -c /path/to/config/file
Set text interface mode
sudo iftop -t
Specify line count for text mode
sudo iftop -t -L 10
```
Interactive Commands
While iftop is running, you can use interactive commands to modify the display:
Display Toggles
| Key | Function |
|-----|----------|
| n | Toggle DNS resolution |
| s | Toggle source host display |
| d | Toggle destination host display |
| N | Toggle port resolution |
| p | Toggle port display |
| P | Pause display |
| b | Toggle between bits/bytes |
| B | Toggle bar graph mode |
| T | Toggle cumulative line totals |
Sorting Options
| Key | Function |
|-----|----------|
| 1 | Sort by 1st column (2-second average) |
| 2 | Sort by 2nd column (10-second average) |
| 3 | Sort by 3rd column (40-second average) |
| < | Sort by source name |
| > | Sort by destination name |
Filtering Commands
| Key | Function |
|-----|----------|
| f | Edit filter code |
| l | Set screen filter |
| L | Clear screen filter |
| o | Freeze current order |
| j/k | Scroll up/down |
Practical Examples and Use Cases
Example 1: Basic Network Monitoring
Monitor the default network interface with hostname resolution:
```bash
sudo iftop
```
This provides a real-time view of all network connections, showing which hosts are communicating and how much bandwidth they're using.
Example 2: Monitoring Web Server Traffic
Monitor HTTP and HTTPS traffic on a web server:
```bash
sudo iftop -f "port 80 or port 443"
```
This filters the display to show only web traffic, helping identify which clients are consuming the most bandwidth.
Example 3: Monitoring Specific Host Communication
Track all traffic to and from a specific server:
```bash
sudo iftop -f "host 192.168.1.100"
```
Useful for monitoring a specific server's network activity or troubleshooting connectivity issues.
Example 4: High-Performance Monitoring
For systems with high network activity, disable DNS resolution for better performance:
```bash
sudo iftop -n -N -i eth0
```
This configuration provides faster updates by avoiding DNS lookups and service name resolution.
Example 5: Bandwidth Usage Analysis
Monitor and log network usage to a file:
```bash
sudo iftop -t -s 60 > network_usage.log
```
This runs iftop in text mode, updating every 60 seconds and saving output to a log file.
Example 6: Monitoring Multiple Interfaces
Create separate monitoring sessions for different interfaces:
```bash
Terminal 1: Monitor wired interface
sudo iftop -i eth0
Terminal 2: Monitor wireless interface
sudo iftop -i wlan0
```
Example 7: Database Server Monitoring
Monitor database traffic (example for MySQL):
```bash
sudo iftop -f "port 3306"
```
Helps identify which applications or users are generating the most database traffic.
Configuration and Customization
Configuration File
iftop can use a configuration file to set default options. Create `/etc/iftoprc` or `~/.iftoprc`:
```bash
Sample iftop configuration file
interface: eth0
dns-resolution: yes
port-resolution: no
filter-code:
port-display: on
show-bars: yes
promiscuous: no
port-resolution: no
sort: 2s
line-display: two-line
show-totals: yes
log-scale: yes
```
Environment Variables
Set environment variables for consistent behavior:
```bash
Set default interface
export IFTOP_INTERFACE=eth0
Disable DNS resolution by default
export IFTOP_NO_DNS=1
```
Custom Filters
Create complex filters for specific monitoring needs:
```bash
Monitor only TCP traffic excluding SSH
sudo iftop -f "tcp and not port 22"
Monitor traffic to specific subnet
sudo iftop -f "dst net 10.0.0.0/8"
Monitor high ports (ephemeral ports)
sudo iftop -f "port > 1024"
```
Advanced Features
Using iftop with Scripts
Create monitoring scripts that use iftop output:
```bash
#!/bin/bash
Script to capture network usage snapshot
INTERFACE="eth0"
DURATION=300 # 5 minutes
OUTPUT_FILE="/var/log/network_snapshot.log"
echo "Network monitoring started at $(date)" >> $OUTPUT_FILE
sudo timeout $DURATION iftop -i $INTERFACE -t -s 10 >> $OUTPUT_FILE
echo "Network monitoring completed at $(date)" >> $OUTPUT_FILE
```
Integration with System Monitoring
Combine iftop with other monitoring tools:
```bash
Monitor system resources alongside network usage
sudo iftop -i eth0 &
IFTOP_PID=$!
Monitor system resources
top -b -n1 | head -20
Clean up
kill $IFTOP_PID
```
Remote Monitoring
Monitor remote systems via SSH:
```bash
Monitor remote server network usage
ssh user@remote-server "sudo iftop -t -s 30 -L 20"
```
Automated Alerting
Create alerts based on network usage:
```bash
#!/bin/bash
Alert script for high network usage
THRESHOLD=1000000 # 1 MB/s in bytes
INTERFACE="eth0"
Get current usage (simplified example)
CURRENT_USAGE=$(sudo iftop -i $INTERFACE -t -s 5 | grep "Total" | tail -1)
Process and compare with threshold
(Implementation depends on specific requirements)
```
Troubleshooting Common Issues
Permission Denied Errors
Problem: iftop requires root privileges to access network interfaces.
Solution:
```bash
Run with sudo
sudo iftop
Or add user to appropriate group (varies by distribution)
sudo usermod -a -G netdev $USER
```
Interface Not Found
Problem: Specified network interface doesn't exist.
Solutions:
```bash
List available interfaces
ip link show
or
ifconfig -a
Use correct interface name
sudo iftop -i enp0s3 # Example for newer naming convention
```
High CPU Usage
Problem: iftop consuming excessive CPU resources.
Solutions:
```bash
Disable DNS resolution
sudo iftop -n
Disable port resolution
sudo iftop -N
Increase update interval
sudo iftop -s 10 # Update every 10 seconds
```
No Traffic Displayed
Problem: iftop shows no network traffic despite active connections.
Troubleshooting steps:
```bash
Check interface status
ip link show eth0
Verify interface has traffic
sudo tcpdump -i eth0 -c 10
Check for filtering issues
sudo iftop -i eth0 -f "" # Remove any filters
```
DNS Resolution Issues
Problem: Slow performance due to DNS lookups.
Solutions:
```bash
Disable DNS resolution
sudo iftop -n
Configure local DNS cache
Install and configure dnsmasq or systemd-resolved
```
Display Issues in Terminal
Problem: Garbled display or formatting issues.
Solutions:
```bash
Set proper terminal type
export TERM=xterm-256color
Use text mode for problematic terminals
sudo iftop -t
Clear terminal before running
clear && sudo iftop
```
Best Practices and Tips
Performance Optimization
1. Disable unnecessary resolution:
```bash
sudo iftop -n -N # Disable DNS and port resolution
```
2. Use appropriate update intervals:
```bash
sudo iftop -s 5 # Update every 5 seconds for less CPU usage
```
3. Filter traffic appropriately:
```bash
sudo iftop -f "not port 22" # Exclude SSH traffic
```
Security Considerations
1. Limit access: Only grant iftop access to necessary users
2. Use filters: Avoid monitoring sensitive traffic when possible
3. Log rotation: Implement proper log rotation for output files
4. Network segmentation: Monitor from appropriate network segments
Monitoring Best Practices
1. Establish baselines: Regular monitoring to understand normal patterns
2. Document findings: Keep records of unusual network activity
3. Combine tools: Use iftop alongside other monitoring solutions
4. Regular updates: Keep iftop updated for security and features
Automation Tips
1. Scheduled monitoring:
```bash
# Add to crontab for regular monitoring
0 /6 /usr/bin/sudo /usr/sbin/iftop -t -s 300 >> /var/log/network.log
```
2. Threshold-based alerts:
```bash
# Create scripts that parse iftop output for alerting
```
3. Integration with monitoring systems: Export data to monitoring platforms
Troubleshooting Workflow
1. Start with basic monitoring: Use default settings first
2. Identify the issue: Determine what specific information you need
3. Apply appropriate filters: Narrow down to relevant traffic
4. Document findings: Record unusual patterns or issues
5. Implement solutions: Make necessary network or application changes
Conclusion
iftop is an invaluable tool for network administrators, system administrators, and anyone who needs to monitor network usage in real-time. Its combination of powerful features, flexible configuration options, and intuitive interface makes it an essential addition to any network monitoring toolkit.
Throughout this guide, we've covered:
- Installation and setup across multiple operating systems
- Basic and advanced usage with practical examples
- Configuration and customization options for specific needs
- Troubleshooting techniques for common issues
- Best practices for effective network monitoring
By mastering iftop, you'll be able to:
- Quickly identify bandwidth-consuming applications and connections
- Troubleshoot network performance issues effectively
- Monitor network security and detect unusual activity
- Optimize network resources based on usage patterns
- Create automated monitoring solutions for your infrastructure
Next Steps
To further enhance your network monitoring capabilities, consider:
1. Exploring complementary tools like `nethogs`, `nload`, and `vnstat`
2. Implementing automated monitoring with scripts and cron jobs
3. Integrating iftop data with comprehensive monitoring solutions
4. Learning advanced filtering techniques for complex network environments
5. Developing custom dashboards that incorporate iftop data
Remember that effective network monitoring is an ongoing process that requires regular attention and continuous learning. iftop provides the foundation for understanding your network traffic patterns, but combining it with other tools and techniques will give you a complete picture of your network's health and performance.
Whether you're troubleshooting a specific issue, conducting regular network audits, or simply keeping an eye on your system's network activity, iftop will prove to be an indispensable tool in your network administration arsenal.