Beej's Guide to Network Programming in OCaml: showip.ml

Posted on Apr 28, 2025

I’m reading Beej’s Guide to Network Programming and porting the examples to OCaml for fun.

The first example is showip.ml (adapted from showip.c) from Section 5.1. This program takes a hostname as command-line argument, and prints the list of addresses suitable for communicating with that host as per getaddrinfo:

let () =
  match Sys.argv with
  | [| _; hostname |] ->
      let addr_infos =
        let service = "" in
        let opts = Unix.[ AI_SOCKTYPE SOCK_STREAM ] in
        Unix.getaddrinfo hostname service opts
      in
      Printf.printf "IP addresses for %s:\n\n" hostname;
      List.iter
        (fun (addr_info : Unix.addr_info) ->
          let ipver =
            match addr_info.ai_family with
            | PF_UNIX -> "unix"
            | PF_INET -> "ipv4"
            | PF_INET6 -> "ipv6"
          in
          let ipstr =
            match addr_info.ai_addr with
            | ADDR_UNIX s -> s
            | ADDR_INET (addr, _port) -> Unix.string_of_inet_addr addr
          in
          Printf.printf "  - %s: %s\n" ipver ipstr)
        addr_infos
  | _ -> Printf.eprintf "Usage: %s <hostname>\n" Sys.argv.(0)

The translation is straightforward – most of the work is finding the correct functions in OCaml’s Unix module.

To compile and run it:

$ ocamlfind opt -linkpkg -package unix -o showip showip.ml
$ ./showip example.com
IP addresses for example.com:

  - ipv4: 23.192.228.84
  - ipv4: 23.215.0.138
  - ipv4: 23.192.228.80
  - ipv4: 96.7.128.175
  - ipv4: 96.7.128.198
  - ipv4: 23.215.0.136
  - ipv6: 2600:1406:bc00:53::b81e:94c8
  - ipv6: 2600:1406:3a00:21::173e:2e65
  - ipv6: 2600:1406:3a00:21::173e:2e66
  - ipv6: 2600:1408:ec00:36::1736:7f31
  - ipv6: 2600:1408:ec00:36::1736:7f24
  - ipv6: 2600:1406:bc00:53::b81e:94ce