Friday, June 4, 2010

Fun with Raw Sockets in Erlang: Decoding Packets

Reading from the network using PF_PACKET will return the packets as binary data.

Parsing the packet is easy to do using Erlang's pattern matching. epcap has some functions to convert the binaries into records. We can use the same functions to decapsulate packets returned from procket.

For example, here is the output from a ping:
=INFO REPORT==== 4-Jun-2010::12:50:55 ===
    source_macaddr: "0:15:AF:xx:xx:xx"
    source_address: {192,168,213,213}
    source_port: []
    destination_macaddr: "0:16:B6:xx:xx:xx"
    destination_address: {67,195,160,76}
    destination_port: []
    protocol: icmp
    protocol_header: [{type,8},{code,0}]
    payload_bytes: 56
    payload: "...L............................ !\"#$%&'()*+,-./01234567"
The code is a modified version of sniff that is distributed with epcap. To compile the code, you'll need a copy of epcap_net.hrl and to run it, both the procket and epcap beam files will have to be in your path. Using the "-pa" option, something like:
erl -pa /path/to/procket/ebin -pa /patch/to/epcap/ebin

No comments:

Post a Comment