Mininet 搭建自定义网络

时间:2021-01-29 20:45:13

Mininet支持参数化拓扑,用几行python代码,你就可以创建一个基于你传进去的参数配置的灵活拓扑结构,还可被多个实验重复使用。

下面是一个小例子:(基于mininet/topo.py:SingleSwitchTopo,主机h1~hn都连接到单个交换机s1上

#!/usr/bin/python

    from mininet.topo import Topo
from mininet.net import Mininet
from mininet.util import dumpNodeConnections
from mininet.log import setLogLevel class SingleSwitchTopo(Topo):
"Single switch connected to n hosts."
def __init__(self, n=2, **opts):
# Initialize topology and default options
Topo.__init__(self, **opts)
switch = self.addSwitch('s1')
# Python's range(N) generates 0..N-1
for h in range(n):
host = self.addHost('h%s' % (h + 1))
self.addLink(host, switch) def simpleTest():
"Create and test a simple network"
topo = SingleSwitchTopo(n=4)
net = Mininet(topo)
net.start()
print "Dumping host connections"
dumpNodeConnections(net.hosts)
print "Testing network connectivity"
net.pingAll()
net.stop() if __name__ == '__main__':
# Tell mininet to print useful information
setLogLevel('info')
simpleTest()

  下面逐一介绍在上述代码中主要的类、方法以及变量:

Topo:Mininet拓扑结构的基类

addSwitch():给拓扑结构中增加一个交换机,返回交换机名字

addHost():增加主机,返回主机名字

addLink():增加一个双向链接,返回链接的key。

Mininet:创建和管理网络的主要类

start():开启网络

pingAll():通过主机之间的互ping测试连通性

stop():关闭网络

net.hosts 网络中的所有主机

dumpNodeConnection():列出所有的连接

 

Mininet搭建网络有3种方法:

底层API:节点和links

h1 = Host( 'h1' )
h2 = Host( 'h2' )
s1 = OVSSwitch( 's1', inNamespace=False )
c0 = Controller( 'c0', inNamespace=False )
Link( h1, s1 )
Link( h2, s1 )
h1.setIP( '10.1/8' )
h2.setIP( '10.2/8' )
c0.start()
s1.start( [ c0 ] )
print h1.cmd( 'ping -c1', h2.IP() )
s1.stop()
c0.stop()

中层API:网络对象

net = Mininet()
h1 = net.addHost( 'h1' )
h2 = net.addHost( 'h2' )
s1 = net.addSwitch( 's1' )
c0 = net.addController( 'c0' )
net.addLink( h1, s1 )
net.addLink( h2, s1 )
net.start()
print h1.cmd( 'ping -c1', h2.IP() )
CLI( net )
net.stop()

高级API:拓扑模板

class SingleSwitchTopo( Topo ):
"Single Switch Topology"
def __init__( self, count=1, **params ):
Topo.__init__( self, **params )
hosts = [ self.addHost( 'h%d' % i )
for i in range( 1, count + 1 ) ]
s1 = self.addSwitch( 's1' )
for h in hosts:
self.addLink( h, s1 ) net = Mininet( topo=SingleSwitchTopo( 3 ) )
net.start()
CLI( net )
net.stop()