Class: Pcap::Pcaplet
- Inherits:
-
Object
- Object
- Pcap::Pcaplet
- Defined in:
- lib/pcaplet.rb
Instance Attribute Summary collapse
-
#capture ⇒ Object
readonly
Returns the value of attribute capture.
Instance Method Summary collapse
- #add_filter(f) ⇒ Object
- #close ⇒ Object
- #each_packet(&block) ⇒ Object (also: #each)
-
#initialize(args = nil) ⇒ Pcaplet
constructor
A new instance of Pcaplet.
- #usage(status, msg = nil) ⇒ Object
Constructor Details
#initialize(args = nil) ⇒ Pcaplet
Returns a new instance of Pcaplet.
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
# File 'lib/pcaplet.rb', line 23 def initialize(args = nil) if args ARGV[0,0] = args.split(/\s+/) end usage(1) unless getopts("dnv", "i:", "r:", "c:-1", "s:68") $DEBUG |= $OPT_d $VERBOSE |= $OPT_v @device = $OPT_i @rfile = $OPT_r Pcap.convert = !$OPT_n @count = $OPT_c.to_i @snaplen = $OPT_s.to_i @filter = ARGV.join(' ') # check option consistency usage(1) if @device && @rfile if !@device and !@rfile @device = Pcap.lookupdev end # open begin if @device @capture = Capture.open_live(@device, @snaplen) elsif @rfile if @rfile !~ /\.gz$/ @capture = Capture.open_offline(@rfile) else $stdin = IO.popen("gzip -dc < #@rfile", 'r') @capture = Capture.open_offline('-') end end @capture.setfilter(@filter) rescue PcapError, ArgumentError $stdout.flush $stderr.puts $! exit(1) end end |
Instance Attribute Details
#capture ⇒ Object (readonly)
Returns the value of attribute capture.
64 65 66 |
# File 'lib/pcaplet.rb', line 64 def capture @capture end |
Instance Method Details
#add_filter(f) ⇒ Object
66 67 68 69 70 71 72 73 74 |
# File 'lib/pcaplet.rb', line 66 def add_filter(f) if @filter == nil || @filter =~ /^\s*$/ # if empty @filter = f else f = f.source if f.is_a? Filter @filter = "( #{@filter} ) and ( #{f} )" end @capture.setfilter(@filter) end |
#close ⇒ Object
107 108 109 |
# File 'lib/pcaplet.rb', line 107 def close @capture.close end |
#each_packet(&block) ⇒ Object Also known as: each
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 |
# File 'lib/pcaplet.rb', line 76 def each_packet(&block) begin duplicated = (RUBY_PLATFORM =~ /linux/ && @device == "lo") unless duplicated @capture.loop(@count, &block) else flip = true @capture.loop(@count) do |pkt| flip = (! flip) next if flip block.call pkt end end rescue Interrupt $stdout.flush $stderr.puts("Interrupted.") $stderr.puts $@.join("\n\t") if $DEBUG ensure # print statistics if live if @device stat = @capture.stats if stat $stderr.print("#{stat.recv} packets received by filter\n"); $stderr.print("#{stat.drop} packets dropped by kernel\n"); end end end end |
#usage(status, msg = nil) ⇒ Object
17 18 19 20 21 |
# File 'lib/pcaplet.rb', line 17 def usage(status, msg = nil) $stderr.puts msg if msg pcaplet_usage exit(status) end |