#!/usr/bin/env python3 """Count IPv4 TCP/UDP DSCP per destination port in capture.py PCAP (stdlib).""" import argparse import collections import json import socket import struct def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('pcap') args = parser.parse_args() counts = collections.Counter() with open(args.pcap, 'rb') as source: header = source.read(24) if len(header) != 24 or struct.unpack(' 65535: parser.error('invalid captured length') frame = source.read(size) if len(frame) != size: parser.error('truncated frame') if size < 34 or frame[12:14] != b'\x08\x00' or frame[14] >> 4 != 4: continue ihl = (frame[14] & 15) * 4 protocol = frame[23] fragment_offset = struct.unpack('!H', frame[20:22])[0] & 0x1fff if ihl < 20 or size < 14+ihl+4 or protocol not in (6, 17) or fragment_offset: continue destination_port = struct.unpack('!H', frame[14+ihl+2:14+ihl+4])[0] key = (socket.inet_ntoa(frame[26:30]), socket.inet_ntoa(frame[30:34]), 'TCP' if protocol == 6 else 'UDP', destination_port, frame[15] >> 2) counts[key] += 1 print(json.dumps([dict(zip(('source', 'destination', 'protocol', 'destination_port', 'dscp'), key), packets=count) for key, count in sorted(counts.items())], indent=2)) if __name__ == '__main__': main()