How to use the dpkt.ethernet.Ethernet function in dpkt

To help you get started, we’ve selected a few dpkt examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mike01 / pypacker / tests / perftest_pypacker_dpkt_scapy.py View on Github external
# dpkt does not parse TCP content but pypacker does
		# -> access layer ip to get comparable result
		pkt2 = pkt1.upper_layer
		bts = pkt2.body_bytes
	t_end = time.time()

	print("nr = %d p/s" % (LOOP_CNT / (t_end - t_start)))
	print("orC = 12527 p/s")
	print("orP =  p/s")
except Exception as ex:
	print("Could not execute pypacker tests: %r" % ex)

try:
	import dpkt
	print(">>> testing dpkt parsing speed")
	EthernetDpkt = dpkt.ethernet.Ethernet

	t_start = time.time()

	for cnt in range(LOOP_CNT):
		pkt1 = EthernetDpkt(pkt_eth_ip_tcp_bts)
		pkt2 = pkt1.ip
		bts = pkt2.data
	t_end = time.time()

	print("nr = %d p/s" % (LOOP_CNT / (t_end - t_start)))
	print("orC = 12028 p/s")
	print("orP =  p/s")
except Exception as ex:
	print("Could not execute dpkt tests: %r" % ex)

try:
github RadionBik / ML-based-network-traffic-classifier / py / pcaptocsv.py View on Github external
f.writelines("%s %s %s %s %s %s\n" % captures)
        
        transp_proto, ip1, port1, ip2, port2, app_proto = captures
        ip1 = ip_from_string(ip1)
        ip2 = ip_from_string(ip2)
        port1 = int(port1)
        port2 = int(port2)
        key = (transp_proto.lower(),frozenset(((ip1, port1), (ip2, port2))))
        flows[key] = []
        apps[key] = app_proto.split(".")
        if len(apps[key]) == 1:
            apps[key].append(None)
    f.close()

    for ts, raw in dpkt.pcap.Reader(open(pcapfile, "rb")):
        eth = dpkt.ethernet.Ethernet(raw)
        ip = eth.data
        #check if the packet is IP, TCP, UDP
        if not isinstance(ip, dpkt.ip.IP):
            continue
        seg = ip.data
        if isinstance(seg, dpkt.tcp.TCP):
            transp_proto = "tcp"
        elif isinstance(seg, dpkt.udp.UDP):
            transp_proto = "udp"
        else:
            continue

        key = (transp_proto, frozenset(((ip.src, seg.sport),(ip.dst, seg.dport))))
        try:
            assert key in flows
        except AssertionError:
github codepr / creak / plugins / recon / arpmap.py View on Github external
if not 'target' in kwargs:
            kwargs['target'] = kwargs['localip']

        subnet = kwargs['target'].split('.')[:-1]
        subnet = '.'.join(subnet)
        target = subnet
        counter = 0

        print('')
        self.print_output('Waiting for responses, enter \'q\' to stop')
        self.print_output('Alive hosts:')
        print(' ====================\n')
        for _ in xrange(attempts):
            for idx in xrange(1, 255):
                arp = dpkt.arp.ARP()
                packet = dpkt.ethernet.Ethernet()
                arp.sha = utils.string_to_binary(utils.parse_mac(kwargs['mac_addr']))
                arp.spa = inet_aton(kwargs['localip'])
                arp.tha = '\x00'
                arp.tpa = inet_aton(target + '.%s' % idx)
                arp.op = dpkt.arp.ARP_OP_REQUEST
                packet.src = utils.string_to_binary(utils.parse_mac(kwargs['mac_addr']))
                packet.dst = '\xff' * 6 # broadcast address
                packet.data = arp
                packet.type = dpkt.ethernet.ETH_TYPE_ARP
                sock.send(str(packet))

        def wait_responses(packets):
            hosts = []
            for _, pkt in packets:
                eth = dpkt.ethernet.Ethernet(pkt)
                ip_packet = eth.data
