Search code examples
pythonpacketpcapdpkt

Check if packet contains Ethernet layer or a Raw IP packet using DPKT python


I have a some pcap files that I need to extract some information from, those packets are mixed, some are Raw IP and others contains ethernet frames.

I need to conditionally check for the type of packet before parsing as the packets with ethernet frames could be parsed with:

for ts, buf in pkts:
    if buf contains_ethernet:
        eth = dpkt.ethernet.Ethernet(buf)
        if eth.type == dpkt.ethernet.ETH_TYPE_IP:
            ip = eth.data
        else:
            continue
    else:
        ip = dpkt.ip.IP(buf)

How can I define the contains_ethernet as a boolean or a condition?


Solution

  • The pcap header file defines the link type of the capture (Ethernet, Raw IP, ...)

    Before processing the packet, you shoud use datalink() of your dpkt.pcap.Reader() object to get the link type of your pcap file. According to your script example :

    if <<dpkt.pcap.Reader>>.datalink() == LINKTYPE_ETHERNET: ## Process Ethernet frame elif <<dpkt.pcap.Reader>>.datalink() == LINKTYPE_RAW: ## Processs Raw IP datagram else: ## Other link types

    Here is the list of link types : http://www.tcpdump.org/linktypes.html

    With values LINKTYPE_ETHERNET for Ethernet and LINKTYPE_RAW for Raw IP