Search code examples
linuxnetwork-programminglivecapturepacket

Live packet capture on linux


I would like to know if there is any possibility to live capture network packets and save it to a variable for example in python. I need some information to get from it and not to save it to a file.

I need to capture http packets and get source addres and its content, which should be a html code, to extract only text from it and then do the rest of the job on that information. There is no reason to save every packet to a file because whole process would be more slower. I was looking for quite a long time for any tool to do this but no success. Please, if you know any tool that could help me to do this, write about it.


Solution

  • I'm sure you have seen this link about a library to process PCAP files. Now the question is how to acquire in real time without storing in a file.

    Probably easiest is to use a fifo

    $ mkfifo /tmp/tcpdump.fifo
    

    Now you can capture and feed data into the named fifo

    $ sudo tcpdump -s0 -i eth0 -f /tmp/tcpdump.fifo tcp port 80
    

    And in your python program you can open '/tmp/tcpdump.fifo' as the input file as per the instructions in the link.

    Alternatively you can try opening '/dev/stdin' in your program and reading the data from there; you could then pipe the PCAP data straight into stdin using the shell and skipping the intermediate named fifo.

    $ sudo tcpdump -s0 -i eth0 -f - tcp port 80 | ./youprogram.py