1 # Copyright (C) 2012 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.
18 from . import packet_base
19 from . import packet_utils
26 class udp(packet_base.PacketBase):
27 """UDP (RFC 768) header encoder/decoder class.
29 An instance has the following attributes at least.
30 Most of them are same to the on-wire counterparts but in host byte order.
31 __init__ takes the corresponding args in this order.
33 ============== ====================
35 ============== ====================
37 dst_port Destination Port
39 (0 means automatically-calculate when encoding)
41 (0 means automatically-calculate when encoding)
42 ============== ====================
46 _MIN_LEN = struct.calcsize(_PACK_STR)
48 def __init__(self, src_port=1, dst_port=1, total_length=0, csum=0):
49 super(udp, self).__init__()
50 self.src_port = src_port
51 self.dst_port = dst_port
52 self.total_length = total_length
56 def get_packet_type(src_port, dst_port):
57 if ((src_port in [67, 68] and dst_port == 67) or
58 (dst_port in [67, 68] and src_port == 67)):
60 if ((src_port in [546, 547] and dst_port == 547) or
61 (dst_port in [546, 547] and src_port == 547)):
63 if (dst_port == vxlan.UDP_DST_PORT or
64 dst_port == vxlan.UDP_DST_PORT_OLD):
66 if dst_port == geneve.UDP_DST_PORT:
72 (src_port, dst_port, total_length, csum) = struct.unpack_from(
74 msg = cls(src_port, dst_port, total_length, csum)
75 return msg, cls.get_packet_type(src_port, dst_port), buf[msg._MIN_LEN:total_length]
77 def serialize(self, payload, prev):
78 if self.total_length == 0:
79 self.total_length = udp._MIN_LEN + len(payload)
80 h = struct.pack(udp._PACK_STR, self.src_port, self.dst_port,
81 self.total_length, self.csum)
83 self.csum = packet_utils.checksum_ip(
84 prev, self.total_length, h + payload)
85 h = struct.pack(udp._PACK_STR, self.src_port, self.dst_port,
86 self.total_length, self.csum)