Added extract_int64_le_unsigned, version 0.8 for release.
[ocaml-bitstring.git] / examples / ipv4_header.ml
1 (* Parse and display an IPv4 header from a file.
2  * $Id: ipv4_header.ml,v 1.2 2008-04-01 17:31:12 rjones Exp $
3  *)
4
5 open Printf
6
7 let header = Bitmatch.bitstring_of_file "ipv4_header.dat"
8
9 let () =
10   bitmatch header with
11   | version : 4; hdrlen : 4; tos : 8; length : 16;
12     identification : 16; flags : 3; fragoffset : 13;
13     ttl : 8; protocol : 8; checksum : 16;
14     source : 32;
15     dest : 32;
16     options : (hdrlen-5)*32 : bitstring;
17     payload : -1 : bitstring
18       when version = 4 ->
19
20     printf "IPv%d:\n" version;
21     printf "  header length: %d * 32 bit words\n" hdrlen;
22     printf "  type of service: %d\n" tos;
23     printf "  packet length: %d bytes\n" length;
24     printf "  identification: %d\n" identification;
25     printf "  flags: %d\n" flags;
26     printf "  fragment offset: %d\n" fragoffset;
27     printf "  ttl: %d\n" ttl;
28     printf "  protocol: %d\n" protocol;
29     printf "  checksum: %d\n" checksum;
30     printf "  source: %lx  dest: %lx\n" source dest;
31     printf "  header options + padding:\n";
32     Bitmatch.hexdump_bitstring stdout options;
33     printf "  packet payload:\n";
34     Bitmatch.hexdump_bitstring stdout payload
35
36   | version : 4 ->
37     eprintf "cannot parse IP version %d\n" version
38
39   | _ as header ->
40     eprintf "data is smaller than one nibble:\n";
41     Bitmatch.hexdump_bitstring stderr header