Following are the steps to parse a packet:
- 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
- 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 ...