github h1kari / des_kpt / des_kpt / readers / KerbPacketReader.py View on Github external
def _parseForTargetPacket(self, timestamp, data):
        eth_packet = dpkt.ethernet.Ethernet(data)

        if isinstance(eth_packet.data, dpkt.ip.IP):
            ip_packet = eth_packet.data

            # check to see if packet is an AS-REP or TGS-REP
            asn_data = None
            test_rep = False
            test_req = False
            if ip_packet.get_proto(ip_packet.p) == dpkt.tcp.TCP and hasattr(ip_packet.data, 'data'):
                tcp_packet = ip_packet.data
                asn_data = tcp_packet.data[4:]

                if tcp_packet.sport == 88:
                    test_rep = True
                elif tcp_packet.dport == 88:
                    test_req = True
github cisco-system-traffic-generator / trex-core / scripts / automation / trex_control_plane / interactive / trex / astf / cap_handling.py View on Github external
l4_type = None
            last_time=None;
            index =0 ;
            for (time,buf) in pcap:
                dtime= time
                pkt_time=0.0; # time from last pkt
                if last_time == None:
                    pkt_time = 0.0;
                else:
                    pkt_time=dtime-last_time;
                last_time = dtime
    
                pkt_num += 1

                eth = dpkt.ethernet.Ethernet(buf)

                l3 = None;
                next = eth.data;

                if isinstance(next, dpkt.ip.IP):
                    l3 = next;

                if isinstance(next, dpkt.ip6.IP6):
                    l3 = next;

                if not l3:
                    self.fail('Packet #%s in pcap is not IPv4 or IPv6!' % index)
    
    
                # first packet
                if self.c_ip is None:
github codepr / creak / plugins / mitm / sniff.py View on Github external
' {:<3} {:<5}'.format(ipv, L1.hl, L1.ttl,
                                        inet_ntoa(L1.src),
                                        'd_addr:',
                                        inet_ntoa(L1.dst),
                                        's_port:',
                                        str(L2.sport),
                                        'd_port:',
                                        str(L2.dport)))

        packets = pcap.pcap(name=kwargs['dev'], promisc=True)
        if 'pcap_filter' in kwargs:
            packets.setfilter(kwargs['pcap_filter'])

        # can be refactored and optimized
        for _, pkt in packets:
            L0 = dpkt.ethernet.Ethernet(pkt)
            L1 = L0.data
            L2 = L1.data
            if L0.type == dpkt.ethernet.ETH_TYPE_ARP:
                op_flag = 'request'
                if L1.op == 2:
                    op_flag = 'reply'

                print(' [ARP] op: {:<8} s_h_addr: {:<8} d_h_addr: {:<8}'
                      ' s_p_addr: {:<8} d_p_addr: {:<8}'.format(op_flag,
                                                               utils.binary_to_string(L1.sha),
                                                               utils.binary_to_string(L1.tha),
                                                               inet_ntoa(L1.spa),
                                                               inet_ntoa(L1.tpa)))
            elif L0.type == dpkt.ethernet.ETH_TYPE_IP:
                ipv = 'IPv4'
                # IPv4 - TCP packet
github zayfod / pycozmo / tools / pycozmo_replay.py View on Github external
def load_engine_pkts(fspec):
    pkts = []

    frame_count = 1
    with open(fspec, "rb") as f:
        first_ts = None
        for ts, frame in dpkt.pcap.Reader(f):
            if first_ts is None:
                first_ts = ts
            eth = dpkt.ethernet.Ethernet(frame)
            if eth.type != dpkt.ethernet.ETH_TYPE_IP:
                # Skip non-IP frames
                continue
            ip = eth.data
            if ip.p != dpkt.ip.IP_PROTO_UDP:
                # Skip non-UDP frames
                continue
            udp = ip.data
            if udp.data[:7] != pycozmo.protocol_declaration.FRAME_ID:
                # Skip non-Cozmo frames
                continue
            frame = pycozmo.Frame.from_bytes(udp.data)
            if frame.type not in [pycozmo.protocol_declaration.FrameType.ENGINE]:
                # Skip non-engine frames
                continue
            for pkt in frame.pkts:
