1

I wrote simple script, that calculates bandwidth of my network. I used library scapy to sniff all incoming traffic and calculate speed. Here is my code, that sniffer traffic:

from time import sleep
from threading import Thread, Event
from scapy.all import *

class Sniffer(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.count_downloaded_bytes = 0

    def run(self):
        sniff(filter="ip", prn=self.get_packet)

    def get_packet(self, packet):
        self.count_downloaded_bytes += len(packet) # calculate size of packets

    def get_count_downloaded_bytes(self):
        count_d_bytes = self.count_downloaded_bytes
        self.count_downloaded_bytes = 0
        return count_d_bytes # returns size of downloaded data in bytes

This code calculates bandwidth in Mb/s every 10 seconds

class NetworkSpeed(Thread):
    def  __init__(self):
        Thread.__init__(self)
        self.sniffer = Sniffer() # create seconds thread, that sniffs traffic
        self.start()

    def calculate_bandwidth(self, count_downloaded_bytes, duration):
        download_speed = (count_downloaded_bytes / 1000000 * 8) / duration
        print('download_speed = ', download_speed)

    def run(self):
        counter = 0
        self.sniffer.start()
        while True:
            if counter == 10:
            self.calculate_bandwidth(self.sniffer.get_count_downloaded_bytes(), 10)
            counter = 0

        counter += 1
        sleep(1)

network_speed = NetworkSpeed()

I know, that the code is not really good, it is just a prototype. But I have next problem: I launched this script with root privileges and after 5 minutes my computer hangs, it started to work very-very slowly. It seems that this script took all RAM. How can I fix this ? because script should work at least 1 day.

Arr
  • 15
  • 2
  • The `while` loop (and the `if` statement inside it) are not correctly indented. I don't know if it's just in the formatting of your question. – mportes Jan 06 '19 at 21:19

1 Answers1

1

I think the problem may lay in the sniff function, try to call with

def run(self):
    sniff(filter="ip", prn=self.get_packet,store=False)

so that it doesn't save packets and fill the ram.

fuomag9
  • 138
  • 1
  • 12
  • thanks for your answer, it fixed my problem! I have some other question: I tried to measure bandwidth and it seems to me, that not all packets are received by my method def get_packet(self, packet); Is it possible, that scapy can not handle all packets, if I, for example, download file with speed 100 Mb/s ? – Arr Jan 07 '19 at 13:49
  • [How to sniff all packets on python when scapy and pypcap have serious loss?](https://stackoverflow.com/questions/47589322/how-to-sniff-all-packets-on-python-when-scapy-and-pypcap-have-serious-loss) This may help you – fuomag9 Jan 07 '19 at 14:02
  • thanks! there is the answer for Windows, but I need the solution for Linux. – Arr Jan 07 '19 at 17:14