lost and found ( for me ? )

Python dpkt : counts # of IPv4 UDP and TCP packets from a pcap file


Here’s a description of how to counts # of UDP , TCP packets from a pcap with python dpkt.

The logics are:
1. counts total # of packets
2. picks up IPv4 packets ( ethernet type is 2048 )
3. picks up UDP packets ( IP protcol number is 17 ) and counts
4. picks up TCP packets ( IP protcol number is 6 ) and counts
5. counts # of packets except for thertnet type 2048

# http://www.iana.org/assignments/ethernet-numbers
# http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xml

python script
root@hat1:~/python_works# less -N count_IPv4_UDP_TCP_packets.py
     1 #!/usr/bin/env python
     2
     3 import dpkt, sys
     4
     5 if len(sys.argv) < 2 or len(sys.argv) > 2:
     6         print "Usage:", sys.argv[0], "filename.pcap"
     7         sys.exit()
     8
     9 f = open(sys.argv[1])
    10 pcap = dpkt.pcap.Reader(f)
    11
    12 udp_packet = 0
    13 tcp_packet = 0
    14 other = 0
    15 total_packet = 0
    16
    17 for ts, buf in pcap:
    18         eth = dpkt.ethernet.Ethernet(buf)
    19 # counts total number of packets
    20         total_packet += 1
    21
    22 # picks up IPv4 packets
    23 # http://www.iana.org/assignments/ethernet-numbers
    24         if eth.type == 2048:
    25                 ip = eth.data
    26                 
    27 # picks up UDP packets
    28 # http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xml
    29                 if ip.p == 17:
    30                         udp_packet += 1
    31
    32 # picks up TCP packets
    33                 if ip.p == 6:
    34                         tcp_packet += 1
    35
    36 # picks up ether type except for 2048
    37         else:
    38                 other += 1
    39
    40 print "total # of packets: %s"  % (total_packet)
    41 print "# of UDP packets: %s" % (udp_packet)
    42 print "# of TCP packets: %s" % (tcp_packet)
    43 print "# of other packets except for TCP or UDP: %s"  % (other)

[ example usage ]

I prepared a pcap file containing 12 packets , 8 TCP packets and 4 UDP packets.
root@hat1:~/python_works# tshark -r zzz.pcap | wc -l
12

root@hat1:~/python_works# tshark -r zzz.pcap tcp | wc -l
8

root@hat1:~/python_works# tshark -r zzz.pcap udp | wc -l
4

root@hat1:~/python_works# ./count_IPv4_UDP_TCP_packets.py zzz.pcap
total # of packets: 12
# of UDP packets: 4
# of TCP packets: 8
# of other packets except for TCP or UDP: 0

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.