github kbandla / dpkt / examples / print_packets.py View on Github external
def print_packets(pcap):
    """Print out information about each packet in a pcap

       Args:
           pcap: dpkt pcap reader object (dpkt.pcap.Reader)
    """
    # For each packet in the pcap process the contents
    for timestamp, buf in pcap:

        # Print out the timestamp in UTC
        print('Timestamp: ', str(datetime.datetime.utcfromtimestamp(timestamp)))

        # Unpack the Ethernet frame (mac src/dst, ethertype)
        eth = dpkt.ethernet.Ethernet(buf)
        print('Ethernet Frame: ', mac_addr(eth.src), mac_addr(eth.dst), eth.type)

        # Make sure the Ethernet data contains an IP packet
        if not isinstance(eth.data, dpkt.ip.IP):
            print('Non IP Packet type not supported %s\n' % eth.data.__class__.__name__)
            continue

        # Now unpack the data within the Ethernet frame (the IP packet)
        # Pulling out src, dst, length, fragment info, TTL, and Protocol
        ip = eth.data

        # Pull out fragment information (flags and offset all packed into off field, so use bitmasks)
        do_not_fragment = bool(ip.off & dpkt.ip.IP_DF)
        more_fragments = bool(ip.off & dpkt.ip.IP_MF)
        fragment_offset = ip.off & dpkt.ip.IP_OFFMASK
github kbandla / dpkt / dpkt / ethernet.py View on Github external
def test_eth_pppoe():   # Eth - PPPoE - IPv6 - UDP - DHCP6
    from . import ip  # IPv6 needs this to build its protocol stack
    from . import ip6
    from . import ppp
    from . import pppoe
    from . import udp
    s = (b'\xca\x01\x0e\x88\x00\x06\xcc\x05\x0e\x88\x00\x00\x88\x64\x11\x00\x00\x11\x00\x64\x57\x6e'
         b'\x00\x00\x00\x00\x3a\x11\xff\xfe\x80\x00\x00\x00\x00\x00\x00\xce\x05\x0e\xff\xfe\x88\x00'
         b'\x00\xff\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x02\x02\x22\x02\x23\x00'
         b'\x3a\x1a\x67\x01\xfc\x24\xab\x00\x08\x00\x02\x05\xe9\x00\x01\x00\x0a\x00\x03\x00\x01\xcc'
         b'\x05\x0e\x88\x00\x00\x00\x06\x00\x06\x00\x19\x00\x17\x00\x18\x00\x19\x00\x0c\x00\x09\x00'
         b'\x01\x00\x00\x00\x00\x00\x00\x00\x00')
    eth = Ethernet(s)

    # stack
    assert isinstance(eth.data, pppoe.PPPoE)
    assert isinstance(eth.data.data, ppp.PPP)
    assert isinstance(eth.data.data.data, ip6.IP6)
    assert isinstance(eth.data.data.data.data, udp.UDP)

    # construction
    assert str(eth) == str(s)
    assert len(eth) == len(s)
github cuckoosandbox / cuckoo / cuckoo / processing / network.py View on Github external
def iplayer_from_raw(raw, linktype=1):
    """Converts a raw packet to a dpkt packet regarding of link type.
    @param raw: raw packet
    @param linktype: integer describing link type as expected by dpkt
    """
    if linktype == 1:  # ethernet
        try:
            pkt = dpkt.ethernet.Ethernet(raw)
            return pkt.data
        except dpkt.NeedData:
            pass
    elif linktype == 101:  # raw
        return dpkt.ip.IP(raw)
    else:
        raise CuckooProcessingError("unknown PCAP linktype")