Created
April 24, 2011 01:30
-
-
Save msantos/939215 to your computer and use it in GitHub Desktop.
Erlang BPF packet sniffer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| -module(dump). | |
| -export([start/0,start/2]). | |
| start() -> | |
| start("en1", []). | |
| start(Dev, Filter) when is_list(Dev), is_list(Filter) -> | |
| {ok, Socket, Length} = bpf:open(Dev), | |
| filter(Socket, Length, Filter). | |
| filter(Socket, Length, Filter) -> | |
| {ok, _} = bpf:ctl(Socket, setf, Filter), | |
| loop(Socket, Length, <<>>). | |
| loop(Socket, Length, <<>>) -> | |
| case procket:read(Socket, Length) of | |
| {ok, Packet} -> | |
| error_logger:info_report([{length, byte_size(Packet)}]), | |
| loop(Socket, Length, Packet); | |
| {error, eagain} -> | |
| timer:sleep(10), | |
| loop(Socket, Length, <<>>) | |
| end; | |
| loop(Socket, Length, Data) -> | |
| case bpf:buf(Data) of | |
| {bpf_buf, Time, Datalen, Packet, Rest} -> | |
| error_logger:info_report([ | |
| {time, timestamp(Time)}, | |
| {packet_is_truncated, Datalen /= byte_size(Packet)}, | |
| {packet, pkt:decapsulate(Packet)}, | |
| {packet_size, byte_size(Packet)}, | |
| {remaining, byte_size(Rest)} | |
| ]), | |
| loop(Socket, Length, Rest); | |
| Error -> | |
| Error | |
| end. | |
| timestamp(Now) when is_tuple(Now) -> | |
| iso_8601_fmt(calendar:now_to_local_time(Now)). | |
| iso_8601_fmt(DateTime) -> | |
| {{Year,Month,Day},{Hour,Min,Sec}} = DateTime, | |
| lists:flatten(io_lib:format("~4.10.0B-~2.10.0B-~2.10.0B ~2.10.0B:~2.10.0B:~2.10.0B", | |
| [Year, Month, Day, Hour, Min, Sec])). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment