How to do it...

Following are the steps to parse a packet:

  1. Create a new file called basic-parse-packet-packet-linux.py and import the modules required to parse the packets:
from struct import * 
import sys 
  1. Now we can create a function to parse the Ethernet header:
def ethernet_head(raw_data): 
    dest, src, prototype = struct.unpack('! 6s 6s H', raw_data[:14])  
    dest_mac = get_mac_addr(dest) 
    src_mac = get_mac_addr(src) 
    proto = socket.htons(prototype) 
    data = raw_data[14:] 
    return dest_mac, src_mac, proto, data  

Here we use the unpack method in the struct module to unpack the headers. From the Ethernet frame structure, the first six bytes are for the destination MAC, the second 6 bytes are for the source MAC, and the last unsigned short is for ...

Get Python Penetration Testing Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.