The Palos Publishing Company

Follow Us On The X Platform @PalosPublishing
Categories We Write About

Monitor your own internet usage with Python

Monitoring your own internet usage can be both insightful and essential, especially when managing bandwidth, optimizing application performance, or identifying unusual traffic patterns. Python, with its rich ecosystem of libraries and system access capabilities, allows you to build custom internet usage monitoring tools. This guide covers how to monitor network data usage on a computer using Python, with code examples and step-by-step explanations.

Required Python Libraries

To monitor network traffic, you’ll typically rely on libraries that provide access to system-level network interfaces. The following Python libraries are most useful for this task:

  • psutil: Provides information on system utilization including CPU, memory, disks, and network.

  • time: Native module for time-related tasks like delays and timestamps.

  • csv or sqlite3 (optional): For logging and storing data.

  • matplotlib (optional): For visualizing internet usage.

You can install the required libraries using pip:

bash
pip install psutil matplotlib

Accessing Network Statistics with psutil

The psutil.net_io_counters() function provides byte-level statistics of network interfaces. Here’s a basic usage example:

python
import psutil net_io = psutil.net_io_counters() print(f"Bytes Sent: {net_io.bytes_sent}") print(f"Bytes Received: {net_io.bytes_recv}")

This gives you the total number of bytes sent and received since the system was last booted. To monitor in real-time, you’d need to take snapshots at intervals and calculate the difference.

Building a Real-Time Internet Usage Monitor

Below is a script that tracks internet usage over time:

python
import psutil import time def bytes_to_mb(bytes): return round(bytes / (1024 ** 2), 2) print("Monitoring internet usage. Press Ctrl+C to stop.n") try: old_sent = psutil.net_io_counters().bytes_sent old_recv = psutil.net_io_counters().bytes_recv while True: time.sleep(1) new_sent = psutil.net_io_counters().bytes_sent new_recv = psutil.net_io_counters().bytes_recv upload_speed = bytes_to_mb(new_sent - old_sent) download_speed = bytes_to_mb(new_recv - old_recv) print(f"Upload: {upload_speed} MB/s, Download: {download_speed} MB/s") old_sent, old_recv = new_sent, new_recv except KeyboardInterrupt: print("nMonitoring stopped.")

This script continuously monitors upload and download speeds every second. It provides a real-time view of how much data is being transferred.

Logging Data Usage Over Time

To analyze internet usage trends, it’s useful to store the data in a file. Here’s how to log the data into a CSV file:

python
import psutil import time import csv def bytes_to_mb(bytes): return round(bytes / (1024 ** 2), 2) filename = "internet_usage_log.csv" with open(filename, mode='w', newline='') as file: writer = csv.writer(file) writer.writerow(["Time", "Upload_MB", "Download_MB"]) old_sent = psutil.net_io_counters().bytes_sent old_recv = psutil.net_io_counters().bytes_recv try: while True: time.sleep(1) new_sent = psutil.net_io_counters().bytes_sent new_recv = psutil.net_io_counters().bytes_recv upload = bytes_to_mb(new_sent - old_sent) download = bytes_to_mb(new_recv - old_recv) timestamp = time.strftime("%Y-%m-%d %H:%M:%S") writer.writerow([timestamp, upload, download]) print(f"{timestamp} | Upload: {upload} MB | Download: {download} MB") old_sent, old_recv = new_sent, new_recv except KeyboardInterrupt: print("nLogging stopped.")

Visualizing Internet Usage

Using matplotlib, you can plot your logged internet data usage to visually analyze usage patterns:

python
import csv import matplotlib.pyplot as plt timestamps = [] uploads = [] downloads = [] with open("internet_usage_log.csv", newline='') as csvfile: reader = csv.DictReader(csvfile) for row in reader: timestamps.append(row["Time"]) uploads.append(float(row["Upload_MB"])) downloads.append(float(row["Download_MB"])) plt.figure(figsize=(12, 6)) plt.plot(timestamps, uploads, label='Upload (MB)', color='blue') plt.plot(timestamps, downloads, label='Download (MB)', color='green') plt.xlabel('Time') plt.ylabel('Data (MB)') plt.title('Internet Usage Over Time') plt.xticks(rotation=45) plt.legend() plt.tight_layout() plt.show()

Monitoring Specific Applications or Interfaces

To go further, you can monitor usage per network interface or process. Here’s how to list network usage by interface:

python
net_io = psutil.net_io_counters(pernic=True) for iface, stats in net_io.items(): print(f"{iface}: Sent={bytes_to_mb(stats.bytes_sent)} MB, Received={bytes_to_mb(stats.bytes_recv)} MB")

For per-process network usage, you’d need to inspect open network connections and calculate data based on traffic stats. This requires administrative privileges and is more complex, often involving socket tracking or using third-party tools like scapy or nethogs.

Creating a GUI Dashboard (Optional)

You can integrate the monitoring system into a GUI using libraries like tkinter, PyQt, or dash for interactive dashboards.

Example with tkinter:

python
import tkinter as tk import psutil import time import threading def update_stats(): old_sent = psutil.net_io_counters().bytes_sent old_recv = psutil.net_io_counters().bytes_recv while True: time.sleep(1) new_sent = psutil.net_io_counters().bytes_sent new_recv = psutil.net_io_counters().bytes_recv upload = bytes_to_mb(new_sent - old_sent) download = bytes_to_mb(new_recv - old_recv) label_upload.config(text=f"Upload: {upload} MB/s") label_download.config(text=f"Download: {download} MB/s") old_sent, old_recv = new_sent, new_recv def bytes_to_mb(bytes): return round(bytes / (1024 ** 2), 2) root = tk.Tk() root.title("Internet Usage Monitor") label_upload = tk.Label(root, text="Upload: 0 MB/s", font=('Arial', 14)) label_download = tk.Label(root, text="Download: 0 MB/s", font=('Arial', 14)) label_upload.pack(pady=10) label_download.pack(pady=10) thread = threading.Thread(target=update_stats) thread.daemon = True thread.start() root.mainloop()

This basic GUI updates internet usage in real-time.

Security and Privacy Considerations

While monitoring your own usage is generally safe, be mindful of:

  • Permission issues: Some OS configurations may require elevated permissions.

  • Performance impact: Real-time monitoring every second can slightly impact system performance.

  • Storage: Logging usage over long periods consumes disk space; consider implementing rotation or summarization.

Conclusion

Python offers a versatile toolkit for monitoring internet usage, from simple scripts to sophisticated dashboards. Whether you’re logging total usage, tracking per-process consumption, or visualizing patterns, Python makes it easy to take control of your network data.

Share this Page your favorite way: Click any app below to share.

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Categories We Write About