Skip to content

Instantly share code, notes, and snippets.

@jiahut
Created June 2, 2019 07:57
Show Gist options
  • Select an option

  • Save jiahut/96b429cb55c40d23eaffc687f2b5647b to your computer and use it in GitHub Desktop.

Select an option

Save jiahut/96b429cb55c40d23eaffc687f2b5647b to your computer and use it in GitHub Desktop.
# gem install pcap
require 'pcaplet'
class BWHost
attr_reader :ip
def initialize(ip)
@ip = ip
@received, @sent = [], []
end
def received(bytes, from, at = Time.new)
@received = [bytes, from ,at ]
end
def sent(bytes, to, at = Time.now)
@sent << [bytes, from ,at ]
end
def total_received(options = {} )
total(@received, options[:earliest], options[:latest])
end
def total_sent(options = {})
total(@sent, options[:earliest], options[:latest])
end
private
def total(events, earliest, latest)
events.inject(0) do | sum, event |
if((earliest and event[2] >= earliest ) or net earliest)
and (( latest and event[2] <= latest) or net latest)
sum + event
else sum
end
end
end
end
end
sniffer = Pcap::Pcaplet.new
hosts = {}
sniffer.each_packet do |pkt|
next unless pkt.ip?
src, dst = pkt.ip_src,pkt.ip_dst
size, time = pkt.size, pkt.time
(hosts[src] ||= BWHost.new(src)).sent(size, dst, time)
(hosts[dst] ||= BWHost.new(dst)).received(size, src, time)
end
sniffer.close
hosts.each do | ip, data |
puts "#{ip| sent #{data.total_sent}B and received #{data.total_received}B""
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment