import struct,collections,ipaddress,datetime
path='/tmp/u443.pcap'
f=open(path,'rb'); gh=f.read(24)
if len(gh)<24: print('EMPTY'); raise SystemExit
end={b'\xd4\xc3\xb2\xa1':'<',b'\xa1\xb2\xc3\xd4':'>',b'\x4d\x3c\xb2\xa1':'<',b'\xa1\xb2\x3c\x4d':'>'}[gh[:4]]
link=struct.unpack(end+'I',gh[20:24])[0]
rows=collections.Counter(); times=[]
while True:
    ph=f.read(16)
    if len(ph)<16: break
    ts,_,incl,_=struct.unpack(end+'IIII',ph); d=f.read(incl)
    if len(d)<incl: break
    if link!=1: continue
    et=struct.unpack('>H',d[12:14])[0]; o=14
    if et==0x8100: et=struct.unpack('>H',d[16:18])[0]; o=18
    if et==0x0800:
        ihl=(d[o]&0xf)*4
        if d[o+9]!=17: continue
        src=str(ipaddress.IPv4Address(d[o+12:o+16])); dst=str(ipaddress.IPv4Address(d[o+16:o+20])); t=o+ihl
    elif et==0x86DD:
        if d[o+6]!=17: continue
        src=str(ipaddress.IPv6Address(d[o+8:o+24])); dst=str(ipaddress.IPv6Address(d[o+24:o+40])); t=o+40
    else: continue
    if len(d)<t+8: continue
    sp,dp,ul,cs=struct.unpack('>HHHH',d[t:t+8])
    pay=d[t+8:t+ul]
    times.append(ts)
    rows[(src,sp,dst,dp,len(pay),pay[:4].hex())]+=1
print('udp packets=%d' % sum(rows.values()))
for k,c in rows.most_common(40):
    src,sp,dst,dp,L,magic=k
    print('  %s:%d -> %s:%d len=%-4d head=%s x%d' % (src,sp,dst,dp,L,magic,c))
if times:
    print('  time span %s..%s UTC' % (datetime.datetime.utcfromtimestamp(min(times)).strftime('%H:%M:%S'),
                                      datetime.datetime.utcfromtimestamp(max(times)).strftime('%H:%M:%S')))
