-
-
Save vpereira/2079339e8a0874de5a44 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'java' | |
require 'jnetpcap.jar' | |
require 'ipaddr' | |
require 'json' | |
class PacketHandler | |
include Java::org::jnetpcap::packet::PcapPacketHandler | |
def initialize | |
@tcp_header = Java::org::jnetpcap::protocol::tcpip::Tcp.new | |
@ip_header = Java::org::jnetpcap::protocol::network::Ip4.new | |
end | |
def nextPacket(packet,user) | |
pkt_info = my_decode packet | |
if pkt_info | |
if use? pkt_info | |
puts pkt_info.to_json | |
if false | |
puts "#{pkt_info[:source_address]} #{pkt_info[:source_port]} => #{pkt_info[:destination_address]} #{pkt_info[:destination_port]} seq #{pkt_info[:seq]} payload size #{pkt_info[:payload].length}" | |
end | |
end | |
end | |
end | |
def my_decode(packet) | |
info = nil | |
if packet.hasHeader @tcp_header | |
if packet.hasHeader @ip_header | |
info = {} | |
info[:source_address] = addressToString @ip_header.sourceToInt | |
info[:source_port] = @tcp_header.source | |
info[:destination_address] = addressToString @ip_header.destinationToInt | |
info[:destination_port] = @tcp_header.destination | |
info[:seq] = @tcp_header.seq | |
payload = @tcp_header.getPayload | |
info[:payload] = payload.to_a | |
info[:payload_chars] = info[:payload].map { |x| ((x >= 0) && (x < 127)) ? x.chr : '.' } | |
end | |
end | |
info | |
end | |
def addressToString(addr) | |
b1 = addr & 255 | |
b2 = (addr >> 8) & 255 | |
b3 = (addr >> 16) & 255 | |
b4 = (addr >> 24) & 255 | |
"#{b4}.#{b3}.#{b2}.#{b1}" | |
end | |
def use?(pkt_info) | |
use_it = false | |
if pkt_info[:payload].length > 0 | |
if (pkt_info[:source_address] == '192.168.100.1') && (pkt_info[:source_port] == 9999) | |
use_it = true | |
elsif (pkt_info[:destination_address] == '192.168.100.1') && (pkt_info[:destination_port] == 9999) | |
use_it = true | |
end | |
end | |
use_it | |
end | |
end | |
my_handler = PacketHandler.new | |
devices = [] | |
errs = java.lang.StringBuilder.new | |
pcap = Java::org::jnetpcap::Pcap | |
r = pcap.findAllDevs devices,errs | |
my_dev = devices[2] | |
if false | |
puts "my_dev #{my_dev.getName} #{my_dev.getAddresses}" | |
end | |
pcap_live = pcap.openLive my_dev.getName, (64 * 1024), Java::org::jnetpcap::Pcap::MODE_PROMISCUOUS, (30 * 1000), errs | |
pcap_live.loop -1, my_handler, 'JRuby Rocks' | |
pcap_live.close |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment