Python Central HubSign in

Python Projects / Advanced

Advanced Network Traffic Monitor

A Python application for real-time monitoring and analysis of network traffic, featuring packet capture, protocol analysis, and visualization.

Abstract

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.

Prerequisites

  • 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

Before you Start

Install Python and the required libraries:

Shell
pip install scapy matplotlib

Getting Started

Create a Project

  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.

Write the Code

Advanced Network Traffic MonitorSource
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)

Example Usage

Shell
sudo python advanced_network_traffic_monitor.py

How it fits together

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

Explanation

Key Features

  • 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.

Code Breakdown

  1. What it imports (lines 12–16)
Python
import psutil
import time
import sys
import matplotlib.pyplot as plt
import numpy as np
  1. TrafficMonitor — the class (lines 18–49)
Python
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)
Python
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.

Features

  • 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

Next Steps

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

Educational Value

This project teaches:

  • Network Programming: Packet capture and analysis
  • Data Visualization: Plotting statistics
  • Software Design: Modular, maintainable code
  • Error Handling: Writing robust Python code

Real-World Applications

  • Network Diagnostics
  • Security Analysis
  • Traffic Engineering
  • Educational Tools

Checkpoint exercise

This exercise practises turning cumulative byte counters into per-second rates and flagging spikes, the loop at the heart of a traffic monitor.

exerciseYour turn

Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.

Output
Press Run to see what your code prints.

Conclusion

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.

Was this page helpful?

Let us know how we did