Erlang Packet Parsing

Erlang is great for parsing network packets because of its strong binary pattern matching mechanisms. For example, using the epcap library, you can begin to parse packets in the following way1:


start() ->
  {ok, _Ref} = epcap:start_link([
    {monitor, true},
    {inteface, "en0"},
    {filter, "icmp"}

listen() ->
    {packet, _, _, _, Packet} ->

print_mac(<<Dst:48, Src:48, _/binary>>) ->
  DstFormat = format_mac(Dst),
  SrcFormat = format_mac(Src),
  io:fwrite("Destination: ~s~nSource ~s~n~n", [DstFormat, SrcFormat]).

format_mac(MacInt) ->
  MacList = [integer_to_list(X, 16) || <<X>> <= <<MacInt:48>>],
  string:join(MacList, ":").

Note that the actual parsing comes down to a very simple <<Dst:48, Src:48, _/binary>> = Packet. Six bytes each are matched and bound for the destination and source MAC address, then the rest is discarded. This is a minimal use of matching functionality, but you can imagine that this would be really powerful for more complex use cases.

  1. The epcap library actually has built-in packet parsing functionality, so this isn’t likely something you would do in a real environment.