1 # Copyright (C) 2013 Nippon Telegraph and Telephone Corporation.
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
26 class NetFlow(object):
28 _NETFLOW_VERSIONS = {}
31 def register_netflow_version(version):
32 def _register_netflow_version(cls):
33 NetFlow._NETFLOW_VERSIONS[version] = cls
35 return _register_netflow_version
38 super(NetFlow, self).__init__()
42 (version,) = struct.unpack_from(cls._PACK_STR, buf)
44 cls_ = cls._NETFLOW_VERSIONS.get(version, None)
46 return cls_.parser(buf)
51 @NetFlow.register_netflow_version(NETFLOW_V5)
52 class NetFlowV5(object):
53 _PACK_STR = '!HHIIIIBBH'
54 _MIN_LEN = struct.calcsize(_PACK_STR)
56 def __init__(self, version, count, sys_uptime, unix_secs,
57 unix_nsecs, flow_sequence, engine_type, engine_id,
58 sampling_interval, flows=None):
59 self.version = version
61 self.sys_uptime = sys_uptime
62 self.unix_secs = unix_secs
63 self.unix_nsecs = unix_nsecs
64 self.flow_sequence = flow_sequence
65 self.engine_type = engine_type
66 self.engine_id = engine_id
67 self.sampling_interval = sampling_interval
71 (version, count, sys_uptime, unix_secs, unix_nsecs,
72 flow_sequence, engine_type, engine_id, sampling_interval) = \
73 struct.unpack_from(cls._PACK_STR, buf)
75 msg = cls(version, count, sys_uptime, unix_secs, unix_nsecs,
76 flow_sequence, engine_type, engine_id,
80 while len(buf) > offset:
81 f = NetFlowV5Flow.parser(buf, offset)
82 offset += NetFlowV5Flow._MIN_LEN
88 class NetFlowV5Flow(object):
89 _PACK_STR = '!IIIHHIIIIHHxBBBHHBB2x'
90 _MIN_LEN = struct.calcsize(_PACK_STR)
92 def __init__(self, srcaddr, dstaddr, nexthop, input_, output,
93 dpkts, doctets, first, last, srcport, dstport,
94 tcp_flags, prot, tos, src_as, dst_as, src_mask,
96 self.srcaddr = srcaddr
97 self.dstaddr = dstaddr
98 self.nexthop = nexthop
102 self.doctets = doctets
105 self.srcport = srcport
106 self.dstport = dstport
107 self.tcp_flags = tcp_flags
112 self.src_mask = src_mask
113 self.dst_mask = dst_mask
116 def parser(cls, buf, offset):
117 (srcaddr, dstaddr, nexthop, input_, output, dpkts, doctets,
118 first, last, srcport, dstport, tcp_flags, prot, tos, src_as,
119 dst_as, src_mask, dst_mask) = struct.unpack_from(
120 cls._PACK_STR, buf, offset)
121 msg = cls(srcaddr, dstaddr, nexthop, input_, output, dpkts,
122 doctets, first, last, srcport, dstport, tcp_flags,
123 prot, tos, src_as, dst_as, src_mask, dst_mask)