使用python

时间:2018-07-21 20:38:14

标签: python mininet topology

我想使用python API构建小型网络拓扑。我的拓扑应该有2个控制器,3个交换机,每个交换机将有几台主机与其连接(已连接主机的数量分别为2、4、1)。这是代码:

#!/usr/bin/python                                                                                                                                                                   

import time
from mininet.net import Mininet
from mininet.node import Controller, OVSKernelSwitch, RemoteController
from mininet.cli import CLI
from mininet.log import setLogLevel, info


def net():

    net = Mininet(controller=RemoteController, switch=OVSKernelSwitch)
    c1 = net.addController('c1', controller=RemoteController, ip="127.0.0.1", port=6653)
    c2 = net.addController('c2', controller=RemoteController, ip="127.0.0.1", port=7753)

    s_n = 3 #number of switches
    c_n = 2 #number of controllers
    hosts = []
    amount = [2, 4, 1] # number of hosts that each switch has

    info( "*** Creating switches\n" )
    switches = [ net.addSwitch( 's%s' % s ) for s in range( 1, s_n ) ]

    index1 = 0 
    L_in = 0
    index2 = 0

    info( "*** Creating hosts\n" )
    for s in switches:
        L_in = (L_in + 1)
        if L_in <= len(amount):

            index1 = (index2 + 1)
            index2 = (index1 + amount[L_in]) - 1
            hosts = [ net.addHost( 'h%s' % n ) for n in ( index1, index2 ) ]
            for h in hosts:
                net.addLink( s, h )
        else:
            break

    # Wire up switches
    last = None
    for switch in switches:
        if last:
            net.addLink( last, switch )
        last = switch

    net.build()
    c1.start()
    c2.start()

    for sw in switches[:c_n]:
        sw.start( [c1] )

    for sw in switches[c_n:]:   
        sw.start( [c2] )

    net.start()
    CLI( net )
    net.stop()


if __name__ == '__main__':
    setLogLevel( 'info' )
    net()

但是当我运行代码时,它无法正常工作。例如,我期望3个开关,但是创建2个开关。我希望有7台主机,但是会创建4台主机。主机和交换机之间的连接也不正确。输出如下:

*** Creating switches
*** Creating hosts
*** Configuring hosts
h1 h4 h5 h5 
*** Starting controller
c1 c2 
*** Starting 2 switches
s1 s2 ...
*** Starting CLI:
mininet> net
h1 h1-eth0:s1-eth1
h4 h4-eth0:s1-eth2
h5 h5-eth0:s2-eth2
h5 h5-eth0:s2-eth2
s1 lo:  s1-eth1:h1-eth0 s1-eth2:h4-eth0 s1-eth3:s2-eth3
s2 lo:  s2-eth1:h5-eth0 s2-eth2:h5-eth0 s2-eth3:s1-eth3
c1
c2

1 个答案:

答案 0 :(得分:1)

这里有很多问题。

range(1, n)产生从1n-1n的数字。

您定义函数net,该函数将遮盖模块net的先前(导入的?)定义。称之为make_net之类的。

L_in这样的显式循环索引几乎总是一个坏主意,与index2的非描述性名称相同。

这样的事情应该给你的想法:

n_switches = 3
hosts_per_switch = [2, 4, 1]

switches = [addSwitch("s%d" % n + 1) for n in range(n_switches)]

for (switch, number_of_hosts) in zip(switches, hosts_per_switch):  # Pair them.
    hosts = [addHost("h%d" % n + 1) for n in range(number_of_hosts)]
    for host in hosts:
        addLink(switch, host)