Bitmatch syntax extension, working on bits and bitstrings.
[ocaml-bitstring.git] / examples / make_ipv4_header.ml
1 (* Create an IPv4 header.
2  * $Id: make_ipv4_header.ml,v 1.1 2008-03-31 22:52:17 rjones Exp $
3  *)
4
5 open Printf
6
7 let version = 4
8 let hdrlen = 5                          (* no options *)
9 let tos = 16
10 let length = 64                         (* total packet length *)
11 let identification = 0
12 let flags = 0
13 let fragoffset = 0
14 let ttl = 255
15 let protocol = 17                       (* UDP *)
16 let checksum = 0
17 let source = 0xc0a80202                 (* 192.168.2.2 *)
18 let dest = 0xc0a80201                   (* 192.168.2.1 *)
19 let options = Bitmatch.empty_bitstring
20 let payload_length = (length - hdrlen*4) * 8
21 let payload = Bitmatch.create_bitstring payload_length
22
23 let header =
24   <| version : 4; hdrlen : 4; tos : 8; length : 16;
25      identification : 16; flags : 3; fragoffset : 13;
26      ttl : 8; protocol : 8; checksum : 16;
27      source : 32;
28      dest : 32;
29      options : -1, bitstring;
30      payload : payload_length, bitstring |>
31
32 (*
33   generates:
34
35   let header = Bitmatch.join_bitstrings [
36     Bitmatch.create_unsigned_be version 4;
37     Bitmatch.create_unsigned_be hdrlen 4; (* etc. *)
38     options;
39     Bitmatch.check_bitstring_length payload payload_length
40   ]
41
42   which can throw an exception if values are out of range.
43 *)
44
45 let () = Bitmatch.file_of_bitstring header "ipv4_header_out.dat"