#!/usr/bin/env ruby

require 'RubyLibtrace'

# 1925, Sat 1 Nov 08 (NZDT)
# ICMP.rb: Demonstrate ICMP header decodes
# Copyright (C) 2008, Nevil Brownlee, U Auckland | CAIDA | WAND

def print_icmp(n, icmp)  # IPv4 only  (IPv6 uses ICMP6 protocol)
   print "ICMP packet #{n}: type=#{icmp.type}, code=#{icmp.code};" +
      "  #{icmp.src_prefix} -> #{icmp.dst_prefix}\n   "
#   printf("checksum=%04x\n", icmp.checksum)
   case icmp.type
   when 0, 8  # Echo Reply, Echo Request
      idh = sprintf("%04x", icmp.echo.ident)
      sqh = sprintf("%04x", icmp.echo.sequence)
      kind = icmp.type == 0 ? 'reply' : 'request'
      print "echo #{kind}; id=#{idh}, seq=#{sqh}"
   when 3  # Destination Unreachable
      print "destination unreachable, IP length=#{icmp.unreachable.length}"
   when 5  # Redirect
      print "redirect; gateway=#{icmp.redirect.gateway}"
   when 11  # 
      print "time-to-live exceeded"
   else
     print "[no further detail]"
   end
   print ";  time=#{icmp.time}\n"
end

f = Trace.new(ARGV[0])
f.start

n = 0;  nn = 0

f.each_packet do |pkt|
   n += 1

   icmp = pkt.icmp
   next if !icmp
   print_icmp(nn, icmp)

   nn += 1
#   break if nn == 2
end

