September 2018
Intermediate to advanced
426 pages
10h 46m
English
In the following example, we are capturing packets in a specific device(eth0), and for each packet we obtain the header and payload for extracting information about Mac addresses, IP headers, and protocol.
You can find the following code in the reading_headers.py file:
#!/usr/bin/pythonimport pcapyfrom struct import *cap = pcapy.open_live("eth0", 65536, 1, 0)while 1: (header,payload) = cap.next() l2hdr = payload[:14] l2data = unpack("!6s6sH", l2hdr) srcmac = "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" % (ord(l2hdr[0]), ord(l2hdr[1]), ord(l2hdr[2]), ord(l2hdr[3]), ord(l2hdr[4]), ord(l2hdr[5])) dstmac = "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" % (ord(l2hdr[6]), ord(l2hdr[7]), ord(l2hdr[8]), ord(l2hdr[9]), ord(l2hdr[10]), ord(l2hdr[11])) ...