Skip to content

Advanced Network Traffic Monitor

Advanced Network Traffic Monitor is a Python project that enables real-time monitoring and analysis of network traffic. The application captures packets, analyzes protocols, and visualizes traffic statistics. It demonstrates network programming, packet parsing, and data visualization, making it suitable for security analysis and network diagnostics.

  • Python 3.8 or above
  • A code editor or IDE
  • Basic understanding of networking concepts
  • Required libraries: scapy, matplotlib
  • Administrator/root privileges for packet capture

Install Python and the required libraries:

Install dependencies
pip install scapy matplotlib
  1. Create a folder named advanced-network-traffic-monitor.
  2. Open the folder in your code editor or IDE.
  3. Create a file named advanced_network_traffic_monitor.py.
  4. Copy the code below into your file.
Advanced Network Traffic Monitor pch.viewSource
Advanced Network Traffic Monitor
"""
Advanced Network Traffic Monitor

Features:
- Network traffic analysis
- Visualization
- Anomaly detection
- Modular design
- CLI interface
- Error handling
"""
import psutil
import time
import sys
import matplotlib.pyplot as plt
import numpy as np

class TrafficMonitor:
    def __init__(self):
        self.data = []
        self.timestamps = []

    def collect(self, duration=60):
        print("Collecting network traffic data...")
        for _ in range(duration):
            stats = psutil.net_io_counters()
            self.data.append(stats.bytes_sent + stats.bytes_recv)
            self.timestamps.append(time.time())
            time.sleep(1)

    def detect_anomaly(self):
        arr = np.array(self.data)
        mean = arr.mean()
        std = arr.std()
        anomalies = [(i, v) for i, v in enumerate(arr) if abs(v - mean) > 2*std]
        return anomalies

    def visualize(self):
        plt.plot(self.timestamps, self.data, label='Traffic')
        anomalies = self.detect_anomaly()
        for idx, val in anomalies:
            plt.scatter(self.timestamps[idx], val, color='r', label='Anomaly' if idx==anomalies[0][0] else "")
        plt.xlabel('Time')
        plt.ylabel('Bytes')
        plt.title('Network Traffic Over Time')
        plt.legend()
        plt.savefig("advanced_network_traffic_monitor.png", dpi=120, bbox_inches="tight")
        print("saved advanced_network_traffic_monitor.png")
        plt.show()

class CLI:
    @staticmethod
    def run():
        monitor = TrafficMonitor()
        monitor.collect(60)
        print("Visualizing...")
        monitor.visualize()
        anomalies = monitor.detect_anomaly()
        print(f"Anomalies detected: {anomalies}")

if __name__ == "__main__":
    try:
        CLI.run()
    except Exception as e:
        print(f"Error: {e}")
        sys.exit(1)
Run the network monitor
sudo python advanced_network_traffic_monitor.py

Read from the top: this is what runs when you execute the file, and which function calls which. It is generated from the code, so it cannot drift from it.

diagram Diagram mermaid
  • Packet Capture: Uses Scapy to capture live network packets.
  • Protocol Analysis: Identifies and counts protocols (TCP, UDP, ICMP).
  • Traffic Visualization: Plots protocol distribution using matplotlib.
  • Error Handling: Manages permissions and invalid inputs.
  • CLI Interface: Interactive command-line usage.
  1. What it imports (lines 12–16)
advanced_network_traffic_monitor.py
import psutil
import time
import sys
import matplotlib.pyplot as plt
import numpy as np
  1. TrafficMonitor — the class (lines 18–49)
advanced_network_traffic_monitor.py
class TrafficMonitor:
    def __init__(self):
        self.data = []
        self.timestamps = []
 
    def collect(self, duration=60):
        print("Collecting network traffic data...")
        for _ in range(duration):
            stats = psutil.net_io_counters()
            self.data.append(stats.bytes_sent + stats.bytes_recv)
            self.timestamps.append(time.time())
            time.sleep(1)
 
    def detect_anomaly(self):
        arr = np.array(self.data)
        mean = arr.mean()
        std = arr.std()
        anomalies = [(i, v) for i, v in enumerate(arr) if abs(v - mean) > 2*std]
        # ... 8 more lines in the file ...
        plt.ylabel('Bytes')
        plt.title('Network Traffic Over Time')
        plt.legend()
        plt.savefig("advanced_network_traffic_monitor.png", dpi=120, bbox_inches="tight")
        print("saved advanced_network_traffic_monitor.png")
        plt.show()
  1. CLI — the class (lines 51–59)
advanced_network_traffic_monitor.py
class CLI:
    @staticmethod
    def run():
        monitor = TrafficMonitor()
        monitor.collect(60)
        print("Visualizing...")
        monitor.visualize()
        anomalies = monitor.detect_anomaly()
        print(f"Anomalies detected: {anomalies}")

The file defines 2 top-level symbols in all; the whole thing is above under Write the Code.

  • Real-Time Monitoring: Captures and analyzes live traffic
  • Protocol Analysis: Identifies and counts protocols
  • Visualization: Plots protocol distribution
  • Error Handling: Manages permissions and exceptions
  • Production-Ready: Modular and maintainable code

Enhance the project by:

  • Adding support for more protocols
  • Logging captured packets to a file
  • Creating a GUI for visualization
  • Integrating with intrusion detection systems
  • Adding batch analysis of pcap files
  • Unit testing for reliability

This project teaches:

  • Network Programming: Packet capture and analysis
  • Data Visualization: Plotting statistics
  • Software Design: Modular, maintainable code
  • Error Handling: Writing robust Python code
  • Network Diagnostics
  • Security Analysis
  • Traffic Engineering
  • Educational Tools

Advanced Network Traffic Monitor provides a robust framework for real-time network analysis and visualization. With extensible design and error handling, it is suitable for diagnostics, security, and educational use. For more advanced projects, visit Python Central Hub.

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading