8 Ryu packet library helps you to parse and build various protocol
9 packets. dpkt is the popular library for the same purpose, however it
10 is not designed to handle protocols that are interleaved; vlan, mpls,
11 gre, etc. So we implemented our own packet library.
16 Unless otherwise specified, MAC/IPv4/IPv6 addresses are specified
17 using human readable strings for this library.
18 For example, '08:60:6e:7f:74:e7', '192.0.2.1', 'fe80::a60:6eff:fe7f:74e7'.
23 First, let's look at how we can use the library to parse the received
24 packets in a handler for OFPPacketIn messages.
26 .. code-block:: python
28 from ryu.lib.packet import packet
30 @handler.set_ev_cls(ofp_event.EventOFPPacketIn, handler.MAIN_DISPATCHER)
31 def packet_in_handler(self, ev):
32 pkt = packet.Packet(array.array('B', ev.msg.data))
33 for p in pkt.protocols:
36 You can create a Packet class instance with the received raw
37 data. Then the packet library parses the data and creates protocol
38 class instances included the data. The packet class 'protocols' has
39 the protocol class instances.
41 If a TCP packet is received, something like the following is printed::
43 <ryu.lib.packet.ethernet.ethernet object at 0x107a5d790>
44 <ryu.lib.packet.vlan.vlan object at 0x107a5d7d0>
45 <ryu.lib.packet.ipv4.ipv4 object at 0x107a5d810>
46 <ryu.lib.packet.tcp.tcp object at 0x107a5d850>
48 If vlan is not used, you see something like::
50 <ryu.lib.packet.ethernet.ethernet object at 0x107a5d790>
51 <ryu.lib.packet.ipv4.ipv4 object at 0x107a5d810>
52 <ryu.lib.packet.tcp.tcp object at 0x107a5d850>
54 You can access to a specific protocol class instance by using the
55 packet class iterator. Let's try to check VLAN id if VLAN is used:
57 .. code-block:: python
59 from ryu.lib.packet import packet
61 @handler.set_ev_cls(ofp_event.EventOFPPacketIn, handler.MAIN_DISPATCHER)
62 def packet_in_handler(self, ev):
63 pkt = packet.Packet(array.array('B', ev.msg.data))
65 print p.protocol_name, p
66 if p.protocol_name == 'vlan':
69 You see something like::
71 ethernet <ryu.lib.packet.ethernet.ethernet object at 0x107a5d790>
72 vlan <ryu.lib.packet.vlan.vlan object at 0x107a5d7d0>
74 ipv4 <ryu.lib.packet.ipv4.ipv4 object at 0x107a5d810>
75 tcp <ryu.lib.packet.tcp.tcp object at 0x107a5d850>
82 You need to create protocol class instances that you want to send, add
83 them to a packet class instance via add_protocol method, and then call
84 serialize method. You have the raw data to send. The following example
85 is building an arp packet.
87 .. code-block:: python
89 from ryu.ofproto import ether
90 from ryu.lib.packet import ethernet, arp, packet
92 e = ethernet.ethernet(dst='ff:ff:ff:ff:ff:ff',
93 src='08:60:6e:7f:74:e7',
94 ethertype=ether.ETH_TYPE_ARP)
95 a = arp.arp(hwtype=1, proto=0x0800, hlen=6, plen=4, opcode=2,
96 src_mac='08:60:6e:7f:74:e7', src_ip='192.0.2.1',
97 dst_mac='00:00:00:00:00:00', dst_ip='192.0.2.2')
102 print repr(p.data) # the on-wire packet