Skip to content

Instantly share code, notes, and snippets.

@jasl
Created November 29, 2012 06:03
Show Gist options
  • Save jasl/4167085 to your computer and use it in GitHub Desktop.
Save jasl/4167085 to your computer and use it in GitHub Desktop.
Parse Pcap file
require 'ipaddr'
def decode(p, m = "i*")
p.unpack(m)[0]
end
def parse_ip_p(data)
r = {}
if data[12..13] == "\x08\x00" and data[14] == "\x45" and data[23] == "\x11"
puts "find a IPV4 UDP package"
else
return nil
end
r[:source_ip] = IPAddr.new_ntoh data[26..29]
r[:target_ip] = IPAddr.new_ntoh data[30..33]
r[:source_port] = decode data[34..35], "n*"
r[:target_port] = decode data[36..37], "n*"
puts "source: #{r[:source_ip]}:#{r[:source_port]}"
puts "target: #{r[:target_ip]}:#{r[:target_port]}"
r
end
pcap = File.binread("1.pcap")
case decode(pcap[20..23])
when 1 then puts "Ethernet"
else puts "Unknown"; return;
end
packages = []
ignore_count = 0
p_l = decode(pcap[32..35])
p_d_s = 24
loop do
puts "package length: #{p_l}"
puts "package start at #{p_d_s}B"
if p = parse_ip_p(pcap[(p_d_s+16)..(p_d_s+16+p_l-1)])
packages<< p
else
ignore_count += 1
end
puts "================================="
p_d_s += p_l+16
break if p_d_s >= pcap.length
p_l = decode(pcap[p_d_s+8..p_d_s+12])
end
puts "total parsed #{packages.length} packages, skip #{ignore_count} packages."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment