Skip to content

Instantly share code, notes, and snippets.

@mjseeley
Created November 6, 2014 21:07
Show Gist options
  • Save mjseeley/e8c235491277399d3078 to your computer and use it in GitHub Desktop.
Save mjseeley/e8c235491277399d3078 to your computer and use it in GitHub Desktop.
Simple dpkt example for processing (tcpdump)pcap files
import dpkt
import socket
# Function/arguments: get_rdns(ip)
# Description: Perform a reverse DNS query for the passed-in IP address.
# Returns: String: the reverse DNS name, or ''.
def get_rdns(ip):
try:
result = socket.gethostbyaddr(ip)[0]
except socket.herror:
# print 'Unable to get rDNS for', ip
result = ip
return result
f = open(r'C:\WIP\pcap_analyzer\test4.pcap', 'rb')
pcap = dpkt.pcap.Reader(f)
comms_list = []
for ts, buf in pcap:
# print ts, len(buf)
eth = dpkt.ethernet.Ethernet(buf)
# print repr(eth.data)
if isinstance(eth.data, dpkt.ip.IP):
eth_data = eth.data
# print repr(eth_data)
data_type = str(type(eth_data.data)).split('.',)[-1].replace("'>", '')
if data_type == 'ICMP':
pass
else:
src_ip = socket.inet_ntoa(eth_data.src)
src_port = str(eth_data.data.sport)
dst_ip = socket.inet_ntoa(eth_data.dst)
dst_port = str(eth_data.data.dport)
# print data_type
comm = '{0}-{1}({2}:{3}) --> {4}({5}:{6})'.format(data_type, get_rdns(src_ip), src_ip, src_port,
get_rdns(dst_ip), dst_ip, dst_port)
if comm not in comms_list:
comms_list.append(comm)
elif isinstance(eth.data, dpkt.stp.STP):
# print repr(eth.data)
pass
for i in comms_list:
print i
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment