The PCAP library is the de-facto packet-capture library used by most applications that need packet capture in some form or the other. There exists a OCaml PCAP library (libmlpcap-ocaml-dev or mlpcap) which basically consists of FFI bindings for all the PCAP functions. The usual documentation (such as here) for the PCAP API should also apply to the OCaml bindings for PCAP.
However, if you get the libmlpcap-ocaml-dev package from Synaptic (or other package manager based upon your OS) you maybe be puzzled about how to compile simple PCAP programs. The full list of c library (-cclib) dependencies was hard to find listed anywhere. This stumped me for a while since there was no documentation to be found about how to build a sample program (I would love to be corrected about this). Hence I thought I should put out my own.
This is what you have to do to write your own OCaml PCAP code. These instruction should apply even if you installed libmlpcap through godi or some other means. Consider the trivial PCAP program that prints “packet!” every time a packet goes through your network:
open Printf open Pcap let dev = "eth1" let bufsize = 64*1024 let callback _args _pkthdr _pktstr = printf "packet!" let main () = let h = pcap_open_live dev bufsize 1 100 in let _num = pcap_loop h 500 callback "" in pcap_close h ;; main ();
To compile this program with ocamlfind and ocamlopt you need to do the following:
ocamlfind ocamlopt -package pcap \ -cclib -lpcap -cclib -lpcap_stubs \ -cclib -lcallback -cclib -lcamlidl \ -o net.opt net.ml -linkpkg
Or, equivalently for ocamlc:
ocamlfind ocamlc -package pcap \ -cclib -lpcap -cclib -lpcap_stubs \ -cclib -lcallback -cclib -lcamlidl \ -o net net.ml -linkpkg
You can can always put this into a build system of your choice, such as make or omake. Enjoy!