Create a Network Traffic Monitor using Python

network traffic monitor

Introduction

You are reading this article, which means your system is connected to an internet connection. But do you ever check how much data your computer sent and received? While operating systems offer built-in tools like Task Manager (Windows) and System Monitor (Linux/Mac) to provide network statistics, this tutorial will guide you in creating a custom network traffic monitor using Python.

Weā€™ll explore building a Python application that displays real-time data on your systemā€™s network activity, including total data transferred, upload, and download speeds. To achieve this, weā€™ll use the powerful psutil library for gathering system information and the prettytable library for presenting data in a user-friendly format. By the end, youā€™ll have a clear understanding of your network behavior.

Read Also: Create a Python Network Scanner: Find IPs & MACs

Requirements and Installations

Make sure Python is installed on your system. You can install it from their official website python.org. Now install the psutil and prettytable libraries using the following command:

pip install psutil prettytable

The Program

Open your favorite text editor and create a Python file named ā€˜traffic_monitor.pyā€™. Now copy the code from below and paste it into that Python file.

import os
import time
import psutil
from prettytable import PrettyTable
from prettytable import DOUBLE_BORDER

# Units of memory sizes
size = ['bytes', 'KB', 'MB', 'GB', 'TB']

# Function that returns bytes in a readable format
def getSize(bytes):
    for unit in size:
        if bytes < 1024:
            return f"{bytes:.1f}{unit}"
        bytes /= 1024

# Prints the Data on the Terminal or Console
def printData():
    # Creating an instance of PrettyTable class
    card = PrettyTable()
    card.set_style(DOUBLE_BORDER)
    # Column Names of the table
    card.field_names = ["Received", "Receiving", "Sent", 'Sending']
    # Adding row to the table
    card.add_row([f"{getSize(netStats2.bytes_recv)}", 
    f"{getSize(downloadStat)}/s", f"{getSize(netStats2.bytes_sent)}", 
    f"{getSize(uploadStat)}/s"])
    print(card)

# psutil.net_io_counters() returns network I/O statistics as a namedtuple
netStats1 = psutil.net_io_counters()

# Getting the data of total bytes sent and received
dataSent = netStats1.bytes_sent
dataRecv = netStats1.bytes_recv

# Running a loop to get the data continuously
while True:
    # Delay for one second
    time.sleep(1)

    # Clear the Terminal or Console
    # For Windows: use 'cls'
    # For Linux and Mac, keep it as it is
    os.system('clear')

    # Getting the network i/o stats again to 
    # count the sending and receiving speed
    netStats2 = psutil.net_io_counters()

    # Upload/Sending speed
    uploadStat = netStats2.bytes_sent - dataSent
    # Receiving/Download Speed
    downloadStat = netStats2.bytes_recv - dataRecv

    # Print the Data
    printData()

    # Agian getting the data of total bytes sent and received
    dataSent = netStats2.bytes_sent
    dataRecv = netStats2.bytes_recv

Output

Output

Summary

In this tutorial, we learned how to create a Python-based network traffic monitor. We used the psutil library to collect network data and prettytable library to present it in a clear tabular format on the terminal/command prompt.

For verification, run the program parallel with Task Manager (or System Monitor) to compare the displayed network data.

For any query, reach out to me at contact@pyseek.com.

Happy Coding!

Share your love
Subhankar Rakshit
Subhankar Rakshit

Hey there! Iā€™m Subhankar Rakshit, the brains behind PySeek. Iā€™m a Post Graduate in Computer Science. PySeek is where I channel my love for Python programming and share it with the world through engaging and informative blogs.

Articles:Ā 194