Script to track network usage showing increased results when not sending packets

27 Views Asked by At

I am trying to monitor the network usage of a python script using psutil and to test this I am using a basic socket programme. When I send this data repeatedly for 60 seconds I get a smaller number than when i just wait for 60 seconds.

I get approxamatly 100858 packets when I just wait and approxamatly 120 when i send the udp packets.

I am running this on a rock pi SBC running Ubuntu, and the server is my laptop on the same local network.

My function to send the data over udp is this

def test_network_and_cpu(duration=60):
    # Define the target host and port for sending and receiving packets
    target_host = '192.168.0.168'
    target_port = 12345
    
    # Create a UDP socket for sending and receiving packets
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    
    # Set a timeout for the socket operations
    sock.settimeout(1)
    
    # Get the start time
    start_time = time.time()
    
    # Initialize counters for sent and received packets
    sent_packets = 0
    received_packets = 0
    
    # Loop until the specified duration is reached
    while time.time() - start_time < duration:
        # Send a packet
        sock.sendto(b"TestPacket", (target_host, target_port))
        sent_packets += 1
        
        # Try to receive a packet
        try:
            data, addr = sock.recvfrom(1024)
            if data:
                received_packets += 1
        except socket.timeout:
            pass
       
        
        # Print CPU load and packet statistics
        print(f"Sent: {sent_packets} | Received: {received_packets}", end='\r')
        
    # Close the socket
    sock.close()
    
    # Print a final message
    print("\nTest completed.")

and I am measuring my network uasage using this

    start_pkts_sent = psutil.net_io_counters().packets_sent
    start_pkts_recv = psutil.net_io_counters().packets_recv
    cpu_percents = monitor(target=test_network_and_cpu)
    end_pkts_sent = psutil.net_io_counters().packets_sent
    end_pkts_recv = psutil.net_io_counters().packets_recv

    final_pkts_sent = end_pkts_sent - start_pkts_sent
    final_pkts_recv = end_pkts_recv - start_pkts_recv

the monitor function is used to get the average cpu usage, i have added it here but it is probably not relevant

def monitor(target):
    worker_process = mp.Process(target=target)
    worker_process.start()
    p = psutil.Process(worker_process.pid)

    # log cpu usage of `worker_process` every 10 ms
    cpu_percents = []
    while worker_process.is_alive():
        cpu_percents.append(p.cpu_percent())
        time.sleep(0.1)

    worker_process.join()
    return cpu_percents
0

There are 0 best solutions below