summaryrefslogtreecommitdiff
path: root/external/construct/formats/data/cap.py
blob: f95c5c1c213fa14fdd4f6519bd500229a7f34791 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
"""
tcpdump capture file
"""
from construct import *
import time
from datetime import datetime


class MicrosecAdapter(Adapter):
    def _decode(self, obj, context):
        return datetime.fromtimestamp(obj[0] + (obj[1] / 1000000.0))
    def _encode(self, obj, context):
        offset = time.mktime(*obj.timetuple())
        sec = int(offset)
        usec = (offset - sec) * 1000000
        return (sec, usec)

packet = Struct("packet",
    MicrosecAdapter(
        Sequence("time", 
            ULInt32("time"),
            ULInt32("usec"),
        )
    ),
    ULInt32("length"),
    Padding(4),
    HexDumpAdapter(Field("data", lambda ctx: ctx.length)),
)

cap_file = Struct("cap_file",
    Padding(24),
    Rename("packets", OptionalGreedyRange(packet)),
)


if __name__ == "__main__":
    obj = cap_file.parse_stream(open("../../tests/cap2.cap", "rb"))
    print(len(obj.packets))