msantos / epcap

Erlang packet capture interface using pcap
http://listincomprehension.com/2009/12/erlang-packet-sniffer-using-ei-and.html
BSD 3-Clause "New" or "Revised" License
178 stars 56 forks source link

Generate .pcap file #21

Closed mousavian closed 7 years ago

mousavian commented 7 years ago

Hi. Is there any possible way to dump packets that are captured using epcap to .pcap file? Preferably using epcap, otherwise I'll appreciate if you can give me any suggestion.

Regards

msantos commented 7 years ago

Not directly using epcap but there are a few libraries for writing files in the pcap format. Here is one I've used:

https://github.com/ates/pcapfile.git

-module(pdump).                                                                                                                                                                                                [0/0]
-export([                                                                       
        start/0, start/2                                                        
    ]).                                                                         

start() ->                                                                      
    start([{filter, "ip or ip6"}], 200).                                        

start(Filter, Count) ->                                                         
    {ok, Pid} = epcap:start(Filter),                                            
    {ok, FH} = pcapfile:open("dump.pcap", ethernet),                            
    dump(Count, Pid, FH).                                                       

dump(0, _Pid, FH) ->                                                            
    pcapfile:close(FH);                                                         
dump(Count, Pid, FH) ->                                                         
    receive                                                                     
        {packet, _DataLinkType, {MegaSecs, Secs, _}, _Length, Packet} ->        
            erlang:display(Packet),                                             
            Timestamp = MegaSecs * 1000000 + Secs,                              
            ok = pcapfile:write(FH, Timestamp, Packet),                         
            dump(Count-1, Pid, FH)                                              
    end.