[erlang-questions] IP packet manipulation within Erlang

Hans Nilsson R <>
Thu Jan 7 11:42:50 CET 2010


Hi!

I think Erlang binary syntax makes it trivialy straightforward for 
handling e.g. IP packets.  The following example shows the technique.  
The argument to decode/1 is an Ethernet frame in a binary.  I used this 
for post-processing of a pcap-file so I have no idea of the speed in a 
"wireline" application, but it was surprisingly fast in my application.  
I guess that the new NIFs will make it faster than with the built-in driver.


decode(<<ED1:8, ED2:8, ED3:8, ED4:8, ED5:8, ED6:8,
        ES1:8, ES2:8, ES3:8, ES4:8, ES5:8, ES6:8,
        EtherType:16,             
        Pkt/binary>> ) ->
    #ethernet{dst  = {ED1, ED2, ED3, ED4, ED5, ED6},
              src  = {ES1, ES2, ES3, ES4, ES5, ES6},
              type = EtherType,
              data = dec_pkt(EtherType,Pkt)}.

dec_pkt(2048, %% IPv4
        <<Version:4,HdrLen:4, TOS:8, TotLen:16,
         ID:16, Flg:3, FragmentOffset:13,
         TTL:8, Protocol:8, HdrChkSum:16,
         IPsrc1:8, IPsrc2:8, IPsrc3:8, IPsrc4:8,
         IPdst1:8, IPdst2:8, IPdst3:8, IPdst4:8,
         Data/binary>>) ->
    OptLen = HdrLen*4 - 20,
    <<Options:OptLen/binary, PayLoad/binary>> = Data,

    #ipv4{version = Version,
          hdr_length = HdrLen,
          tos = TOS,
          length = TotLen,
          id = ID,
          flags = Flg,
          fragment_offset = FragmentOffset,
          ttl = TTL,
          protocol = Protocol,
          checksum = HdrChkSum,
          src_ip = {IPsrc1, IPsrc2, IPsrc3, IPsrc4},
          dst_ip = {IPdst1, IPdst2, IPdst3, IPdst4},
          options = Options,
          data = case FragmentOffset of
                     0 -> dec_ipv4(Protocol,PayLoad);
                     _ -> PayLoad
                 end
         };

dec_pkt(EtherType,X) -> {'??',EtherType,X}.
   
... and so on for #udp, #tcp, #sctp .....

/Hans


Chandru skrev:
> 2010/1/7 Martti Kuparinen <>
>
>   
>> Hi,
>>
>> How suitable is Erlang for a small project where I'd like to
>>
>> - grab all incoming IP packets
>> - perform some IP header manipulation
>> - send out the modified packets
>>
>> I'm aware I need some kind of bpf/pcap driver to get the packets into
>> Erlang (or does Erlang now have something in this front).
>>
>> Do you guys have any idea how fast this whole thing would be compared to
>> doing same in normal userland C program? Or even compared to doing the
>> manipulation within Linux kernel.
>>
>>     
>
> I attempted this a few years ago. I tried to write a linked in driver which
> got packets from libipq [1]. That was painful. So I dumped the idea of using
> erlang at all, and did it all in C which was pretty straightforward and
> worked quite well. I didn't put any large load on it, but it was enough for
> what I was doing at the time.
>
> cheers
> Chandru
>
> [1] http://en.wikipedia.org/wiki/Libipq
>
>   



More information about the erlang-questions mailing list