How to Make a Network Usage Monitor in Python
Published on Aug. 22, 2023, 12:16 p.m.
To make a network usage monitor in Python, you can use the psutil
library to get information about network connections and data transfer rates. Here is an example code snippet:
import psutil
import time
def monitor_network():
old_value = psutil.net_io_counters().bytes_sent + psutil.net_io_counters().bytes_recv
while True:
new_value = psutil.net_io_counters().bytes_sent + psutil.net_io_counters().bytes_recv
bytes_per_second = (new_value - old_value) / 1
old_value = new_value
print("Current network usage: ", bytes_per_second, "bytes per second")
time.sleep(1)
monitor_network()
Current network usage: 0.0 bytes per second
Current network usage: 16622.0 bytes per second
Current network usage: 290297.0 bytes per second
Current network usage: 31555.0 bytes per second
Current network usage: 11301.0 bytes per second
Current network usage: 10862.0 bytes per second
Current network usage: 2454.0 bytes per second
Current network usage: 20847.0 bytes per second
Current network usage: 200564.0 bytes per second
Current network usage: 107393.0 bytes per second
In this example, we define a function called monitor_network()
that uses the psutil
library to get the current number of bytes sent and received by the system through network connections. We use a while loop to continuously calculate the rate of data transfer in bytes per second and print the result to the console.
We sleep for 1 second between iterations to avoid consuming too much processing time.
You can modify this code to suit your specific monitoring requirements, such as tracking usage over a longer period or logging the data to a file.
Please note that network monitoring may require elevated privileges on some systems, and should be used responsibly and only with the appropriate permissions.