Ryu控制器二次开发,实现一个简单的只能够简单地广播数据包的交换机。
from ryu.base import app_manager
from ryu.controller import ofp_event
from ryu.controller.handler import MAIN_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.ofproto import ofproto_v1_0
from ryu.lib.packet import packet
from ryu.lib.packet import ethernet
from ryu.lib.packet import ether_types
from ryu.lib.packet import ipv4
class SimpleSwitch(app_manager.RyuApp):
OFP_VERSIONS = [ofproto_v1_0.OFP_VERSION]
def __init__(self, *args, **kwargs):
super(SimpleSwitch, self).__init__(*args, **kwargs)
@set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
def _packet_in_handler(self, ev):
msg = ev.msg
datapath = msg.datapath
ofproto = datapath.ofproto
pkt = packet.Packet(msg.data)
eth = pkt.get_protocol(ethernet.ethernet)
if eth.ethertype == ether_types.ETH_TYPE_LLDP:
#ignore lldp packet
return
if eth.ethertype == ether_types.ETH_TYPE_IPV6:
#ignore ipv6 packet
return
print ("PACKET_IN:")
print (eth.ethertype)
print ("ethernet:")
print ("eth_src=",eth.src)
print ("eth_dst=",eth.dst)
if eth.ethertype == ether_types.ETH_TYPE_IP:
_ipv4 = pkt.get_protocol(ipv4.ipv4)
print ("ipv4:")
print ("ip_src=",_ipv4.src)
print ("ip_dst=",_ipv4.dst)
dpid = datapath.id
out_port = ofproto.OFPP_FLOOD
actions = [datapath.ofproto_parser.OFPActionOutput(out_port)]
data = None
out = datapath.ofproto_parser.OFPPacketOut(datapath=datapath, buffer_id=msg.buffer_id, in_port=msg.in_port, actions=actions, data=data)
datapath.send_msg(out)
print ("PACKET_OUT...")
print
保存为SimpleSwitch.py,使用python 3.5编译通过。
在SimpleSwitch.py目录下运行:
ryu-manager SimpleSwitch.py
在本机使用mininet创建最简拓扑:
sudo mn --controller=remote,ip=127.0.0.1,port=6633
- 此时交换机s1上并无流表
- 在Mininet CLI运行h1 ping h2,h1发送广播寻找h2,交换机无流表处理,触发交换机向控制器发送packet_in消息
- 控制器向交换机回送packet_out消息,根据程序中定义的动作,让交换机将端口1进入的数据包在拓扑内广播泛洪(ofproto.OFPP_FLOOD)
- h2收到广播后向h1回送信息,交换机对于2端口进入的数据包无流表处理,触发交换机向控制器发送packet_in消息
- 控制器向交换机回送packet_out消息,根据程序中定义的动作,让交换机将端口2进入的数据包在拓扑内广播泛洪(ofproto.OFPP_FLOOD)
- h1收到广播后和h2建立ip通信,再次触发packet_in
- 控制器继续packet_out,对端口1的数据广播
- h2回送消息
- 控制器继续packet_out,对端口2的数据广播