#!/usr/bin/env ruby

require 'RubyLibtrace'

# 1925, Sun 6 Apr 08 (PDT)
# bpf-filter.rb: Create a packet filter, use it to configure an input trace
# Copyright (C) 2008, Nevil Brownlee, U Auckland | CAIDA | Wand

def s_to_hex(s,  offset)  # Print s as a hex dump
   os = "\n" + ''.rjust(offset)
   len = s.length
   o = '';  j = 0
   s.each_byte do |b|
      o << sprintf("%02x", b)
      j += 1
      if j != len
         o << ' ' if j%2 == 0
         o << ' ' if j%4 == 0
         o << os  if j%32 == 0
      end
   end
   o
end

f = Trace.new(ARGV[0])

filter = Filter.new('udp port 53')  # Only want DNS packets

pr = nil
fr = f.conf_filter(filter)
sr = f.conf_snaplen(500)
#pr = f.conf_promisc(false)
   # libtrace bug: conf_promisc only works for int:eth1 !!!
   #   doesn't work for pcapfile: or pcapint:
   # Remember: on a live interface, must sudo to capture
   #           on a trace file, can't set promicuous
print "filter=#{fr} snaplen=#{sr}, promisc=#{pr}\n\n"

f.start

nfp = 0
f.each_packet do |pkt|
   nfp += 1

   upp = pkt.udp_payload
   print "Filtered packet #{nfp}, " +
     "capture_len=#{pkt.capture_len}\n"
      print "data: #{s_to_hex(upp.data, 6)}\n\n"

   break if nfp == 4
end

