def genericTest(topo):
    net = Mininet(topo=topo, switch=SliceableSwitch,
        controller=RemoteController)
    net.start()
    run(net)
    CLI(net)
    net.stop()
def setupNetwork():
    "Create network"
    topo = MyTopo()
    network = Mininet(topo=topo, autoSetMacs=True, controller=None)
    network.start()
    CLI( network )
    network.stop()
 def testDefaultDpid( self ):
     """Verify that the default dpid is assigned using a valid provided
     canonical switchname if no dpid is passed in switch creation."""
     switch = Mininet( Topo(),
                       self.switchClass,
                       Host, Controller ).addSwitch( 's1' )
     self.assertEqual( switch.defaultDpid(), switch.dpid )
Exemple #4
0
    def start_networking(self):
        setLogLevel("info")
        net = Mininet(topo=self, \
                      controller=lambda name: RemoteController(name))
        net.start()

        # setup each switch
        for sw in net.switches:
            # set ofp version
            self.set_ofp_version(sw, ['OpenFlow10', 'OpenFlow13'])
            # if sw is bridge, set it up for normal SW
            swEntry = self.switchList[sw.name][1]
            isBridge = swEntry["bridge"]
            if isBridge:
                self.set_normalsw(sw)
            self.switchList[sw.name].append(sw)

        # setup each host
        for host in net.hosts:
            self.add_ipv6address(host)
            self.hostList[host.name].append(host)

        # execute pre_command
        if "pre_cmd_file" in self.jsonData:
            cmd_file = self.jsonData["pre_cmd_file"]
            self.exec_usercmd(cmd_file)

        CLI(net)

        # execute post_command
        if "post_cmd_file" in self.jsonData:
            cmd_file = self.jsonData["post_cmd_file"]
            self.exec_usercmd(cmd_file)

        net.stop()
def topology():

    "Create a network."
    net = Mininet( controller=Controller, link=TCLink, switch=OVSKernelSwitch )

    print "*** Creating nodes"
    sta1 = net.addStation( 'sta1', mac='00:00:00:00:00:02', ip='10.0.0.2/8', position='10,20,0' )
    sta2 = net.addStation( 'sta2', mac='00:00:00:00:00:03', ip='10.0.0.3/8', position='10,30,0' )
    ap1 = net.addBaseStation( 'ap1', ssid= 'new-ssid', mode= 'g', channel= '1', position='15,30,0' )
    c1 = net.addController( 'c1', controller=Controller )

    """uncomment to plot graph"""
    #net.plotGraph(max_x=60, max_y=60)

    print "*** Creating links"
    net.addLink(ap1, sta1)
    net.addLink(ap1, sta2)

    print "*** Starting network"
    net.build()
    c1.start()
    ap1.start( [c1] )

    print "*** Running CLI"
    CLI( net )

    print "*** Stopping network"
    net.stop()
Exemple #6
0
def runMultiLink():
    "Create and run multiple link network"
    topo = simpleMultiLinkTopo( n=2 )
    net = Mininet( topo=topo )
    net.start()
    CLI( net )
    net.stop()
Exemple #7
0
def run( n ):
    topo = OpticalTopo( n )
    net = Mininet( topo=topo, controller=RemoteController, autoSetMacs=True )
    net.start()
    #installStaticFlows( net )
    CLI( net )
    net.stop()
def topology():
    "Create a network."
    net = Mininet( wirelessRadios=3, controller=Controller, link=TCLink, switch=OVSKernelSwitch )
    #wirelessRadios = Number of STAs + APs

    print "*** Creating nodes"
    sta1 = net.addStation( 'sta1' )
    sta2 = net.addStation( 'sta2' )
    ap1 = net.addBaseStation( 'ap1', ssid="simplewifi", mode="g", channel="5" )
    c0 = net.addController('c0', controller=Controller, ip='127.0.0.1', port=6633 )

    print "*** Adding Link"
    net.addLink(sta1, ap1)
    net.addLink(sta2, ap1)

    print "*** Starting network"
    net.build()
    c0.start()
    ap1.start( [c0] )

    print "*** Running CLI"
    CLI( net )

    print "*** Stopping network"
    net.stop()
Exemple #9
0
    def build( self ):
        print "Build network based on our topology."

        net = Mininet( topo=None, build=False, link=TCLink, ipBase=self.minieditIpBase )
 
        net.controllers = self.addControllers()
        
        # Make nodes
        print "Getting Hosts and Switches."
        for widget in self.widgetToItem:
            name = widget[ 'text' ]
            tags = self.canvas.gettags( self.widgetToItem[ widget ] )
            nodeNum = int( name[ 1: ] )
            if 'Switch' in tags:
                net.addSwitch( name )
            elif 'Host' in tags:
                ipBaseNum, prefixLen = netParse( self.minieditIpBase )
                ip = ipAdd(i=nodeNum, prefixLen=prefixLen, ipBaseNum=ipBaseNum)
                net.addHost( name, ip=ip )
            else:
                raise Exception( "Cannot create mystery node: " + name )

        # Make links
        print "Getting Links."
        for link in self.links.values():
            ( src, dst, linkopts ) = link
            srcName, dstName = src[ 'text' ], dst[ 'text' ]
            src, dst = net.nameToNode[ srcName ], net.nameToNode[ dstName ]
            net.addLink(src, dst, **linkopts)

        self.printInfo()
        # Build network (we have to do this separately at the moment )
        net.build()

        return net
Exemple #10
0
    def create_mininet(self, topo, tunnels=[],  switch=UserSwitch,
                       controller=None, STT=False):
        if(not self.net is None):
            self.logger.warn("running mininet instance detected!\
                              Shutting it down...")
            self.destroy_mininet()

        self.logger.info("Creating mininet instance")
        if controller:
            self.net = Mininet(topo=topo, intf=TCIntf, link=TCLink,
                               switch=switch, controller=controller)
        else:
            self.net = Mininet(topo=topo, intf=TCIntf, link=TCLink,
                               switch=switch)
        if STT:
            self.logger.info("Starting Mininet...")
            self.net.start()
        self.logger.info("Adding tunnels to mininet instance")
        for tunnel in tunnels:
            port = None
            cls = None
            if "port" in tunnel[2].keys():
                port = tunnel[2]["port"]
                del tunnel[2]["port"]
            if "cls" in tunnel[2].keys():
                cls = tunnel[2]["cls"]
                del tunnel[2]["cls"]
            self.addTunnel(tunnel[0], tunnel[1], port, cls, STT=STT, **tunnel[2])
        if not STT:
            self.logger.info("Starting Mininet...")
            self.net.start()
        self.logger.info("Startup complete.")
        self.x11popens = []
        return True
Exemple #11
0
def test():
    topo = DssTopo()
    net = Mininet(topo, link=TCLink)
    net.start()

    pidList(net)

    global NPAUSE
    global NRESUME

    NPAUSE = 'sudo /home/kd/VirtualTimeKernel/test_virtual_time/freeze_all_procs -f -p %s'%pIDS
    NRESUME ='sudo /home/kd/VirtualTimeKernel/test_virtual_time/freeze_all_procs -u -p %s'%pIDS
    
    #block
    print(net.get('h1').cmd('ping -c 1 10.0.0.2'))

    net.get('h1').cmd('ping -c 40 10.0.0.2 > %sbl.test'% FileOut)
    
    #dont block
    net.get('h1').cmd('/home/kd/VirtualTimeKernel/iputils/ping -c 40 -D 10.0.0.2 > %svt.test &'% FileOut)
    time.sleep(5)

    for x in range(0,int(sys.argv[3])):
        print 'pausing'
        pause()
        time.sleep(stime)
	print 'resumed'
 
    time.sleep(30)
    net.stop()    
Exemple #12
0
def perfTest():
    topo = crazy_switches()
    net = Mininet(topo=topo, controller=lambda name: RemoteController( 'c0', '127.0.0.1' ),
                  host=CPULimitedHost, link=TCLink)
    net.start()
    CLI(net)
    net.stop()
def main():

	# All b/w are in megabits
	max_bw = 1000

	# B/w of queue 1 and queue 2
	values = [3,1,4]

	topo = MyTopo(max_bw)

	net = Mininet(topo, link = TCLink, controller = partial(RemoteController, ip = '127.0.0.1', port = 6633))
	
	net.start()

	# Queue set in between h1 and s1
	cmd = 'ovs-vsctl -- set Port s2-eth4 qos=@newqos -- \
		--id=@newqos create QoS type=linux-htb other-config:max-rate=1000000000 queues=0=@q0,1=@q1,2=@q2,3=@q3 -- \
		--id=@q0 create Queue other-config:min-rate=%d other-config:max-rate=%d -- \
		--id=@q1 create Queue other-config:min-rate=%d other-config:max-rate=%d -- \
		--id=@q2 create Queue other-config:min-rate=%d other-config:max-rate=%d -- \
		--id=@q3 create Queue other-config:min-rate=%d other-config:max-rate=%d' % \
		(max_bw * 10**6, max_bw * 10**6, \
		values[0] * 10**6, values[0] * 10**6, \
		values[1] * 10**6, values[1] * 10**6, \
		values[2] * 10**6, values[2] * 10**6)

	sp.call(cmd, shell = True)
	
	CLI(net)
	net.stop()
Exemple #14
0
def myNet():
    #OpenDayLight controller
    CONTROLLER1_IP='127.0.0.1'

    #Floodlight controller

    net = Mininet( topo=None, build=False)

    # Create nodes
    h1 = net.addHost( 'h1', mac='01:00:00:00:01:00', ip='192.168.0.1/24' )

    # Create switches
    s1 = net.addSwitch( 's1', listenPort=6634, mac='00:00:00:00:00:01' )
    
    print "*** Creating links"
    net.addLink(h1, s1 )
  

    # Add Controllers
    c0 = net.addController( 'c0', controller=RemoteController, ip=CONTROLLER1_IP, port=6633)

    net.build()

    # Connect each switch to a different controller
    s1.start([c0])

    s1.cmdPrint('ovs-vsctl show')
    
    CLI( net )
    net.stop()
def LowMnNet(n, nn, nnn):
	print "############ Instanitiate a mininet of topology LowMnTopo ###############\n"
	topo = LowMnTopo(n, nn, nnn)
	ctrl_port=6633
	net = Mininet(topo=topo, ipBase='10.0.0.0/8', autoSetMacs=True, host=CPULimitedHost, link=TCLink)
 	net.start()
	return net
Exemple #16
0
def setup(num, hwintf, beg_ip):

    info( '*** Creating network\n' )
    #net = Mininet( topo=TestTopo( num ), switch=UserSwitch, controller=RemoteController)
    #net = Mininet( topo=TestTopo( num ), controller=RemoteController, listenPort=6634)
    net = Mininet( topo=TestTopo( num ), controller=RemoteController)
    #net = Mininet( topo=TestTopo( num ))

    os.environ['NOX_CORE_DIR'] = '/opt/nox/bin'
    #controller = net.addController(name='c0', controller=NOX, noxArgs='switchqos --threads=1')
    controller = net.addController(name='c0', controller=NOX, noxArgs='switchqos --threads=10')
    #controller = net.addController(name='c0', controller=NOX, noxArgs='switch --threads=10')

    #os.environ['NOX_CORE_DIR'] = '/usr/local/bin'
    #controller = net.addController(name='c0', controller=NOX, noxArgs='switchqos')

    # Add HW interface to root switch
    switch = net.switches[ 0 ]
    switch.addIntf(hwintf)

    ip = beg_ip.split('.')
    for n in range( N-1 ):
        h = net.hosts[n]
        i = h.intfs[0]
        h.setIP(i, '.'.join(ip), 24)
        #print "IP: " + `h.IP()`
        ip[3] = str(int(ip[3]) + 1)
        #print h.IP()

    #import networkx
    #networkx.draw(net.topo.g)
    #import pylab
    #pylab.show()

    return(net)
Exemple #17
0
    def testLinkBandwidth( self ):
        "Verify that link bandwidths are accurate within a bound."
        if self.switchClass is UserSwitch:
            self.skipTest( 'UserSwitch has very poor performance -'
                           ' skipping for now' )
        BW = 5  # Mbps
        BW_TOLERANCE = 0.8  # BW fraction below which test should fail
        # Verify ability to create limited-link topo first;
        lopts = { 'bw': BW, 'use_htb': True }
        # Also verify correctness of limit limitng within a bound.
        mn = Mininet( SingleSwitchOptionsTopo( n=N, lopts=lopts ),
                      link=TCLink, switch=self.switchClass,
                      waitConnected=True )
        bw_strs = mn.run( mn.iperf, fmt='m' )
        loptsStr = ', '.join( '%s: %s' % ( opt, value )
                              for opt, value in lopts.items() )
        msg = ( '\nTesting link bandwidth limited to %d Mbps per link\n'
                'iperf results[ client, server ]: %s\n'
                'Topo = SingleSwitchTopo, %s hosts\n'
                'Link = TCLink\n'
                'lopts = %s\n'
                'host = default\n'
                'switch = %s\n'
                % ( BW, bw_strs, N, loptsStr, self.switchClass ) )

        # On the client side, iperf doesn't wait for ACKs - it simply
        # reports how long it took to fill up the TCP send buffer.
        # As long as the kernel doesn't wait a long time before
        # delivering bytes to the iperf server, its reported data rate
        # should be close to the actual receive rate.
        serverRate, _clientRate = bw_strs
        bw = float( serverRate.split(' ')[0] )
        self.assertWithinTolerance( bw, BW, BW_TOLERANCE, msg )
def on_topology(topology_gml_file):
    local_apps = 'ryuo.topology.topology'
    working_dir = '.'
    # Clean up environment
    mn_c = subprocess.Popen(['mn', '-c'])
    mn_c.wait()
    # Run Ryuo name server
    ryuo_ns = subprocess.Popen(['bin/ryuo-ns'])
    time.sleep(3)
    # Run Ryuo app
    ryuo_app = subprocess.Popen(['ryu-manager', 'ryuo.topology.app'],
                                cwd=working_dir, stdout=subprocess.PIPE)
    time.sleep(4)
    net = Mininet(topo=RyuoTopoFromTopoZoo(topology_gml_file,
                                           'OpenFlow13',
                                           working_dir,
                                           local_apps),
                  switch=RyuoOVSSwitch,
                  controller=RemoteController,
                  link=TCLink)
    net.start()
    time.sleep(10)
    net.stop()
    ryuo_app.kill()
    ryuo_ns.kill()
Exemple #19
0
 def __init__( self, *args, **kwargs ):
     """servers: a list of servers to use (note: include
        localhost or None to use local system as well)
        user: user name for server ssh
        placement: Placer() subclass"""
     params = { 'host': RemoteHost,
                'switch': RemoteOVSSwitch,
                'link': RemoteLink,
                'precheck': True }
     params.update( kwargs )
     servers = params.pop( 'servers', [ 'localhost' ] )
     servers = [ s if s else 'localhost' for s in servers ]
     self.servers = servers
     self.serverIP = params.pop( 'serverIP', {} )
     if not self.serverIP:
         self.serverIP = { server: RemoteMixin.findServerIP( server )
                           for server in self.servers }
     self.user = params.pop( 'user', findUser() )
     if params.pop( 'precheck' ):
         self.precheck()
     self.connections = {}
     self.placement = params.pop( 'placement', SwitchBinPlacer )
     # Make sure control directory exists
     self.cdir = os.environ[ 'HOME' ] + '/.ssh/mn'
     errRun( [ 'mkdir', '-p', self.cdir ] )
     Mininet.__init__( self, *args, **params )
Exemple #20
0
def simple():
	t=MyTopo();
	#c=Controller(name="c0",command="python ./pox/pox.py")
	#net=Mininet(t,controller=bridge);
	net=Mininet(topo=t,controller=lambda name:RemoteController(name,ip='127.0.0.1'))
	#net.addController(name="c0",port=6633);
	#mininet.node.RemoteController(port=6633)
	net.start();
	
	#print net.host;
	f=open("MacHost.txt","w");
	for i in net.hosts:
		print "i= ";
		print i;
		print Node.MAC(i);
		f.write(str(i)+" "+str(Node.MAC(i))+"\n");
	f.close();
	z=0
	f=open("/home/saumya/pox/output.txt","w")
	f.close()
	for i in net.hosts:
		for j in net.hosts:
			if(i!=j):
				time.sleep(10);
				net.ping([i,j])
				z=z+1;
				parse("/home/saumya/pox/output.txt");
				draw_graph();
def startNetwork():
	topo = createTopo()
	global net
	net = Mininet(topo=topo, autoSetMacs=True)
	net.start()
	h1,h2,h3,h4,h5,h6,r1,r2,r3  = net.hosts
	h1.cmd('ifconfig h1-eth0 10.0.0.1 netmask 255.255.255.0')
	h1.cmd('route add default gw 10.0.0.3')
	h2.cmd('ifconfig h2-eth0 10.0.0.2 netmask 255.255.255.0')
	h2.cmd('route add default gw 10.0.0.3')
	h3.cmd('ifconfig h3-eth0 20.0.0.1 netmask 255.255.255.0')
	h3.cmd('route add default gw 20.0.0.3')
	h4.cmd('ifconfig h4-eth0 20.0.0.2 netmask 255.255.255.0')
	h4.cmd('route add default gw 20.0.0.3')
	h5.cmd('ifconfig h5-eth0 30.0.0.1 netmask 255.255.255.0')
	h5.cmd('route add default gw 30.0.0.3')
	h6.cmd('ifconfig h6-eth0 30.0.0.2 netmask 255.255.255.0')
	h6.cmd('route add default gw 30.0.0.3')

	r1.cmd('ifconfig r1-eth0 10.0.0.3 netmask 255.255.255.0')
	r2.cmd('ifconfig r2-eth0 20.0.0.3 netmask 255.255.255.0')
	r3.cmd('ifconfig r3-eth0 30.0.0.3 netmask 255.255.255.0')

	r1.cmd('ifconfig r1-eth1 110.0.0.1 netmask 255.255.255.0')
	r2.cmd('ifconfig r2-eth1 110.0.0.2 netmask 255.255.255.0')
	r1.cmd('ifconfig r1-eth2 120.0.0.1 netmask 255.255.255.0')
	r3.cmd('ifconfig r3-eth1 120.0.0.2 netmask 255.255.255.0')
	r2.cmd('ifconfig r2-eth2 130.0.0.1 netmask 255.255.255.0')
	r3.cmd('ifconfig r3-eth2 130.0.0.2 netmask 255.255.255.0')

	r1.cmd('echo 1 >> /proc/sys/net/ipv4/ip_forward')
	r2.cmd('echo 1 >> /proc/sys/net/ipv4/ip_forward')
	r3.cmd('echo 1 >> /proc/sys/net/ipv4/ip_forward')

	CLI(net)
Exemple #22
0
def prev_get_default_net_hosts_switches(topo, listen_port, num_hosts, num_switches):
    net = Mininet(topo=topo, host=CPULimitedHost, controller=RemoteController,
                  listenPort=listen_port)
    net.start()
    hosts = get_hosts(net, num_hosts)
    switches = get_switches(net, num_switches)
    return (net, hosts, switches)
def main():
    net = Mininet()
    # create hosts
    h1 = net.addHost('h1')
    h2 = net.addHost('h2')

    # create switch
    s1 = net.addSwitch('S1')

    # create controller
    c1 = net.addController('c1')

    # create links
    net.addLink(h1, s1)
    net.addLink(h2, s1)

    net.start()

    # start web server on h2
    print('starting web server...')
    h2.cmd('python -m SimpleHTTPServer 80 &')
    sleep(2)

    # use h1 as a web client
    print('accessing web server..')
    h1.cmd('curl', h2.IP())

    # CLI(net)
    print('kill web server..')
    h2.cmd('kill %python')

    print('finish.')
    net.stop()
Exemple #24
0
def monitorTest( N=3, seconds=3 ):
    "Run pings and monitor multiple hosts"
    topo = SingleSwitchTopo( N )
    net = Mininet( topo )
    net.start()
    hosts = net.hosts
    info( "Starting test...\n" )
    server = hosts[ 0 ]
    outfiles, errfiles = {}, {}
    for h in hosts:
        # Create and/or erase output files
        outfiles[ h ] = '/tmp/%s.out' % h.name
        errfiles[ h ] = '/tmp/%s.err' % h.name
        h.cmd( 'echo >', outfiles[ h ] )
        h.cmd( 'echo >', errfiles[ h ] )
        # Start pings
        h.cmdPrint('ping', server.IP(),
                   '>', outfiles[ h ],
                   '2>', errfiles[ h ],
                   '&' )
    info( "Monitoring output for", seconds, "seconds\n" )
    for h, line in monitorFiles( outfiles, seconds, timeoutms=500 ):
        if h:
            info( '%s: %s\n' % ( h.name, line ) )
    for h in hosts:
        h.cmd('kill %ping')
    net.stop()
Exemple #25
0
def topoTest():
    "Create network and run simple performance test"
    topo = ITATopo()
    # topo = ITATopo(12, 10)
    net = Mininet(topo=topo, host=CPULimitedHost, link=TCLink)

    net.interact()
Exemple #26
0
def run():
    "Create network and run the CLI"
    topo = InternetTopo()
    net = Mininet(topo=topo)
    net.start()
    CLI(net)
    net.stop()
Exemple #27
0
def main():
    # Defines the log level
    setLogLevel('info')

    # parses command line arguments
    parser = OptionParser()
    parser.add_option('-H', dest='hosts', default=5,
                      help='Number of hosts per switch')
    parser.add_option('-S', dest='switches', default=2,
                      help='Number of switches')
    (options, args) = parser.parse_args()

    # Build network topology (see mininet/topo.py)
    topo = LinearTopo(int(options.switches), int(options.hosts))

    # Creates the Network using a remote controller
    net = Mininet(topo,
                  controller=lambda a: RemoteController(a, ip='127.0.0.1'))

    # Starts the network
    net.start()
    # Run the mininet client
    CLI(net)
    # Stop the network
    net.stop()
Exemple #28
0
def multiping(netsize, chunksize, seconds):
    "Ping subsets of size chunksize in net of size netsize"

    # Create network and identify subnets
    topo = SingleSwitchTopo(netsize)
    net = Mininet(topo=topo)
    net.start()
    hosts = net.hosts
    subnets = chunks(hosts, chunksize)

    # Create polling object
    fds = [host.stdout.fileno() for host in hosts]
    poller = poll()
    for fd in fds:
        poller.register(fd, POLLIN)

    # Start pings
    for subnet in subnets:
        ips = [host.IP() for host in subnet]
        for host in subnet:
            startpings(host, ips)

    # Monitor output
    endTime = time() + seconds
    while time() < endTime:
        readable = poller.poll(1000)
        for fd, _mask in readable:
            node = Node.outToNode[fd]
            print "%s:" % node.name, node.monitor().strip()

    # Stop pings
    for host in hosts:
        host.cmd("kill %while")

    net.stop()
Exemple #29
0
def emptyNet():

    net = Mininet(topo=None, build=False)
    c0 = Controller('c0', inNamespace=False)

    h1 = Host('h1')
    h2 = Host('h2')
    #intf1 = Intf("h1-eth1")
    #intf2 = Intf("h2-eth1")
    s1 = OVSSwitch('br0', inNamespace=False)    

    Link(h1, s1)
    Link(h2, s1)


    c0.start()
    s1.start([c0])

    net.start()    
    #s1.cmd('ovs-vsctl set bridge br0 protocols=OpenFlow13')
    CLI(net)

    net.stop()
    h1.stop()
    h2.stop()
    s1.stop()
    c0.stop()
Exemple #30
0
def get_default_net_hosts_switches(topo, listen_port):
    net = Mininet(topo=topo, host=CPULimitedHost, controller=RemoteController,
                  listenPort=listen_port)
    net.start()
    hosts = get_nodes(net, topo.hosts())
    switches = get_nodes(net, topo.switches())
    return (net, hosts, switches)
def topology():

    "Create a network."
    net = Mininet(controller=Controller, link=TCLink, switch=OVSKernelSwitch)

    print "*** Creating nodes"
    ## The mobile node
    sta1 = net.addStation('sta1',
                          wlans=2,
                          mac='00:00:00:00:00:02',
                          ip='10.0.0.2/24')
    ## The long range, poor quality access point
    ap1 = net.addAccessPoint('ap1',
                             ssid='ap1-ssid',
                             mode='g',
                             channel='1',
                             position='50,50,0',
                             range=51)
    ## The sort range, good quality access points
    ap2 = net.addAccessPoint('ap2',
                             ssid='ap2-ssid',
                             mode='g',
                             channel='4',
                             position='10,10,0',
                             range=30)
    ap3 = net.addAccessPoint('ap3',
                             ssid='ap3-ssid',
                             mode='g',
                             channel='4',
                             position='90,10,0',
                             range=30)
    ap4 = net.addAccessPoint('ap4',
                             ssid='fast-ssid',
                             mode='g',
                             channel='4',
                             position='50,80,0',
                             range=10)
    ## Controller for the APs (don't need to change this)
    c1 = net.addController('c1', controller=Controller)
    ## The host, will run the HTTP server in this example
    h1 = net.addHost('h1', ip='10.0.0.3/24')

    print "*** Configuring wifi nodes"
    net.configureWifiNodes()

    ## (ap2--ap3--ap4)
    print "*** Creating links"
    net.addLink(ap2, ap3)
    net.addLink(ap3, ap4)

    ## Poor quality link ap1---h1
    net.addLink(ap1, h1, bw=2, delay='10ms', max_queue_size=1000)
    ## Good quality link ap2---h1 (note that ap2--ap3--ap4)
    net.addLink(ap2, h1)

    ## Just to make sure the interfaces are correctly set
    net.addLink(ap1, sta1)
    net.addLink(ap2, sta1)

    print "*** Starting network"
    net.build()
    c1.start()
    ap1.start([c1])
    ap2.start([c1])
    ap3.start([c1])
    ap4.start([c1])

    ## Manually set a second IP for h1 and sta1
    sta1.setIP('10.1.0.2/24', intf='sta1-wlan1')
    h1.setIP('10.1.0.3/24', intf='h1-eth1')

    ## Run a simple HTTP server on h1
    #print "*** Starting HTTP server on H1"
    #h1.cmdPrint('python -m SimpleHTTPServer 80 &')
    """association control"""
    net.associationControl('ssf')
    """Plot graph"""
    net.plotGraph(max_x=100, max_y=100)
    """Seed"""
    net.seed(20)

    "*** Available models: RandomWalk, TruncatedLevyWalk, RandomDirection, RandomWayPoint, GaussMarkov, ReferencePoint, TimeVariantCommunity ***"
    net.startMobility(startTime=0,
                      model='RandomWayPoint',
                      max_x=100,
                      max_y=100,
                      min_v=0.5,
                      max_v=0.8)

    print "*** Running CLI"
    CLI(net)

    print "*** Stopping network"
    net.stop()
Exemple #32
0
    def medir(self,filename):
        print "Iniciando el experimento"
        list_files = self.crearNombresArchivos(filename)
        if self.tasaAtaque == None:
            for f in list_files:
                medida = PingMeasure(outfile=f, t_total=self.tiempo, intervalo=1)
                net = Mininet(switch=OVSSwitch, build=False, link=TCLink)
                net.addController('c0', controller=RemoteController, ip="127.0.0.1", port=6653)
                h1 = net.addHost('h1', ip='10.0.0.1')  # Cliente
                h2 = net.addHost('h2', ip='10.0.0.2')  # Atacante
                h3 = net.addHost('h3', ip='10.0.0.3')  # Victima
                medida.configHosts(h2, h3)
                sw1 = net.addSwitch('sw1', protocols='OpenFlow13')
                net.addLink(h1, sw1, bw=100)
                net.addLink(h2, sw1, bw=100)
                net.addLink(h3, sw1, bw=100)
                net.build()
                net.start()
                medida.medir()
                net.stop()
                medida.printOutputFile()

        else:
            for f in list_files:
                medida = PingMeasureAttack(outfile=f, t_total=self.tiempo, intervalo= 1)
                net = Mininet(switch=OVSSwitch, build=False, link=TCLink)
                net.addController('c0', controller=RemoteController, ip="127.0.0.1", port=6653)
                h1 = net.addHost('h1', ip='10.0.0.1')  # Cliente
                h2 = net.addHost('h2', ip='10.0.0.2')  # Atacante
                h3 = net.addHost('h3', ip='10.0.0.3')  # Victima
                medida.configAttack(h2, h3, h1, self.tasaAtaque)
                sw1 = net.addSwitch('sw1', protocols='OpenFlow13')
                net.addLink(h1, sw1, bw=100)
                net.addLink(h2, sw1, bw=100)
                net.addLink(h3, sw1, bw=100)
                net.build()
                net.start()
                medida.medirAtaque()
                net.stop()
                medida.printOutputFile()
Exemple #33
0
def bufferbloat():
    if not os.path.exists(args.dir):
        os.makedirs(args.dir)
    os.system("sysctl -w net.ipv4.tcp_congestion_control=%s" % args.cong)

    # Cleanup any leftovers from previous mininet runs
    cleanup()

    topo = BBTopo()
    net = Mininet(topo=topo, host=CPULimitedHost, link=TCLink)
    net.start()
    # This dumps the topology and how nodes are interconnected through
    # links.
    dumpNodeConnections(net.hosts)
    # This performs a basic all pairs ping test.
    net.pingAll()

    # Start all the monitoring processes
    start_tcpprobe("cwnd.txt")
    start_ping(net)

    # TODO: Start monitoring the queue sizes.  Since the switch I
    # created is "s0", I monitor one of the interfaces.  Which
    # interface?  The interface numbering starts with 1 and increases.
    # Depending on the order you add links to your network, this
    # number may be 1 or 2.  Ensure you use the correct number.
    #
    qmon = start_qmon(iface='s0-eth2', outfile='%s/q.txt' % (args.dir))
    # qmon = None

    # TODO: Start iperf, webservers, etc.
    start_iperf(net)
    start_webserver(net)

    # Hint: The command below invokes a CLI which you can use to
    # debug.  It allows you to run arbitrary commands inside your
    # emulated hosts h1 and h2.
    #
    # CLI(net)

    # TODO: measure the time it takes to complete webpage transfer
    # from h1 to h2 (say) 3 times.  Hint: check what the following
    # command does: curl -o /dev/null -s -w %{time_total} google.com
    # Now use the curl command to fetch webpage from the webserver you
    # spawned on host h1 (not from google!)
    # Hint: have a separate function to do this and you may find the
    # loop below useful.
    h1 = net.get('h1')
    h2 = net.get('h2')
    #Record the start time to help us know whether we should stop the simulation
    start_time = time()

    #The list save the download times in fixed duration
    fetch_times = []

    #The list save tuples (fetch time point, download time) (which is [fetch_clock, float(fetch_time)] returned by measure_fetch_time)
    measure_data = []
    while True:
        # do the measurement (say) 3 times.
        fetch_info = measure_fetch_time(h1, h2)

        #get the download time
        fetch_time = fetch_info[1]
        print "fetch time %s" % fetch_time

        #add every download time to the list
        fetch_times.append(float(fetch_time))

        #add every tuple (fetch time point, download time) to the list
        measure_data.append(fetch_info)

        #download the webpage from h1 every two seconds
        sleep(1)
        now = time()
        delta = now - start_time
        if delta > args.time:
            break
        print "%.1fs left..." % (args.time - delta)

    #save the time points and download times to the file
    save_download_time_to_file(measure_data)

    # TODO: compute average (and standard deviation) of the fetch
    # times.  You don't need to plot them.  Just note it in your
    # README and explain.
    ave = helper.avg(fetch_times)
    std = helper.stdev(fetch_times)
    print "Average: " + str(ave)
    print "Standard deviation: " + str(std)

    #save the average (and standard deviation) of the fetch to the file
    save_ave_std_to_file(str(ave), str(std))

    stop_tcpprobe()
    if qmon is not None:
        qmon.terminate()
    net.stop()
    # Ensure that all processes you create within Mininet are killed.
    # Sometimes they require manual killing.
    Popen("pgrep -f webserver.py | xargs kill -9", shell=True).wait()
def myNetwork():

    net = Mininet( topo=None,
                   build=False,
                   ipBase='10.0.0.0/8')

    info( '*** Adding controller\n' )
    c0=net.addController(name='c0',
                      controller=RemoteController,
                      port=6633)

    info( '*** Add switches\n')
    S_1_1 = net.addHost('S_1_1')
    S_1_2 = net.addHost('S_1_2')
    S_1_3 = net.addHost('S_1_3')
    S_2 = net.addHost('S_2')
    S_3_1 = net.addHost('S_3_1')
    S_3_2 = net.addHost('S_3_2')
    MLS1 = net.addHost('MLS1')
    MLS2 = net.addHost('MLS2')
    ISP = net.addHost('ISP')
    S_2_2 = net.addHost('S_2_2')
    S_3_3 = net.addHost('S_3_3')

    info( '*** Adding Routers\n')
    R1 = net.addHost('R1', cls=Node)
    R2 = net.addHost('R2', cls=Node)

    info( '*** Add hosts\n')
    info('*** Adding Level1 hosts\n')  # Summarization Address : 10.0.0.0/16
    info('*** 7 Offices\n')  # Subnet: 10.0.0.0/24  VLAN10
    for i in range(1, 9):   # Use a for loop to add hosts.
        net.addHost('L1_OH' + str(i), cls=Host, ip='10.0.0.' + str(i) + '/24', defaultRoute = 'via 10.0.0.254 dev L1_OH' + str(i) + '-eth0')
        net.addLink('L1_OH' + str(i), S_1_1, intfName2 = 'S_1_1-eth0' + str(i))

    info('*** 40 lab PCs\n')  # Subnet: 10.0.1.0/24  VLAN11
    for i in range(1,41):
        net.addHost('L1_LH' + str(i), cls=Host, ip='10.0.1.' + str(i) + '/24', defaultRoute = 'via 10.0.1.254 dev L1_LH' + str(i) + '-eth0')
        net.addLink('L1_LH' + str(i), S_1_2, intfName2 = 'S_1_2-eth0' + str(i))

    info( '*** 1 lab-Tut PCs\n')        # Subnet: 10.0.2.0/24   VLAN12
    net.addHost('L1_LT', cls=Host, ip='10.0.2.0/24', defaultRoute='via 10.0.2.254 dev L1_LT-eth0')
    net.addLink('L1_LT', S_1_3, intfName2='S_1_3-eth0')

    info( '*** 10 Servers\n')       # Subnet: 10.0.4.0/24     VLAN14
    for i in range(1,11):
        net.addHost('L1_SH' + str(i), cls=Host, ip='10.0.4.' + str(i) + '/24', defaultRoute = 'via 10.0.4.254 dev L1_SH' + str(i) + '-eth0')
        net.addLink('L1_SH' + str(i), S_1_3, intfName2 = 'S_1_3-eth1' + str(i))

    info( '*** Adding Level2 hosts\n')      # Summarization Address : 10.1.0.0/16
    info( '*** Sofeware House 10 PCs\n')  # Subnet: 10.1.0.0/24     VLAN20
    for i in range(1,11):
        net.addHost('L2_SH' + str(i), cls=Host, ip='10.1.0.' + str(i) + '/24', defaultRoute = 'via 10.1.0.254 dev L2_SH' + str(i) + '-eth0')
        net.addLink('L2_SH' + str(i), S_2, intfName2 = 'S_2-eth0' + str(i))

    info( '*** Adding Level3 hosts\n')      # Summarization Address : 10.2.0.0/16
    info('*** R&D Lab 30 PCs\n')  # Subnet: 10.2.0.0/24     VLAN30
    for i in range(1,31):
        net.addHost('L3_LH' + str(i), cls=Host, ip='10.2.0.' + str(i) + '/24', defaultRoute = 'via 10.2.0.254 dev L3_LH' + str(i) + '-eth0')
        net.addLink('L3_LH' + str(i), S_3_1, intfName2 = 'S_3_1-eth0' + str(i))

    info('*** Management 5 PCs\n')  # Subnet: 10.2.1.0/24   VLAN31
    for i in range(1,6):
        net.addHost('L3_MH' + str(i), cls=Host, ip='10.2.1.' + str(i) + '/24', defaultRoute = 'via 10.2.1.254 dev L3_MH' + str(i) + '-eth0')
        net.addLink('L3_MH' + str(i), S_3_2, intfName2 = 'S_3_2-eth0' + str(i))

    info('*** APs\n')  #subnet: 10.4.0.0/22    VLAN40
    net.addHost('L1AP', cls=Host,ip='10.4.0.1/22', defaultRoute = 'via 10.4.0.254 dev L1AP-eth0')
    net.addHost('L2AP', cls=Host,ip='10.4.0.2/22', defaultRoute = 'via 10.4.0.253 dev L2AP-eth0')
    net.addHost('L3AP', cls=Host,ip='10.4.0.3/22', defaultRoute = 'via 10.4.0.252 dev L3AP-eth0')
    net.addLink('L1AP', S_1_3, intfName2 = 'S_1_3-eth99')
    net.addLink('L2AP', S_2_2, intfName2 = 'S_2_2-eth99')
    net.addLink('L3AP', S_3_3, intfName2 = 'S_3_3-eth99')


    info('*** Network Links\n')

    net.addLink(S_1_1, MLS1, intfName1='S_1_1-eth81', intfName2='MLS1-eth10')  #VLAN10
    net.addLink(S_1_2, MLS1, intfName1='S_1_2-eth81', intfName2='MLS1-eth11')  #VLAN11
    net.addLink(S_1_3, MLS1, intfName1='S_1_3-eth81', intfName2='MLS1-eth12')  #VLAN12 VLAN14 VLAN40
    net.addLink(S_2, MLS1, intfName1='S_2-eth81', intfName2='MLS1-eth20')  #VLAN20
    net.addLink(S_2_2, MLS1, intfName1='S_2_2-eth81', intfName2='MLS1-eth24')  #VLAN40

    net.addLink(S_3_1, MLS1, intfName1='S_3_1-eth81',intfName2='MLS1-eth30') #VLAN30
    net.addLink(S_3_2, MLS1, intfName1='S_3_2-eth81',intfName2='MLS1-eth31') #VLAN31
    net.addLink(S_3_3, MLS1, intfName1='S_3_3-eth81',intfName2='MLS1-eth34') #VLAN40

    net.addLink(S_1_1, MLS2, intfName1='S_1_1-eth91', intfName2='MLS2-eth10')  #VLAN10
    net.addLink(S_1_2, MLS2, intfName1='S_1_2-eth91', intfName2='MLS2-eth11')  #VLAN11
    net.addLink(S_1_3, MLS2, intfName1='S_1_3-eth91', intfName2='MLS2-eth12')  #VLAN12 VLAN14 VLAN40
    net.addLink(S_2, MLS2, intfName1='S_2-eth91', intfName2='MLS2-eth20')  #VLAN20
    net.addLink(S_2_2, MLS2, intfName1='S_2_2-eth91', intfName2='MLS2-eth24')  #VLAN40

    net.addLink(S_3_1, MLS2, intfName1='S_3_1-eth91',intfName2='MLS2-eth30') #VLAN30
    net.addLink(S_3_2, MLS2, intfName1='S_3_2-eth91',intfName2='MLS2-eth31') #VLAN31 VLAN40
    net.addLink(S_3_3, MLS2, intfName1='S_3_3-eth91',intfName2='MLS2-eth34') #VLAN40

    net.addLink(R1, MLS1, intfName1='R1-eth3', intfName2='MLS1-eth100')
    net.addLink(R2, MLS2, intfName1='R2-eth3', intfName2='MLS2-eth100')
    net.addLink(R1, R2, intfName1='R1-eth1',intfName2='R2-eth1')
    net.addLink(ISP,R1 ,intfName1='ISP-eth1', intfName2='R1-eth0')
    net.addLink(ISP,R2 ,intfName1='ISP-eth2', intfName2='R2-eth0')

    info( '*** Starting network\n')
    net.build()
    info( '*** Starting controllers\n')
    for controller in net.controllers:
        controller.start()

    info( '*** Starting switches\n')
    net.start()

    info( '*** Post configure switches and hosts\n')
    #floor2 config
    S_2.cmd("vconfig add S_2-eth81 20")
    S_2_2.cmd("vconfig add S_2_2-eth81 40")

    S_2.cmd("brctl addbr brvlan20")
    S_2_2.cmd("brctl addbr brvlan40")

    S_2.cmd("brctl addif brvlan20 S_2-eth81")
    S_2_2.cmd("brctl addif brvlan40 S_2_2-eth81")
    S_2_2.cmd("brctl addif brvlan40 S_2_2-eth99")
    for i in range(1,11):
        S_2.cmd("brctl addif brvlan20 S_2-eth0" + str(i))

    S_2.cmd("ifconfig brvlan20 up")
    S_2_2.cmd("ifconfig brvlan40 up")

    #floor3 config
    S_3_1.cmd("vconfig add S_3_1-eth81 30")
    S_3_2.cmd("vconfig add S_3_2-eth81 31")
    S_3_3.cmd("vconfig add S_3_3-eth81 40")


    S_3_1.cmd("brctl addbr brvlan30")
    S_3_2.cmd("brctl addbr brvlan31")
    S_3_3.cmd("brctl addbr brvlan40")

    S_3_1.cmd("brctl addif brvlan30 S_3_1-eth81")
    S_3_2.cmd("brctl addif brvlan31 S_3_2-eth81")
    S_3_3.cmd("brctl addif brvlan40 S_3_3-eth81")
    S_3_3.cmd("brctl addif brvlan40 S_3_3-eth99")

    for i in range(1,31):
        S_3_1.cmd("brctl addif brvlan30 S_3_1-eth0" + str(i))
    for i in range(1,6):
        S_3_2.cmd("brctl addif brvlan31 S_3_2-eth0" + str(i))

    S_3_1.cmd("ifconfig brvlan30 up")
    S_3_2.cmd("ifconfig brvlan31 up")
    S_3_3.cmd("ifconfig brvlan40 up")

    # floor1 config
    S_1_1.cmd("vconfig add S_1_1-eth81 10")
    S_1_2.cmd("vconfig add S_1_2-eth81 11")
    S_1_1.cmd("brctl addbr brvlan10")
    S_1_2.cmd("brctl addbr brvlan11")
    S_1_3.cmd("brctl addbr brvlan12")
    S_1_3.cmd("brctl addbr brvlan14")
    S_1_3.cmd("brctl addbr brvlan40")
    S_1_1.cmd("brctl addif brvlan10 S_1_1-eth81")
    S_1_2.cmd("brctl addif brvlan11 S_1_2-eth81")
    S_1_3.cmd("vconfig add S_1_3-eth81 12")
    S_1_3.cmd("vconfig add S_1_3-eth81 14")
    S_1_3.cmd("vconfig add S_1_3-eth81 40")
    S_1_3.cmd("ifconfig S_1_3-eth81.12 up")
    S_1_3.cmd("ifconfig S_1_3-eth81.14 up")
    S_1_3.cmd("ifconfig S_1_3-eth81.40 up")
    S_1_3.cmd("brctl addif brvlan12 S_1_3-eth81.12")
    S_1_3.cmd("brctl addif brvlan14 S_1_3-eth81.14")
    S_1_3.cmd("brctl addif brvlan40 S_1_3-eth81.40")
    for i in range(1, 9):   # Use a for loop to add hosts.
        S_1_1.cmd("brctl addif brvlan10 S_1_1-eth0" + str(i))
    for i in range(1,41):
        S_1_2.cmd("brctl addif brvlan11 S_1_2-eth0" + str(i))
    S_1_3.cmd("brctl addif brvlan12 S_1_3-eth0")
    for i in range(1,11):
        S_1_3.cmd("brctl addif brvlan14 S_1_3-eth1" + str(i))
    S_1_3.cmd("brctl addif brvlan40 S_1_3-eth99")
    S_1_1.cmd("ifconfig brvlan10 up")
    S_1_2.cmd("ifconfig brvlan11 up")
    S_1_3.cmd("ifconfig brvlan12 up")
    S_1_3.cmd("ifconfig brvlan14 up")
    S_1_3.cmd("ifconfig brvlan40 up")

    # MLS1 supporting all the vlans
    MLS1.cmd("vconfig add MLS1-eth10 10")
    MLS1.cmd("vconfig add MLS1-eth11 11")
    MLS1.cmd("vconfig add MLS1-eth12 12")
    MLS1.cmd("vconfig add MLS1-eth12 14")
    MLS1.cmd("vconfig add MLS1-eth12 40")
    MLS1.cmd("vconfig add MLS1-eth20 20")
    MLS1.cmd("vconfig add MLS1-eth24 40")
    MLS1.cmd("vconfig add MLS1-eth30 30")
    MLS1.cmd("vconfig add MLS1-eth31 31")
    MLS1.cmd("vconfig add MLS1-eth34 40")

    # MLS1 configuring the interfaces
    MLS1.cmd("echo 1>/proc/sys/net/ipv4/ip_forward")
    MLS1.cmd("ifconfig MLS1-eth10 10.0.0.254/24")
    MLS1.cmd("ifconfig MLS1-eth11 10.0.1.254/24")
    MLS1.cmd("ifconfig MLS1-eth12.12 10.0.2.254/24")
    MLS1.cmd("ifconfig MLS1-eth12.14 10.0.4.254/24")
    MLS1.cmd("ifconfig MLS1-eth12.40 10.4.0.254/24")
    MLS1.cmd("ifconfig MLS1-eth20 10.1.0.254/24")
    MLS1.cmd("ifconfig MLS1-eth24 10.4.0.253/24")
    MLS1.cmd("ifconfig MLS1-eth30 10.2.0.254/24")
    MLS1.cmd("ifconfig MLS1-eth31 10.2.1.254/24")
    MLS1.cmd("ifconfig MLS1-eth34 10.4.0.252/24")


    MLS1.cmd("ifconfig MLS1-eth100 10.3.2.2/24")
    MLS2.cmd("ifconfig MLS2-eth100 10.3.4.2/24")

    # Routing on ISP, MLS1,2, R1,2
    ISP.cmd("ifconfig ISP-eth1 220.110.0.1/30")
    ISP.cmd("ifconfig ISP-eth2 220.110.0.5/30")
    R1.cmd("ifconfig R1-eth0 220.110.0.2/30")
    R2.cmd("ifconfig R2-eth0 220.110.0.6/30")
    R1.cmd("route add -net 0.0.0.0/0 gw 220.110.0.1")
    R2.cmd("route add -net 0.0.0.0/0 gw 220.110.0.5")
    R1.cmd("ifconfig R1-eth1 10.3.1.1/24")
    R2.cmd("ifconfig R2-eth1 10.3.1.2/24")
    R1.cmd("ifconfig R1-eth3 10.3.2.1/24")
    R2.cmd("ifconfig R2-eth3 10.3.4.1/24")
    MLS1.cmd("route add -net 0.0.0.0/0 gw 10.3.2.1")
    MLS2.cmd("route add -net 0.0.0.0/0 gw 10.3.4.1")
    R1.cmd("route add -net 10.0.0.0/8 gw 10.3.2.2")
    ISP.cmd("route add -net 10.0.0.0/8 gw 220.110.0.2")
    #ISP.cmd("route add -net 10.0.0.0/8 gw 220.110.0.6")





    info('*** Router interface config\n')



    CLI(net)
    net.stop()
Exemple #35
0
def topology():

    "Create a network."
    net = Mininet(controller=Controller, link=TCLink, accessPoint=OVSKernelAP)

    print "*** Creating nodes"
    sta1 = net.addStation('sta1')
    sta2 = net.addStation('sta2')
    ap1 = net.addAccessPoint('ap1',
                             ssid='new-ssid',
                             equipmentModel='DI524',
                             mode='g',
                             channel='1',
                             position='50,50,0')
    c1 = net.addController('c1', controller=Controller)

    print "*** Configuring wifi nodes"
    net.configureWifiNodes()

    print "*** Associating and Creating links"
    net.addLink(ap1, sta1)
    net.addLink(ap1, sta2)

    print "*** Starting network"
    net.build()
    c1.start()
    ap1.start([c1])
    """uncomment to plot graph"""
    net.plotGraph(max_x=100, max_y=100)
    """Seed"""
    net.seed(1)

    "*** Available propagation models: friisPropagationLossModel, twoRayGroundPropagationLossModel, logDistancePropagationLossModel ***"
    net.propagationModel('friisPropagationLossModel', sL=2)

    "*** Available mobility models: RandomWalk, TruncatedLevyWalk, RandomDirection, RandomWayPoint, GaussMarkov ***"
    net.startMobility(startTime=0,
                      model='RandomWayPoint',
                      max_x=100,
                      max_y=100,
                      min_v=0.5,
                      max_v=0.5)

    print "*** Running CLI"
    CLI(net)

    print "*** Stopping network"
    net.stop()
Exemple #36
0
def run():
    "Create control and data networks, and invoke the CLI"

    info('* Creating Control Network\n')
    ctopo = ControlNetwork(n=4, dataController=DataController)
    cnet = Mininet(topo=ctopo, ipBase='192.168.123.0/24', controller=None)
    info('* Adding Control Network Controller\n')
    cnet.addController('cc0', controller=Controller)
    info('* Starting Control Network\n')
    cnet.start()

    info('* Creating Data Network\n')
    topo = TreeTopo(depth=2, fanout=2)
    # UserSwitch so we can easily test failover
    sw = partial(UserSwitch, opts='--inactivity-probe=1 --max-backoff=1')
    net = Mininet(topo=topo, switch=sw, controller=None)
    info('* Adding Controllers to Data Network\n')
    for host in cnet.hosts:
        if isinstance(host, Controller):
            net.addController(host)
    info('* Starting Data Network\n')
    net.start()

    mn = MininetFacade(net, cnet=cnet)

    CLI(mn)

    info('* Stopping Data Network\n')
    net.stop()

    info('* Stopping Control Network\n')
    cnet.stop()
   e) ISP F prefers to use routes announced by E1 but he likes to be
      able to fallback to routes announced by E4 in case the link to
      E1 fails. Similarly, ISP E prefers to use routes announced by F3
      but he likes to be able to fallback to routes announced by F2 in
      case the link to F3 fails. Create filters implementing these
      policies. [2pt]
"""

from mininet.cli import CLI
from mininet.net import Mininet
from mininet.log import setLogLevel

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

    net = Mininet(switch=None, controller=None)

    # Topology of ISP 'f':

    a1 = net.addHost('a1', ip=None)
    a2 = net.addHost('a2', ip=None)
    a3 = net.addHost('a3', ip=None)
    a4 = net.addHost('a4', ip=None)

    f1 = net.addHost('f1', ip=None)
    f1.cmd("sysctl -w net.ipv6.conf.all.forwarding=1")
    f2 = net.addHost('f2', ip=None)
    f2.cmd("sysctl -w net.ipv6.conf.all.forwarding=1")
    f3 = net.addHost('f3', ip=None)
    f3.cmd("sysctl -w net.ipv6.conf.all.forwarding=1")
    f4 = net.addHost('f4', ip=None)
Exemple #38
0
def main():
    global lr, density, fix_choice, max_thrpt
    if len(argv) > 3:
        density = argv[3]
    if len(argv) > 4:
        fix_choice = int(argv[4])
    if len(argv) > 5:
        lr = float(argv[5])
    if len(argv) > 6:
        max_thrpt = float(argv[6])
    timestamp = datetime.datetime.fromtimestamp(
        time.time()).strftime('_%H_%M_%S')
    log = 'lr' + str(lr) + 'alg' + str(fix_choice) + timestamp + '.log'

    rtopo = RTopo()
    net = Mininet(
        topo=rtopo,
        link=TCLink,
        switch=OVSKernelSwitch,
        controller=RemoteController,
        autoSetMacs=True  # --mac
    )
    #c1 = net.addController('c1',controller = RemoteController, ip='127.0.0.1', port = 6633)
    #c1.start()
    #for i in range(1,m+1):
    #    net['s'+str(i)].start([c1])
    c = RemoteController('c', ip='127.0.0.1', port=6633)
    net.addController(c)

    K = 3
    f = open(log, 'w')
    for i in range(K):
        f.write('0\n')
    f.write('@')
    f.close()
    request_file = "default.req"
    if len(argv) > 2:
        request_file = argv[2]
    f = open(request_file, 'r')
    num = int(f.readline())
    cmd.Cmd('sudo rm sender.txt')
    for i in range(1, n + 1):
        cmd.Cmd('sudo rm h{}.txt'.format(i))

    net.start()

    time.sleep(10)
    random.seed(7)
    for i in range(1, n + 1):
        for j in range(1, n + 1):
            if i != j and random.random() > 0.9:
                host1 = 'h' + str(i)
                host2 = 'h' + str(j)
                net[host2].cmd(
                    'sudo python2 ../receive.py {} {} 2>&1>>{}.txt&'.format(
                        4000 + i, 0, 'noise' + host2))
                net[host1].cmd(
                    'sudo python2 ../randomtraffic.py {} {} {} {} 2>&1 >> {}.txt&'
                    .format(random.randint(1, 100), net[host2].IP(), 4000 + i,
                            density, 'traffic' + host1))
    time.sleep(4)

    time0 = time.time()
    for i in range(num):
        starttime, host1, host2, portnum, packagesize = f.readline(
        )[:-1].split()
        starttime = float(starttime) + time0
        net[host2].cmd(
            'sudo python2 ../receive.py {} {} 2>&1>>{}.txt &'.format(
                portnum, starttime, host2))
        net[host1].cmd(
            'sudo python2 ../send.py {} {} {} {} {} {} {} {} 2>&1 >>sender{}.txt&'
            .format(packagesize, net[host2].IP(), portnum, starttime, lr,
                    lr * max_thrpt, fix_choice, log, fix_choice))
    f.close()

    # hosts =[]
    # for i in range(2,4):
    #     hosts.append('h'+str(i))
    # portnum = range(5000+2,5000+4)
    # schedule = np.array(range(2,4))+ time.time() #time

    # #print(type(net['h1']))
    # for t in range(0,2):
    #     net[hosts[t]].cmd('python2 receive.py {} {} 2>&1>>{}.txt &'.format(portnum[t], schedule[t], hosts[t]))
    #     net['h1'].cmd('python2 send.py {} {} {} {} {} 2>&1 >>sender.txt&'.format(100,net[hosts[t]].IP(), portnum[t], schedule[t], 0.1))
    #     tprint net[hosts[t]].IP()
    while True:
        if os.path.isfile(str(num) + ".kill"):
            cmd.Cmd('sudo rm *.kill')
            break
        else:
            time.sleep(0.5)
    net.stop()
Exemple #39
0
def mqttRun():

    dty = setTrial(1, 'mqtt')[0]
    runTime = '20'
    interval = '.1'

    cmds = []
    brokerCommands = [
        'tcpdump -w broker.pcap',
        '{ mosquitto -p 9883 } 2> mosquittoStdout.txt'
    ]
    plantCommands = [
        'tcpdump -w plant.pcap',
        '{ python ../nlmodel_mqtt.py 10.0.0.1 9883 } 2> plantStdout.txt'
    ]
    ctrlCommands = [
        'tcpdump -w controller.pcap',
        '{ python ../nlcontroller.py mqtt bar 10.0.0.1 9883 controlOutput 20 .1  6.09 3.5 -5.18 -12.08 6.58 -0.4 } 2> controllerStdout.txt'
    ]

    #will the broker always be there?

    lossPct = 0
    delay = '10ms'
    waitTime = 22

    topo = myTopo(Lpct=lossPct, D=delay, wait=waitTime)
    net = Mininet(topo=topo,
                  host=CPULimitedHost,
                  link=TCLink,
                  autoStaticArp=True)

    net.start()
    info("Dumping host connections\n")
    dumpNodeConnections(net.hosts)

    #Logging commands
    fout = open(dty + '/commands.txt', 'w')
    fout.write('Loss Percent: ' + str(lossPct) + '\n')
    fout.write('Delay: ' + str(delay) + '\n')
    fout.write('Wait time: ' + str(waitTime) + '\n\n')
    fout.close()

    from datetime import datetime
    start = datetime.now()

    for i in range(3):
        net.getNodeByName('h%s' % (i + 1)).cmd('cd ' + dty)
    #sending out all the commands

    net.getNodeByName('h1').cmd('python ../runCommands.py ' +
                                str(waitTime + 2) + '  ' +
                                toArg(brokerCommands) + ' &')
    net.getNodeByName('h2').cmd('python ../runCommands.py ' +
                                str(waitTime + 1) + '  ' +
                                toArg(plantCommands) + ' &')
    net.getNodeByName('h3').cmd('python ../runCommands.py ' + str(waitTime) +
                                '  ' + toArg(ctrlCommands) + ' &')

    time.sleep(waitTime + 3)
    #    net.getNodeByName('h1').sendCmd('mosquitto -p 9888 > mosquittoOutput.txt')
    #    net.getNodeByName('h1').sendCmd('ifconfig > ifcfig.txt')
    #    net.getNodeByName('h2').sendCmd(cmds[1])
    #    net.getNodeByName('h3').sendCmd(cmds[2])

    #

    end = datetime.now()
    fout = open(dty + '/time.txt', 'w')
    fout.write('Start: ' + start.strftime('%b-%d-%H:%M.%S') + '\n')
    fout.write('End: ' + end.strftime('%b-%d-%H:%M.%S') + '\n')

    #CLI(net)
    net.stop()
Exemple #40
0
def myNetwork():
    net = Mininet(topo=None, build=False, ipBase='10.0.0.0/8')
    info('*** Adding controller\n')
    c0 = net.addController(name='c0',
                           controller=RemoteController,
                           protocol='tcp',
                           port=6653)
    info('*** Add switches\n')
    s2 = net.addSwitch('s2',
                       cls=OVSKernelSwitch,
                       protocols='OpenFlow15',
                       ip="10.0.0.3")
    s1 = net.addSwitch('s1',
                       cls=OVSKernelSwitch,
                       protocols='OpenFlow15',
                       ip="10.0.0.4")
    print("ssss")
    #s2.cmd('sudo ethtool -s s2-eth1 speed 100')
    info('*** Add hosts\n')
    h1 = net.addHost('h1',
                     cls=Host,
                     ip='10.0.0.1',
                     defaultRoute="via 140.128.102.174")
    h2 = net.addHost('h2', cls=Host, ip='10.0.0.2', defaultRoute=None)
    meter = 0 * 1000
    delay = "100ms"
    info('*** Add links\n')
    #https://github.com/mininet/mininet/blob/de28f67a97fc8915cc1586c984465d89a016d8eb/mininet/link.py#L314
    net.addLink(s1,
                h1,
                cls=TCLink,
                bw=1000,
                jitter="0ms",
                delay="0ms",
                loss=0,
                max_queue_size=55)
    net.addLink(h2,
                s2,
                cls=TCLink,
                bw=1000,
                jitter="0ms",
                delay="0ms",
                loss=0,
                max_queue_size=55)

    net.addLink(s1,
                s2,
                port1=10,
                port2=10,
                cls=TCLink,
                bw=1,
                jitter="0ms",
                delay="300ms",
                loss=0,
                max_queue_size=None)
    net.addLink(s1,
                s2,
                port1=11,
                port2=11,
                cls=TCLink,
                bw=1,
                jitter="0ms",
                delay="200ms",
                loss=0,
                max_queue_size=None)
    net.addLink(s1,
                s2,
                port1=12,
                port2=12,
                cls=TCLink,
                bw=1,
                jitter="0ms",
                delay="0ms",
                loss=0,
                max_queue_size=None)
    net.addLink(s1,
                s2,
                port1=14,
                port2=14,
                cls=TCLink,
                bw=1,
                jitter="0ms",
                delay="0ms",
                loss=0,
                max_queue_size=None)
    #mininet 的delay,jitter,loss底層是依靠netem(Network Emulation)模擬
    #由於mininet底層呼叫netem時沒有設定jitter的分佈狀態,所以netem依照默認設定是normal(常態分佈)
    #https://git.kernel.org/pub/scm/network/iproute2/iproute2.git/tree/man/man8/tc-netem.8#n89

    #在netem指令之下jitter可以設定三種
    #https://git.kernel.org/pub/scm/network/iproute2/iproute2.git/tree/man/man8/tc-netem.8#n23
    #uniform " | " normal " | " pareto " |  " paretonormal

    #net.addLink(s1, s2,port1=888,port2=321,cls=TCLink, bw=1000,jitter="450ms",delay="0.75s",loss=11,max_queue_size=23)
    #print(str(l),"****jjjjjjjjjjjjjjjjjj****")
    #net.addLink(s1, s2,port1=433,port2=32232,cls=TCLink, bw=10,jitter="0ms",delay="0s",loss=0,max_queue_size=2223)

    #print(a)
    #a.cmd("sudo ethtool -s s1-eth1 speed 100")
    #a.cmd("sudo ethtool -s s2-eth1 speed 100")

    info('*** Starting network\n')
    net.build()
    ##
    #print(s1.cmd('sudo ethtool -s s1-eth888 speed 1000'))
    #s1.cmd('sudo ethtool -s s1-eth433 speed 10')
    #s1.cmd('sudo ethtool -s s2-eth321 speed 1000')
    #s1.cmd('sudo ethtool -s s2-eth32232 speed 10')
    #s2.cmd('sudo ethtool -s s2-eth32232 speed 1000')

    #print(s1.cmd('sudo ethtool -s s2-eth1 speed 1000000'))
    ##
    info('*** Starting controllers\n')
    for controller in net.controllers:
        controller.start()

    info('*** Starting switches\n')
    #net.get('s2').start([c0])
    net.get('s1').start([c0])
    net.get('s2').start([c0])

    info('*** Post configure switches and hosts\n')
    #net.pingAll(0.1)
    import time

    CLI(net)

    net.stop()
def myNetwork():

    net = Mininet( topo=None,
                   build=False,
                   ipBase='10.0.0.0/8')

    info( '*** Adding controller\n' )
    c0=net.addController(name='c0',
                      controller=RemoteController,
                      ip='127.0.0.1',
                      protocol='tcp',
                      port=6653)

    info( '*** Add switches\n')
    s2 = net.addSwitch('s2', cls=OVSKernelSwitch)
    s1 = net.addSwitch('s1', cls=IVSSwitch)

    info( '*** Add hosts\n')
    h2 = net.addHost('h2', cls=Host, ip='10.0.0.2', defaultRoute=None)
    h1 = net.addHost('h1', cls=Host, ip='10.0.0.1', defaultRoute=None)
    h3 = net.addHost('h3', cls=Host, ip='10.0.0.3', defaultRoute=None)

    info( '*** Add links\n')
    s1s2 = {'bw':400,'loss':0}
    net.addLink(s1, s2, cls=TCLink , **s1s2)
    s2h1 = {'bw':1000,'loss':10,'max_queue_size':10,'speedup':40}
    net.addLink(s2, h1, cls=TCLink , **s2h1)
    s2h2 = {'bw':120,'loss':0}
    net.addLink(s2, h2, cls=TCLink , **s2h2)
    s2h3 = {'bw':400,'loss':20}
    net.addLink(s2, h3, cls=TCLink , **s2h3)

    info( '*** Starting network\n')
    net.build()
    info( '*** Starting controllers\n')
    for controller in net.controllers:
        controller.start()

    info( '*** Starting switches\n')
    net.get('s2').start([c0])
    net.get('s1').start([c0])

    info( '*** Post configure switches and hosts\n')

    CLI(net)
    net.stop()
Exemple #42
0
def Start(OFDM_R=9, UDP=True, TP=9, PCAP=False):
    setLogLevel('info')
    #info( '*** ns-3 network demo\n' )
    net = Mininet()

    #info( '*** Creating Network\n' )
    h0 = net.addHost('h0')
    h1 = net.addHost('h1')
    h2 = net.addHost('h2')
    h3 = net.addHost('h3')
    h4 = net.addHost('h4')
    h5 = net.addHost('h5')

    wifi = WIFISegment()

    #CONFIGURATION
    udp = UDP
    bandwidth = 20
    ofdm_r = "OfdmRate" + str(OFDM_R) + "Mbps"
    OfdmRate = ofdm_r  #9,24,48
    if udp == False:
        #TCP
        payloadSize = 1448  #bytes
        ns.core.Config.SetDefault("ns3::TcpSocket::SegmentSize",
                                  ns.core.UintegerValue(payloadSize))
    else:
        payloadSize = 1472

    wifi = WIFISegment()

    wifi.wifihelper.SetStandard(ns.wifi.WIFI_PHY_STANDARD_80211a)

    wifi.wifihelper.SetRemoteStationManager(
        "ns3::ConstantRateWifiManager", "DataMode",
        ns.core.StringValue(OfdmRate), "ControlMode",
        ns.core.StringValue("OfdmRate9Mbps"))

    Sssid = "wifi-80211a"

    wifi.addSta(h0, ssid=Sssid)
    wifi.addSta(h1, ssid=Sssid)
    wifi.addSta(h2, ssid=Sssid)
    wifi.addSta(h3, ssid=Sssid)
    wifi.addSta(h4, ssid=Sssid)
    wifi.addAp(h5, ssid=Sssid)

    # set channel bandwidth
    ns.core.Config.Set(
        "/NodeList/*/DeviceList/*/$ns3::WifiNetDevice/Phy/ChannelWidth",
        ns.core.UintegerValue(bandwidth))

    if PCAP == True:
        wifi.phyhelper.EnablePcap("80211a_sta1.pcap", h0.nsNode.GetDevice(0),
                                  True, True)
        wifi.phyhelper.EnablePcap("80211a_sta2.pcap", h1.nsNode.GetDevice(0),
                                  True, True)
        wifi.phyhelper.EnablePcap("80211a_sta3.pcap", h2.nsNode.GetDevice(0),
                                  True, True)
        wifi.phyhelper.EnablePcap("80211a_sta4.pcap", h3.nsNode.GetDevice(0),
                                  True, True)
        wifi.phyhelper.EnablePcap("80211a_sta5.pcap", h4.nsNode.GetDevice(0),
                                  True, True)
        wifi.phyhelper.EnablePcap("80211a_ap.pcap", h5.nsNode.GetDevice(0),
                                  True, True)

    #info( '*** Configuring hosts\n' )
    h0.setIP('192.168.123.1/24')
    h1.setIP('192.168.123.2/24')
    h2.setIP('192.168.123.3/24')
    h3.setIP('192.168.123.4/24')
    h4.setIP('192.168.123.5/24')
    h5.setIP('192.168.123.6/24')

    mininet.ns3.start()

    #info( '\n *** Testing network connectivity\n' )
    net.pingFull([h0, h5])
    #net.pingFull([h1,h2])
    #net.pingFull([h0,h1])
    info('*** Starting UDP iperf server on AP(h5)\n')
    h5.sendCmd("iperf -s -i 1 -u")
    info(
        '*** Testing bandwidth between h0 and h5 while others stas are not transmitting\n'
    )
    val = "iperf -c 192.168.123.6 -u -b " + str(TP) + "M"
    h0.cmdPrint(val)
    info(
        '*** Testing bandwidth between h0 and h5 while all stats are also transmitting\n'
    )
    val = "iperf -c 192.168.123.6 -u -b " + str(TP) + "M"
    h0.sendCmd(val)
    h1.sendCmd(val)
    h2.sendCmd(val)
    h3.sendCmd(val)
    h4.cmdPrint(val)
Exemple #43
0
from mininet.link import TCLink


class CustomTopo(Topo):
    def __init__(self, bw=1e3, **opts):
        super(CustomTopo, self).__init__(**opts)

        s = [self.addSwitch('s%d' % n) for n in range(1, 4)]
        h = [self.addHost('h%d' % n) for n in range(1, 5)]

        self.addLink(s[0], s[1], bw=bw)
        self.addLink(s[0], s[2], bw=bw)
        self.addLink(s[2], s[1], bw=bw)

        self.addLink(h[0], s[0], bw=bw)
        self.addLink(h[1], s[0], bw=bw)
        self.addLink(h[2], s[1], bw=bw)
        self.addLink(h[3], s[1], bw=bw)


if __name__ == '__main__':
    net = Mininet(topo=CustomTopo(),
                  controller=RemoteController,
                  cleanup=True,
                  autoSetMacs=True,
                  autoStaticArp=True,
                  link=TCLink)
    net.start()
    CLI(net)
    net.stop()
def main():

    with open(args.manifest, 'r') as f:
        manifest = json.load(f)

    conf = manifest['targets'][args.target]
    params = conf['parameters'] if 'parameters' in conf else {}

    os.environ.update(dict(map(lambda (k, v): (k, str(v)),
                               params.iteritems())))

    def formatParams(s):
        for param in params:
            s = re.sub('\$' + param + '(\W|$)', str(params[param]) + r'\1', s)
            s = s.replace('${' + param + '}', str(params[param]))
        return s

    AppTopo = apptopo.AppTopo
    AppController = appcontroller.AppController

    if 'topo_module' in conf:
        sys.path.insert(0, os.path.dirname(args.manifest))
        topo_module = importlib.import_module(conf['topo_module'])
        AppTopo = topo_module.CustomAppTopo

    if 'controller_module' in conf:
        sys.path.insert(0, os.path.dirname(args.manifest))
        controller_module = importlib.import_module(conf['controller_module'])
        AppController = controller_module.CustomAppController

    if not os.path.isdir(args.log_dir):
        if os.path.exists(args.log_dir):
            raise Exception('Log dir exists and is not a dir')
        os.mkdir(args.log_dir)
    os.environ['P4APP_LOGDIR'] = args.log_dir

    links = [l[:2] for l in conf['links']]
    latencies = dict([(''.join(sorted(l[:2])), l[2]) for l in conf['links']
                      if len(l) >= 3])
    bws = dict([(''.join(sorted(l[:2])), l[3]) for l in conf['links']
                if len(l) >= 4])

    for host_name in sorted(conf['hosts'].keys()):
        host = conf['hosts'][host_name]
        if 'latency' not in host: continue
        for a, b in links:
            if a != host_name and b != host_name: continue
            other = a if a != host_name else b
            latencies[host_name + other] = host['latency']

    for l in latencies:
        if isinstance(latencies[l], (str, unicode)):
            latencies[l] = formatParams(latencies[l])
        else:
            latencies[l] = str(latencies[l]) + "ms"

    bmv2_log = args.bmv2_log or ('bmv2_log' in conf and conf['bmv2_log'])
    pcap_dump = args.pcap_dump or ('pcap_dump' in conf and conf['pcap_dump'])

    topo = AppTopo(links,
                   latencies,
                   manifest=manifest,
                   target=args.target,
                   log_dir=args.log_dir,
                   bws=bws)
    switchClass = configureP4Switch(sw_path=args.behavioral_exe,
                                    json_path=args.json,
                                    log_console=bmv2_log,
                                    pcap_dump=pcap_dump)
    net = Mininet(topo=topo,
                  link=TCLink,
                  host=P4Host,
                  switch=switchClass,
                  controller=None)
    net.start()

    sleep(1)

    controller = None
    if args.auto_control_plane or 'controller_module' in conf:
        controller = AppController(manifest=manifest,
                                   target=args.target,
                                   topo=topo,
                                   net=net,
                                   links=links)
        controller.start()

    for h in net.hosts:
        h.describe()

    if args.cli_message is not None:
        with open(args.cli_message, 'r') as message_file:
            print message_file.read()

    if args.cli or ('cli' in conf and conf['cli']):
        #for host in net.hosts:
        #h = host.name.split('h')[1]
        #int_h = int(h)
        #cmd = 'python send_ntp_response.py 1 %s 1 %s 1 0 &' % (str(int_h-1),str(int_h-1))
        #print cmd
        #info(host.cmd(cmd))
        CLI(net)

    stdout_files = dict()
    return_codes = []
    host_procs = []

    def formatCmd(cmd):
        for h in net.hosts:
            cmd = cmd.replace(h.name, h.defaultIntf().updateIP())
        return cmd

    def _wait_for_exit(p, host):
        print p.communicate()
        if p.returncode is None:
            p.wait()
            print p.communicate()
        return_codes.append(p.returncode)
        if host_name in stdout_files:
            stdout_files[host_name].flush()
            stdout_files[host_name].close()

    print '\n'.join(map(lambda (k, v): "%s: %s" %
                        (k, v), params.iteritems())) + '\n'

    for host_name in sorted(conf['hosts'].keys()):
        host = conf['hosts'][host_name]
        if 'cmd' not in host: continue

        h = net.get(host_name)
        stdout_filename = os.path.join(args.log_dir, h.name + '.stdout')
        stdout_files[h.name] = open(stdout_filename, 'w')
        cmd = formatCmd(host['cmd'])
        print h.name, cmd
        p = h.popen(cmd,
                    stdout=stdout_files[h.name],
                    shell=True,
                    preexec_fn=os.setpgrp)
        if 'startup_sleep' in host: sleep(host['startup_sleep'])

        if 'wait' in host and host['wait']:
            _wait_for_exit(p, host_name)
        else:
            host_procs.append((p, host_name))

    for p, host_name in host_procs:
        if 'wait' in conf['hosts'][host_name] and conf['hosts'][host_name][
                'wait']:
            _wait_for_exit(p, host_name)

    for p, host_name in host_procs:
        if 'wait' in conf['hosts'][host_name] and conf['hosts'][host_name][
                'wait']:
            continue
        if p.returncode is None:
            run_command('pkill -INT -P %d' % p.pid)
            sleep(0.2)
            rc = run_command('pkill -0 -P %d' %
                             p.pid)  # check if it's still running
            if rc == 0:  # the process group is still running, send TERM
                sleep(1)  # give it a little more time to exit gracefully
                run_command('pkill -TERM -P %d' % p.pid)
        _wait_for_exit(p, host_name)

    if 'after' in conf and 'cmd' in conf['after']:
        cmds = conf['after']['cmd'] if type(
            conf['after']['cmd']) == list else [conf['after']['cmd']]
        for cmd in cmds:
            os.system(cmd)

    if controller: controller.stop()

    net.stop()

    #    if bmv2_log:
    #        os.system('bash -c "cp /tmp/p4s.s*.log \'%s\'"' % args.log_dir)
    #    if pcap_dump:
    #        os.system('bash -c "cp *.pcap \'%s\'"' % args.log_dir)

    bad_codes = [rc for rc in return_codes if rc != 0]
    if len(bad_codes): sys.exit(1)
Exemple #45
0
from mininet.cli import CLI
from mininet.link import Link
from mininet.net import Mininet
from mininet.node import RemoteController
from mininet.term import makeTerm
from mininet.node import UserSwitch
from mininet.link import TCLink

if '__main__' == __name__:
    net = Mininet(controller=RemoteController)

    c0 = net.addController('c0', ip="127.0.0.1")

    s1 = net.addSwitch('s1', cls=UserSwitch)
    #s2 = net.addSwitch('s2',cls=UserSwitch)

    h1 = net.addHost('h1')
    h2 = net.addHost('h2', mac='00:00:00:00:00:22')
    h3 = net.addHost('h3', mac='00:00:00:00:00:23')
    h4 = net.addHost('h4', mac='00:00:00:00:00:24')

    #TCLink(s1, s2, bw=1)
    #TCLink(s1, s2, bw=1)
    TCLink(s1, h1, bw=1)
    TCLink(s1, h1, bw=1)
    TCLink(s1, h2, bw=1)
    TCLink(s1, h3, bw=1)
    TCLink(s1, h4, bw=1)

    #TCLink(s2, h1, bw=1)
Exemple #46
0
def main(cli=0):
    net = Mininet( controller = None )

    # add hosts
    h1 = net.addHost( 'h1', ip = '172.16.10.1/24' )
    h2 = net.addHost( 'h2', ip = '172.16.10.2/24' )

    # add switch 1
    sw1 = net.addSwitch( 'sw1', target_name = "p4dockerswitch",
            cls = P4DockerSwitch, config_fs = 'configs/sw1/stp',
            pcap_dump = True )

    # add switch 2
    sw2 = net.addSwitch( 'sw2', target_name = "p4dockerswitch",
            cls = P4DockerSwitch, config_fs = 'configs/sw2/stp',
            pcap_dump = True )

    # add switch 3
    sw3 = net.addSwitch( 'sw3', target_name = "p4dockerswitch",
            cls = P4DockerSwitch, config_fs = 'configs/sw3/stp',
            pcap_dump = True )

    # add switch 4
    sw4 = net.addSwitch( 'sw4', target_name = "p4dockerswitch",
            cls = P4DockerSwitch, config_fs = 'configs/sw4/stp',
            pcap_dump = True )

    # add links
    if StrictVersion(VERSION) <= StrictVersion('2.2.0') :
        net.addLink( sw1, h1, port1 = 1 )
        net.addLink( sw2, h2, port1 = 1 )
        net.addLink( sw1, sw3, port1 = 2, port2 = 1 )
        net.addLink( sw1, sw4, port1 = 3, port2 = 1 )
        net.addLink( sw2, sw3, port1 = 2, port2 = 2 )
        net.addLink( sw2, sw4, port1 = 3, port2 = 2 )
        net.addLink( sw3, sw4, port1 = 3, port2 = 3 )
    else:
        net.addLink( sw1, h1, port1 = 1, fast = False )
        net.addLink( sw2, h2, port1 = 1, fast = False )
        net.addLink( sw1, sw3, port1 = 2, port2 = 1, fast = False )
        net.addLink( sw1, sw4, port1 = 3, port2 = 1, fast = False )
        net.addLink( sw2, sw3, port1 = 2, port2 = 2, fast = False )
        net.addLink( sw2, sw4, port1 = 3, port2 = 2, fast = False )
        net.addLink( sw3, sw4, port1 = 3, port2 = 3, fast = False )

    net.start()
    result = 0

    if cli:
        CLI( net )
    else:
        sleep(30)

        node_values = net.values()
        print node_values
        hosts = net.hosts
        print hosts

        print "PING BETWEEN THE HOSTS"
        result = net.ping(hosts, 30)
        # print host arp table & routes
        for host in hosts:
            print "ARP ENTRIES ON HOST"
            print host.cmd('arp -n')
            print "HOST ROUTES"
            print host.cmd('route')
            print "HOST INTERFACE LIST"
            intfList = host.intfNames()
            print intfList

        if result != 0:
            print "PING FAILED BETWEEN HOSTS %s"  % (hosts)
        else:
            print "PING SUCCESSFUL!!!"

    net.stop()
    return result
Exemple #47
0
def topology():

    "Create a network."
    net = Mininet(controller=Controller, link=TCLink, switch=OVSKernelSwitch)
    staList = []

    print "*** Creating nodes"
    for n in range(10):
        staList.append(n)
        staList[n] = net.addStation('sta%s' % (n + 1),
                                    wlans=2,
                                    mac='00:00:00:00:00:%s' % (n + 1),
                                    ip='192.168.0.%s/24' % (n + 1))
    phyap1 = net.addPhysicalBaseStation('phyap1',
                                        ssid='SBRC16-MininetWiFi',
                                        mode='g',
                                        channel='1',
                                        position='50,115,0',
                                        phywlan='wlan11')
    sta11 = net.addStation('sta11', ip='10.0.0.111/8', position='120,200,0')
    ap2 = net.addBaseStation('ap2',
                             ssid='ap2',
                             mode='g',
                             channel='11',
                             position='100,175,0')
    ap3 = net.addBaseStation('ap3',
                             ssid='ap3',
                             mode='g',
                             channel='6',
                             position='150,50,0')
    ap4 = net.addBaseStation('ap4',
                             ssid='ap4',
                             mode='g',
                             channel='1',
                             position='175,150,0')
    c1 = net.addController('c1', controller=Controller, port=6653)
    root = Node('root', inNamespace=False)

    print "*** Creating links"
    for sta in staList:
        net.addMesh(sta, ssid='meshNet')
    """uncomment to plot graph"""
    net.plotGraph(max_x=240, max_y=240)
    """Routing"""
    net.meshRouting('custom')
    """Seed"""
    net.seed(20)

    print "*** Associating and Creating links"
    net.addLink(phyap1, ap2)
    net.addLink(ap2, ap3)
    net.addLink(ap3, ap4)

    print "*** Starting network"
    net.build()
    c1.start()
    phyap1.start([c1])
    ap2.start([c1])
    ap3.start([c1])
    ap4.start([c1])

    ip = 201
    for sta in staList:
        sta.setIP('10.0.0.%s/8' % ip, intf="%s-wlan1" % sta)
        ip += 1

    "*** Available models: RandomWalk, TruncatedLevyWalk, RandomDirection, RandomWayPoint, GaussMarkov, ReferencePoint, TimeVariantCommunity ***"
    net.startMobility(startTime=0,
                      model='RandomWalk',
                      max_x=220,
                      max_y=220,
                      min_v=0.1,
                      max_v=0.2)

    print "*** Running CLI"
    CLI(net)

    print "*** Stopping network"
    net.stop()
Exemple #48
0
        self.addLink(s1, s2)
        self.addLink(s1, s3)
        self.addLink(s2, h1)
        self.addLink(s2, h2)
        self.addLink(s3, h3)
        self.addLink(s3, h4)
        self.addLink(s1, dpi)


# topos = { 'mytopo': (lambda: MyTopo()) }
if __name__ == '__main__':
    setLogLevel('info')

    # Init Topo with no controller
    topo = MyTopo()
    net = Mininet(topo, autoSetMacs=False, controller=None)

    # Add controller with specific ip and port
    c = RemoteController('c', '0.0.0.0', 6633)
    net.addController(c)

    # nat custom settings must be set before configDefault()
    nat = net.addNAT()
    nat.setMAC('00:00:00:FF:00:00')
    nat.configDefault()

    # strat net
    net.start()
    CLI(net)
    net.stop()
aux_array = []
aux = []

serversEnabled = False

name_files = []
name_files_server = []
json_data = ''
#Variables para la generacion de trafico ITG

hots_receiver = None
host_sender = None

# Creacion de la red en Mininet
net = Mininet(build=False)


def wireshark_launcher():
    run_wireshark = subprocess.call(['wireshark-gtk', '-S'])
        
# Creacion del hilo para lanzar Wireshark
w = threading.Thread(target=wireshark_launcher,)

@app.route('/',methods=['GET'])
def get():
    return 'Este es el Sevidor Mininet by Atlas'

@app.route('/',methods=['POST'])
def executor():
    global serversEnabled, aux_array, name_files, name_files_server, aux, json_data, tstart, linkeados, net, host_added, switch_added,controller_added
Exemple #50
0
def myNetwork():

    net = Mininet( topo=None,
                   build=False,
                   ipBase='10.0.0.0/8')

    info( '*** Adding controller\n' )
    c0=net.addController(name='c0',
                      controller=RemoteController,
                      ip='127.0.0.1',
                      protocol='tcp',
                      port=6633)

    info( '*** Add switches\n')
    s4 = net.addSwitch('s4', cls=OVSKernelSwitch)
    s3 = net.addSwitch('s3', cls=OVSKernelSwitch)
    s5 = net.addSwitch('s5', cls=OVSKernelSwitch)
    s2 = net.addSwitch('s2', cls=OVSKernelSwitch)
    s1 = net.addSwitch('s1', cls=OVSKernelSwitch)

    info( '*** Add hosts\n')
    h6 = net.addHost('h6', cls=Host, ip='10.0.0.6', defaultRoute=None)
    h2 = net.addHost('h2', cls=Host, ip='10.0.0.2', defaultRoute=None)
    h4 = net.addHost('h4', cls=Host, ip='10.0.0.4', defaultRoute=None)
    h5 = net.addHost('h5', cls=Host, ip='10.0.0.5', defaultRoute=None)
    h3 = net.addHost('h3', cls=Host, ip='10.0.0.3', defaultRoute=None)
    h1 = net.addHost('h1', cls=Host, ip='10.0.0.1', defaultRoute=None)

    info( '*** Add links\n')
    net.addLink(h1, s1)
    net.addLink(h2, s1)
    net.addLink(s2, s1)
    net.addLink(s2, s3)
    net.addLink(s3, s4)
    net.addLink(s3, s5)
    net.addLink(s5, h5)
    net.addLink(s5, h6)
    net.addLink(s4, h4)
    net.addLink(s4, h3)

    info( '*** Starting network\n')
    net.build()
    info( '*** Starting controllers\n')
    for controller in net.controllers:
        controller.start()

    info( '*** Starting switches\n')
    net.get('s4').start([c0])
    net.get('s3').start([c0])
    net.get('s5').start([c0])
    net.get('s2').start([c0])
    net.get('s1').start([c0])

    info( '*** Post configure switches and hosts\n')

    CLI(net)
    net.stop()
        s5 = self.addSwitch('s5')
        self.addLink(h1, s1)
        self.addLink(h2, s2)
        self.addLink(h3, s3)
        self.addLink(h4, s4)
        self.addLink(h5, s5)
        self.addLink(s1, s2, bw=20, delay='40ms')
        self.addLink(s1, s3, bw=40, delay='10ms')
        self.addLink(s1, s4, bw=30, delay='30ms')
        self.addLink(s1, s5, bw=25, delay='20ms')
        self.addLink(s2, s3, bw=25, delay='15ms')
        self.addLink(s2, s4, bw=25, delay='25ms')
        self.addLink(s2, s5, bw=25, delay='10ms')
        self.addLink(s3, s4, bw=25, delay='25ms')
        self.addLink(s3, s5, bw=25, delay='20ms')
        self.addLink(s4, s5, bw=25, delay='15ms')
        
if __name__ == '__main__':
    setLogLevel( 'info' )

    # Create data network
    topo = AssignmentNetworks()
    net = Mininet(topo=topo, link=TCLink, autoSetMacs=True,
           autoStaticArp=True)

    # Run network
    net.start()
    CLI( net )
    net.stop()

Exemple #52
0
def WifiNet(inputFile):

    # enable mptcp
    call(["sudo", "sysctl", "-w", "net.mptcp.mptcp_enabled=1"])

    input = open(inputFile, "r")
    """ Node names """
    max_outgoing = []
    hosts = []
    switches = []  # satellite and dummy satellite
    links = []
    sw_name = []
    portCount = {}  # count the current eth usage of a host/switch
    linkToPort = {}  # map link to certain ethernets of src and dst

    flows = []
    routingConfig = []
    queue_num = 1
    num_host = 0
    num_ship = 0
    num_sat = 0

    line = input.readline()
    # Add nodes
    while line.strip() != "End":
        action, type_node, target = line.strip().split()
        if type_node == "host:":
            hosts.append(target)
            num_host += 1
        else:
            if type_node == "ship:":
                num_ship += 1
                max_outgoing.append(0)
            elif type_node == "hub:":
                num_sat += 1
            switches.append(target)
        line = input.readline()

    # Add links
    line = input.readline()
    while line.strip() != "End":
        action, type_node, end1, end2 = line.strip().split()
        if end1[0] == "s" and int(end1[1:]) <= num_ship and end2[0] == "s":
            max_outgoing[int(end1[1:]) - 1] += 1
        links.append([end1, end2])
        line = input.readline()

    print(max_outgoing)

    # Routing table of hosts
    line = input.readline()
    while line.strip() != "End":
        host, st, num_ip = line.strip().split()
        file = open(host + ".sh", "w")
        file.write("#!/bin/bash\n\n")
        for i in range(0, int(num_ip)):
            ipaddr = input.readline().strip()
            intf = host + "-eth" + str(i)
            file.write("ifconfig " + intf + " " + ipaddr +
                       " netmask 255.255.255.255\n")
            file.write("ip rule add from " + ipaddr + " table " + str(i + 1) +
                       "\n")
            file.write("ip route add " + ipaddr + "/32 dev " + intf +
                       " scope link table " + str(i + 1) + "\n")
            file.write("ip route add default via " + ipaddr + " dev " + intf +
                       " table " + str(i + 1) + "\n")
            if i == 0:
                file.write("ip route add default scope global nexthop via " +
                           ipaddr + " dev " + intf + "\n")
        file.close()
        call(["sudo", "chmod", "777", host + ".sh"])
        line = input.readline()

    input.close()
    net = Mininet(link=TCLink, controller=None, autoSetMacs=True)

    nodes = {}
    """ Initialize Ships """
    for host in hosts:
        node = net.addHost(host)
        nodes[host] = node
    """ Initialize SATCOMs """
    for switch in switches:
        node = net.addSwitch(switch)
        nodes[switch] = node
    print(links)
    """ Add links """
    for link in links:
        name1, name2 = link[0], link[1]
        node1, node2 = nodes[name1], nodes[name2]
        if (name1 == 's6' and name2 == 's9'):
            net.addLink(node1, node2, bw=30)
            info('set *************************')
        elif (name1 == 's7' and name2 == 's10'):
            net.addLink(node1, node2, bw=20)
        elif (name1 == 's8' and name2 == 's11'):
            net.addLink(node1, node2, bw=15)
        else:
            net.addLink(node1, node2)
    """ Start the simulation """
    info('*** Starting network ***\n')
    net.start()

    #  set all ships
    for i in range(0, num_host):
        src = nodes[hosts[i]]
        info("--configing routing table of " + hosts[i])
        if os.path.isfile(hosts[i] + '.sh'):
            src.cmdPrint('./' + hosts[i] + '.sh')

    info('*** start test ***\n')

    time.sleep(3)
    info('*** set flow tables ***\n')
    call(["sudo", "bash", "MPTCPFlowTable.sh"])

    # start D-ITG Servers

    for i in [2, 5, 8, 11, 14]:
        srv = nodes[hosts[i]]
        info("starting D-ITG servers...\n")
        srv.cmdPrint("cd ~/D-ITG-2.8.1-r1023/bin")
        srv.cmdPrint("./ITGRecv &")

    time.sleep(1)

    # start D-ITG application
    # set simulation time

    sTime = 60000  # default 120,000ms
    for i in range(0, 10):
        # normal requirement
        senderList = [0, 1, 3, 4, 6, 7, 9, 10, 12, 13]
        recvList = [11, 14, 2, 8, 5, 11, 5, 8, 2, 11]
        # bwReq = [6,4,7,3,4,4,3,3,3,3]

        # large requirement
        bwReq = [2, 12, 3, 3, 5, 5, 12, 2, 12, 2]
        ITGTest(senderList[i], recvList[i], hosts, nodes, bwReq[i] * 125,
                sTime)
        time.sleep(0.2)

    info("running simulaiton...\n")
    info("please wait...\n")

    time.sleep(sTime / 1000)

    # You need to change the path here
    call(["sudo", "python", "../analysis/analysis.py"])
    # CLI(net)

    net.stop()
    info('*** net.stop()\n')
Exemple #53
0
class NetworkManager():
  def __init__(self, host_cfgs, switch_cfgs, link_cfgs):
    self.net = Mininet( controller = None, link = TCLinkCustom )
    self.link_cfgs = link_cfgs
    self.host_cfgs = dict()
    self.switch_cfgs = dict()
    self.ip_addr = dict() # Cache of ip addr instances

    for h in host_cfgs:
      self.host_cfgs[h.name] = h

    for s in switch_cfgs:
      self.switch_cfgs[s.name] = s

  def setupAndStartNetwork(self):
    self.addHosts()
    self.addSwitches()
    self.addLinks()
    self.net.start()

    print 'Waiting 10 seconds for switches to intialize...'
    time.sleep(10)
 
    self.configSwitches()
    self.configHostRoutesAndArp()
    self.configINTSourcesAndSinks()
    self.setupHostToMonitorConns()
    self.startHostPreprocessors()
    
    print 'Waiting 20 seconds for Quagga to learn routes...'
    time.sleep(20)

    self.startPingMesh()

    return self.net
    
  def addHosts(self):
    for h in self.host_cfgs.values():
      ip_with_prefix = "%s/%d" % (h.ip, h.prefix_len)
      self.net.addHost( h.name, cls = h.cls, mac = h.mac, ip = ip_with_prefix ) 

  def addSwitches(self):
    for s in self.switch_cfgs.values():
      print( "Adding switch %s" % s.name )
      if s.cls == Bmv2DockerSwitch:
	fs_map = [[ os.path.join( os.getcwd(), s.config_fs ), '/configs' ]]
	port_map = [[ s.swapi_port, 9091 ],
                    [ s.bmcli_port, 10001 ]]
        self.net.addSwitch(
          s.name, model_dir = s.model_dir,
	  pcap_dump = s.pcap_dump, 
          image = s.docker_name, cls       = s.cls,
	  fs_map    = fs_map, port_map    = port_map, 
          pps = s.pps, qdepth = s.qdepth )
      else:
        self.net.addSwitch(
          s.name,
          target_name = s.target_name, cls       = s.cls, 
          swapi_port  = s.swapi_port,  pcap_dump = s.pcap_dump,
          target_dir  = s.target_dir,
          pps = s.pps, qdepth = s.qdepth)

  def addLinks(self):
    for l in self.link_cfgs:
      n1 = self.net.get( l.node1 )
      n2 = self.net.get( l.node2 )
      if StrictVersion(VERSION) <= StrictVersion('2.2.0') :
        if l.port2 != None:
          self.net.addLink( n1, n2, port1 = l.port1 + 1, port2 = l.port2 + 1, bw=5)
        else:
          self.net.addLink( n1, n2, port1 = l.port1 + 1, bw=5)
      else:
        if l.port2 != None:
          self.net.addLink( n1, n2, port1 = l.port1 + 1, port2 = l.port2 + 1, fast=False, bw=5)
        else:
          self.net.addLink( n1, n2, port1 = l.port1 + 1, fast=False, bw=5)

  def configINTSourcesAndSinks(self):
    for c1 in self.host_cfgs.values():
      if c1.vxlan_cfg != None:
        vc = c1.vxlan_cfg
        h = self.net.get( c1.name )
        h.cmd( "brctl addbr testbr0" )
        h.cmd( "ip link add vxlan0 type vxlan id %d group %s dev eth0" % ( vc.vni, vc.group ))
        h.cmd( "brctl addif testbr0 vxlan0" )
        h.cmd( "ifconfig vxlan0 up" )
        h.cmd( "ifconfig testbr0 up" )
        h.cmd( "ip link add veth0 type veth peer name veth1" )
        h.cmd( "ifconfig veth0 %s/%d up" % ( vc.ip, vc.prefix_len ))
        h.cmd( "ifconfig veth0 mtu %d" % vc.mtu )
        h.cmd( "ifconfig veth1 up" )
        h.cmd( "ip link set dev veth0 address %s" % vc.veth_mac )
        h.cmd( "brctl addif testbr0 veth1" )

    for c1 in self.host_cfgs.values():
      if c1.vxlan_cfg != None:
        vc = c1.vxlan_cfg
        for c2 in self.host_cfgs.values():
          if ( c2 != c1 ) and (c2.vxlan_cfg != None):
            h = self.net.get( c2.name )
            h.cmd( "arp -s %s %s" % ( vc.ip, vc.veth_mac ))
            h.cmd( "bridge fdb add to %s dst %s dev vxlan0 via eth0" % ( vc.veth_mac, c1.ip ))

  def configHostRoutesAndArp(self):
    for l in self.link_cfgs:
      if l.port2 == None:
        sw = self.switch_cfgs[l.node1]
        h = self.net.get(l.node2)
        port = sw.port_cfgs[l.port1]
        h.cmd("route add default gw %s" % port.ip)

  def configSwitches(self):
    for s in self.switch_cfgs.values():
      self.configSwitch(s)
    self.startQuaggaOnSwitches()

  def startQuaggaOnSwitches(self):
    print "Starting quagga on switches"
    for s in self.switch_cfgs.values():
      sw = self.net.get(s.name)
      sw.cmd("service quagga start")

  def configSwitch(self, cfg):
    device = 0
    transport, client = open_connection( cfg.swapi_port )
    print "INT Config ", cfg.name

    client.switcht_api_init( device )

    client.switcht_int_transit_enable( device, cfg.switch_id, 1 )

    close_connection( transport )

  def setupHostToMonitorConns(self):
    runOnNativeHost("brctl addbr testbr1")

    i = 21
    for hn in self.host_cfgs:
      h = self.net.get(hn) 
      vm_eth_intf = 'vm-eth%s' % i
      vm_eth_intf_ip = '192.168.1.%d' % i
      h_eth_intf  = '%s-vm-eth%d' % (h.name, i)
      h_eth_intf_ip = '192.168.1.%d' % (i * 2)
      runOnNativeHost('ip link add %s type veth peer name %s' % (h_eth_intf, vm_eth_intf))
      runOnNativeHost('ip link set %s netns %d' % (h_eth_intf, h.shell.pid))
      runOnNativeHost('brctl addif testbr1 %s' % vm_eth_intf)

      h.cmd('ifconfig %s up' % h_eth_intf)
      h.cmd('ifconfig %s %s/24' % (h_eth_intf, h_eth_intf_ip))
      runOnNativeHost('ifconfig %s up' % vm_eth_intf)

      i = i + 1

    runOnNativeHost("ip link add veth-t1 type veth peer name veth-t2")
    runOnNativeHost("brctl addif testbr1 veth-t1")
    runOnNativeHost("ifconfig veth-t1 up")
    runOnNativeHost("ifconfig veth-t2 up")
    runOnNativeHost("ifconfig veth-t2 192.168.1.100")
    runOnNativeHost("ifconfig testbr1 up")

    runOnNativeHost("../apps/int/monitor/monitor.py > tmp_monitor 2>&1 &")
    runOnNativeHost("../apps/int/monitor/client_msg_handler.py > tmp_client_msg_handler 2>&1 &")

  def startHostPreprocessors(self):
    for c in self.host_cfgs.values():
      h = self.net.get(c.name)
      cmd = "../apps/int/monitor/preprocessor.py %s > tmp_%s 2>&1 &" % (c.ip, c.name)
      print(cmd)
      h.cmd(cmd)

  def cleanup(self):
    for i in range(len(self.host_cfgs)):
      runOnNativeHost('ip link delete vm-eth%d' % (i + 21))
    runOnNativeHost('ip link delete veth-t1')
    runOnNativeHost('ifconfig testbr1 down')
    runOnNativeHost('brctl delbr testbr1')

  # Helper functions
  def get_ip_addr_handle(self, ip, prefix_len):
    k = (ip, prefix_len)
    if (k in self.ip_addr):
      return self.ip_addr[k]

    h = switcht_ip_addr_t(ipaddr = ip, prefix_length = prefix_len)
    self.ip_addr[k] = h

    return h

  def startPingMesh(self):
    print "Starting ping mesh sessions"
    for c1 in self.host_cfgs.values():
      if c1.vxlan_cfg != None:
        h = self.net.get( c1.name )
        for c2 in self.host_cfgs.values():
          if (c2.name != c1.name and c2.vxlan_cfg != None):
            vc = c2.vxlan_cfg
            h.cmd ( "ping %s > /dev/null &" % (vc.ip) )
            print h.name + " pinging " + vc.ip
def myNetwork():

    net = Mininet(topo=None, link=TCLink, build=False, ipBase='10.0.0.0/8')

    info('*** Adding controller\n')
    c0 = net.addController(name='c0',
                           controller=RemoteController,
                           ip='127.0.0.1',
                           protocol='tcp',
                           port=6633)

    info('*** Add switches\n')
    s1 = net.addSwitch('s1', cls=OVSKernelSwitch)
    s2 = net.addSwitch('s2', cls=OVSKernelSwitch)
    s3 = net.addSwitch('s3', cls=OVSKernelSwitch)
    s4 = net.addSwitch('s4', cls=OVSKernelSwitch)

    info('*** Add hosts\n')
    h1 = net.addHost('h1', cls=Host, ip='10.0.0.1', defaultRoute=None)
    h2 = net.addHost('h2', cls=Host, ip='10.0.0.2', defaultRoute=None)
    h3 = net.addHost('h3', cls=Host, ip='10.0.0.3', defaultRoute=None)
    h4 = net.addHost('h4', cls=Host, ip='10.0.0.4', defaultRoute=None)

    info('*** Add links\n')
    net.addLink(s1, h1, bw=50, loss=3)
    net.addLink(s1, h2, bw=100, delay='2ms', loss=0)
    net.addLink(s4, h3, bw=50, delay='2ms', loss=0)
    net.addLink(s4, h4, bw=100, loss=2)

    net.addLink(s1, s2, bw=90, loss=2)
    net.addLink(s1, s3, bw=90, delay='2ms', loss=0)
    net.addLink(s4, s2, bw=40, loss=3)
    net.addLink(s4, s3, bw=40, delay='2ms', loss=0)

    info('*** Starting network\n')
    net.build()
    info('*** Starting controllers\n')
    for controller in net.controllers:
        controller.start()

    info('*** Starting switches\n')
    net.get('s1').start([c0])
    net.get('s2').start([c0])
    net.get('s3').start([c0])
    net.get('s4').start([c0])

    info('*** Post configure switches and hosts\n')
    CLI(net)
    net.stop()
Exemple #55
0
from mininet.net import Mininet
from mininet.node import Node, Switch
from mininet.link import Link, Intf
from mininet.log import setLogLevel, info
from mininet.cli import CLI

import mininet.ns3
from mininet.ns3 import TBIntf

import ns.network

if __name__ == '__main__':
    setLogLevel('info')
    info('*** ns-3 network demo\n')
    net = Mininet()

    info('*** Creating Network\n')
    h0 = net.addHost('h0')
    h1 = net.addHost('h1')
    h2 = net.addHost('h2')

    #   NS part ------------------------------------------------------

    channel = ns.network.SimpleChannel()

    h0ns = ns.network.Node()
    device0 = ns.network.SimpleNetDevice()
    device0.SetChannel(channel)
    h0ns.AddDevice(device0)

    h1ns = ns.network.Node()
Exemple #56
0
def DeltaNetwork():
#Make topology
        net = Mininet(topo=None, controller=None, build=False)

#Add switch
        proto = sys.argv[5]
        s0 = net.addSwitch('s0', dpid='00:00:00:00:00:01', protocols=proto)
        s1 = net.addSwitch('s1', dpid='00:00:00:00:00:02', protocols=proto)
        s2 = net.addSwitch('s2', dpid='00:00:00:00:00:03', protocols=proto)
        s3 = net.addSwitch('s3') # for connection with DELTA

#Add hosts
        h1 = net.addHost('h1', ip='10.0.0.1/24', mac='00:00:00:00:00:11')
        h2 = net.addHost('h2', ip='10.0.0.2/24', mac='00:00:00:00:00:22')

#Add links
        net.addLink(s0, h1)
        net.addLink(s2, h2)
        net.addLink(s0, s1)
        net.addLink(s1, s2)

        net.addLink(s3, h1, intfName2='eth0')

#       net.build()
        net.start()

#Add hardware interface to switch1
        s3.attach('eth0')

#Set ip
        os.system("sudo ovs-ofctl add-flow s3 in_port=1,actions=output:2")
        os.system("sudo ovs-ofctl add-flow s3 in_port=2,actions=output:1")

        h1.cmd("ifconfig eth0 10.0.2.10/24 netmask 255.255.255.0")
        #h1.cmd("dhclient eth0")

#connect a controller
        os.system("sudo ovs-vsctl set-controller s0 tcp:"+sys.argv[1]+":"+sys.argv[2])
        os.system("sudo ovs-vsctl set-controller s1 tcp:"+sys.argv[1]+":"+sys.argv[2])
        os.system("sudo ovs-vsctl set-controller s2 tcp:"+sys.argv[1]+":"+sys.argv[2])

        h1.cmd("java -jar $HOME/delta-agent-host-1.0-SNAPSHOT.jar "+sys.argv[3]+" "+sys.argv[4])
        CLI(net)
        net.stop()
def topology():
	"Create a network."
	net = Mininet(controller=Controller, link=TCLink, switch=OVSKernelSwitch, accessPoint=OVSKernelAP)
	global gnet
	gnet = net

	print "*** Creating nodes"
	car = []
	stas = []
	for x in range(0, 4):
		car.append(x)
		stas.append(x)
	for x in range(0, 4):
		car[x] = net.addCar('car%s' % (x), wlans=2, ip='10.0.0.%s/8' % (x + 1), \
		mac='00:00:00:00:00:0%s' % x, mode='b')
    
	eNodeB1 = net.addAccessPoint('eNodeB1', ssid='eNodeB1', dpid='1000000000000000', mode='ac', channel='1', position='80,75,0', range=60)
	eNodeB2 = net.addAccessPoint('eNodeB2', ssid='eNodeB2', dpid='2000000000000000', mode='ac', channel='6', position='180,75,0', range=70)
	rsu1 = net.addAccessPoint('rsu1', ssid='rsu1', dpid='3000000000000000', mode='g', channel='11', position='140,120,0', range=40)
	c1 = net.addController('c1', controller=Controller)
	client = net.addHost ('client')
	switch = net.addSwitch ('switch', dpid='4000000000000000')

	net.plotNode(client, position='125,230,0')
	net.plotNode(switch, position='125,200,0')

	print "*** Configuring wifi nodes"
	net.configureWifiNodes()

	print "*** Creating links"
	net.addLink(eNodeB1, switch)
	net.addLink(eNodeB2, switch)
	net.addLink(rsu1, switch)
	net.addLink(switch, client)

	print "*** Starting network"
	net.build()
	c1.start()
	eNodeB1.start([c1])
	eNodeB2.start([c1])
	rsu1.start([c1])
	switch.start([c1])

	for sw in net.vehicles:
		sw.start([c1])

	i = 1
	j = 2
	for c in car:
		c.cmd('ifconfig %s-wlan0 192.168.0.%s/24 up' % (c, i))
		c.cmd('ifconfig %s-eth0 192.168.1.%s/24 up' % (c, i))
		c.cmd('ip route add 10.0.0.0/8 via 192.168.1.%s' % j)
		i += 2
		j += 2

	i = 1
	j = 2
	for v in net.vehiclesSTA:
		v.cmd('ifconfig %s-eth0 192.168.1.%s/24 up' % (v, j))
		v.cmd('ifconfig %s-mp0 10.0.0.%s/24 up' % (v, i))
		v.cmd('echo 1 > /proc/sys/net/ipv4/ip_forward')
		i += 1
		j += 2

	for v1 in net.vehiclesSTA:
		i = 1
		j = 1
		for v2 in net.vehiclesSTA:
			if v1 != v2:
				v1.cmd('route add -host 192.168.1.%s gw 10.0.0.%s' % (j, i))
			i += 1
			j += 2

	client.cmd('ifconfig client-eth0 200.0.10.2')
	net.vehiclesSTA[0].cmd('ifconfig car0STA-eth0 200.0.10.50')

	car[0].cmd('modprobe bonding mode=3')
	car[0].cmd('ip link add bond0 type bond')
	car[0].cmd('ip link set bond0 address 02:01:02:03:04:08')
	car[0].cmd('ip link set car0-eth0 down')
	car[0].cmd('ip link set car0-eth0 address 00:00:00:00:00:11')
	car[0].cmd('ip link set car0-eth0 master bond0')
	car[0].cmd('ip link set car0-wlan0 down')
	car[0].cmd('ip link set car0-wlan0 address 00:00:00:00:00:15')
	car[0].cmd('ip link set car0-wlan0 master bond0')
	car[0].cmd('ip link set car0-wlan1 down')
	car[0].cmd('ip link set car0-wlan1 address 00:00:00:00:00:13')
	car[0].cmd('ip link set car0-wlan1 master bond0')
	car[0].cmd('ip addr add 200.0.10.100/24 dev bond0')
	car[0].cmd('ip link set bond0 up')

	car[3].cmd('ifconfig car3-wlan0 200.0.10.150')

	client.cmd('ip route add 192.168.1.8 via 200.0.10.150')
	client.cmd('ip route add 10.0.0.1 via 200.0.10.150')

	net.vehiclesSTA[3].cmd('ip route add 200.0.10.2 via 192.168.1.7')
	net.vehiclesSTA[3].cmd('ip route add 200.0.10.100 via 10.0.0.1')
	net.vehiclesSTA[0].cmd('ip route add 200.0.10.2 via 10.0.0.4')

	car[0].cmd('ip route add 10.0.0.4 via 200.0.10.50')
	car[0].cmd('ip route add 192.168.1.7 via 200.0.10.50')
	car[0].cmd('ip route add 200.0.10.2 via 200.0.10.50')
	car[3].cmd('ip route add 200.0.10.100 via 192.168.1.8')

	"""plot graph"""
	net.plotGraph(max_x=250, max_y=250)

	net.startGraph()

	# STREAMING commands
	car[0].cmdPrint("cvlc -vvv bunnyMob.mp4 --sout '#duplicate{dst=rtp{dst=200.0.10.2,port=5004,mux=ts},dst=display}' :sout-keep &")
	car[0].cmdPrint("echo $!") # PID of latest bg process
	client.cmdPrint("cvlc rtp://200.0.10.2:5004/bunnyMob.mp4 &")
	client.cmdPrint("echo $!")

	car[0].moveNodeTo('95,100,0')
	car[1].moveNodeTo('80,100,0')
	car[2].moveNodeTo('65,100,0')
	car[3].moveNodeTo('50,100,0')

	os.system('ovs-ofctl del-flows switch')

	time.sleep(3)

	#apply_experiment(car,client,switch,net) # DOKIMH XWRIS FUNCTION
	time.sleep(2)
	print "Applying first phase"
	os.system('ovs-ofctl mod-flows switch in_port=1,actions=output:4')
	os.system('ovs-ofctl mod-flows switch in_port=4,actions=output:1')

	car[0].cmd('ip route add 200.0.10.2 via 200.0.10.50')
	client.cmd('ip route add 200.0.10.100 via 200.0.10.150')
	#me aftes edw tis entoles pane ta mhnymata #gia kapoio logo de tis dexetai mesa apo python 
	#client.cmd('ip route add 200.0.10.100 via 200.0.10.2')
	#car[0].cmd('ip route add 200.0.10.2 via 200.0.10.100')

	CLI(net)#kanw xterm client ,car0 kai tis prosthetw

	#ifconfig output gathering
	#~ t_end = time.time() + 21 #gia 20 seconds 
	#~ print time.time()
	print "ifonfig output gathering"
	t_simulation = 0
	while t_simulation < 20:
		car[0].cmd('ifconfig bond0 | grep \"TX packets\" >> %s' % packets_t_car0)
		car[0].cmd('ifconfig bond0 | grep \"TX bytes\" >> %s' % bytes_t_car0)
		car[3].cmd('ifconfig car3-eth0 | grep \"RX packets\" >> %s' % packets_r_car3)
		car[3].cmd('ifconfig car3-eth0 | grep \"RX bytes\" >> %s' % bytes_r_car3)

		car[3].cmd('ifconfig car3-wlan0 | grep \"TX packets\" >> %s' % packets_t_car3)
		car[3].cmd('ifconfig car3-wlan0 | grep \"TX bytes\" >> %s' % bytes_t_car3)
		client.cmd('ifconfig client-eth0 | grep \"RX packets\" >> %s' % packets_r_client)
		client.cmd('ifconfig client-eth0 | grep \"RX bytes\" >> %s' % bytes_r_client)
		time.sleep(1)
		t_simulation=t_simulation+1    

	#iperf output gathering
	client.cmdPrint('iperf -s -u -i 1 > %s &' % iperf_out_srv)
	car[0].cmdPrint('iperf -u -i 1 -t 20 -c 200.0.10.2')
	#client.cmdPrint('sudo kill -9 $!') #skotwnw th diergasia tou iperf ston client
	
	#ping output gathering
	#~ car[3].cmd('ping -t 1 -c 20 200.0.10.100 > %s' % ping_v2v) #ping sto car3->car0
	#~ car[3].cmd('ping -t 1 -c 20 200.0.10.2 > %s' % ping_v2i) #ping sto car3->client
	car[0].cmd('ping -t 1 -c 20 200.0.10.2 > %s' % car0_pings_client)
	client.cmd('ping -t 1 -c 20 200.0.10.100 > %s' % client_pings_car0)
    
	graphic1()
	print "xterm client -> sudo kill -9 <client_iperf_bg_process_PID>"
	CLI(net)

	#end of phase 1 
	print "Moving nodes"
	car[0].moveNodeTo('150,100,0')
	car[1].moveNodeTo('120,100,0')
	car[2].moveNodeTo('90,100,0')
	car[3].moveNodeTo('70,100,0')

	time.sleep(2)
	print "Applying second phase"

	os.system('ovs-ofctl del-flows switch')
	os.system('ovs-ofctl mod-flows switch in_port=2,actions=output:4')
	os.system('ovs-ofctl mod-flows switch in_port=4,actions=output:2')
	os.system('ovs-ofctl mod-flows switch in_port=3,actions=output:4')
	os.system('ovs-ofctl mod-flows switch in_port=4,actions=output:3')

	#~ mallon prepei ksana xterm client car0 kai tis parakatw
	#~ client.cmd('route add -host 200.0.10.100 gw 200.0.10.2')
	#~ car[0].cmd('route add -host 200.0.10.2 gw 200.0.10.100')
	#~ telika tis eixe akomh perasmenes apo to prohgoumeno xterm client car0

	print "ifonfig output gathering"
	t_simulation = 0
	while t_simulation < 20:
		car[0].cmd('ifconfig bond0 | grep \"TX packets\" >> %s' % packets2_t_car0)
		car[0].cmd('ifconfig bond0 | grep \"TX bytes\" >> %s' % bytes2_t_car0)
		client.cmd('ifconfig client-eth0 | grep \"RX packets\" >> %s' % packets2_r_client)
		client.cmd('ifconfig client-eth0 | grep \"RX bytes\" >> %s' % bytes2_r_client)
		time.sleep(1)
		t_simulation=t_simulation+1    

	print 'iperf output gathering'
	#CLI(net)
	client.cmdPrint('iperf -s -u -i 1 > %s &' % iperf2_out_srv)
	car[0].cmdPrint('iperf -u -i 1 -t 20 -c 200.0.10.2')
	#client.cmdPrint('sudo kill -9 $!') #skotwnw th diergasia tou iperf ston client
	
	print 'ping output gathering'
	#~ car[3].cmd('ping -t 1 -c 20 200.0.10.100 > %s' % ping_v2v) #ping sto car3->car0
	#~ car[3].cmd('ping -t 1 -c 20 200.0.10.2 > %s' % ping_v2i) #ping sto car3->client
	car[0].cmd('ping -t 1 -c 20 200.0.10.2 > %s' % car0_pings2_client)
	client.cmd('ping -t 1 -c 20 200.0.10.100 > %s' % client_pings2_car0)
	

	graphic2()
	time.sleep(2)
    #################################################################################
    
	print "Moving nodes"
	car[0].moveNodeTo('190,100,0')
	car[1].moveNodeTo('150,100,0')
	car[2].moveNodeTo('120,100,0')
	car[3].moveNodeTo('90,100,0')

	time.sleep(2)
	print "Applying third phase"
    
    ################################################################################ 
    #   1) Add the flow rules below and routing commands if needed
	os.system('ovs-ofctl del-flows switch')
	os.system('ovs-ofctl mod-flows switch in_port=2,actions=output:4')
	os.system('ovs-ofctl mod-flows switch in_port=4,actions=output:2')

    #   2) Calculate Network Measurements using IPerf or command line tools(ifconfig)
    #       Hint: Remember that you can insert commands via the mininet
    #       Example: car[0].cmd('ifconfig bond0 | grep \"TX packets\" >> %s' % output.data)
	print "*** CLI 3 *** -- check if streaming is happening(eNodeB2 only) (car0 ping client)"
	print "ifonfig output gathering"
	t_simulation = 0
	while t_simulation < 20:
		car[0].cmd('ifconfig bond0 | grep \"TX packets\" >> %s' % packets3_t_car0)
		car[0].cmd('ifconfig bond0 | grep \"TX bytes\" >> %s' % bytes3_t_car0)
		client.cmd('ifconfig client-eth0 | grep \"RX packets\" >> %s' % packets3_r_client)
		client.cmd('ifconfig client-eth0 | grep \"RX bytes\" >> %s' % bytes3_r_client)
		time.sleep(1)
		t_simulation=t_simulation+1    

	print 'iperf output gathering'
	CLI(net)
	client.cmdPrint('iperf -s -u -i 1 > %s &' % iperf3_out_srv)
	car[0].cmdPrint('iperf -u -i 1 -t 20 -c 200.0.10.2')
	#client.cmdPrint('sudo kill -9 $!') #skotwnw th diergasia tou iperf ston client
	
	print 'ping output gathering'
	#~ car[3].cmd('ping -t 1 -c 20 200.0.10.100 > %s' % ping_v2v) #ping sto car3->car0
	#~ car[3].cmd('ping -t 1 -c 20 200.0.10.2 > %s' % ping_v2i) #ping sto car3->client
	car[0].cmd('ping -t 1 -c 20 200.0.10.2 > %s' % car0_pings3_client)
	client.cmd('ping -t 1 -c 20 200.0.10.100 > %s' % client_pings3_car0)

    # Uncomment the line below to generate the graph that you implemented
	graphic3()
#	time.sleep(5) #na prolavei na fortwsei ta figures
    # kills all the xterms that have been opened
#    os.system('pkill xterm')

#    print "*** Running CLI"
	print "last CLI before closing"
	CLI(net)

	print "*** Stopping network"
	net.stop()
Exemple #58
0
def emptyNet(nHost, nSwitch):

    "Create an empty network and add nodes to it."

    net = Mininet(controller=Controller)

    info('*** Adding controller ***\n')
    net.addController('c0')

    info('*** Adding hosts\n')
    odd = []
    even = []
    arr = []
    for i in range(nHost):
        if i % 2 == 0:
            randomN = random.randint(1, 50000)
            h1 = net.addHost('h' + str(i), ip=subnet1 + str(i + 1))
            s = 'h' + str(i)
            arr.append({s: randomN})
            odd.append(h1)
        else:
            h2 = net.addHost('h' + str(i), ip=subnet2 + str(i + 1))
            randomN = random.randint(1, 50000)
            s = 'h' + str(i)
            arr.append({s: randomN})
            even.append(h2)
    print 'Host name and their id are as follows : '
    print arr
    # h1 = net.addHost( 'h1', ip= ip1  )
    # h2 = net.addHost( 'h2', ip= ip2 )

    info('*** Adding switch\n')
    switch = []
    for i in range(nSwitch):
        s3 = net.addSwitch('s' + str(i + 1))
        switch.append(s3)


#    s3 = net.addSwitch( 's3' )

    info('*** Creating links\n')
    for i in range(nSwitch):
        a = net.addLink(odd[i], switch[i])
        a.intf1.config(bw=2)
        b = net.addLink(even[i], switch[i])
        b.intf1.config(bw=1)

    for i in range(nSwitch - 1):
        net.addLink(switch[i], switch[i + 1])

    # net.addLink( h1, s3 )
    # net.addLink( h2, s3 )

    info('*** Starting network\n')
    net.start()

    info('*** Running CLI\n')
    CLI(net)

    info('*** Stopping network')
    net.stop()
Exemple #59
0
def mainTopo():
    #Define Initial Topology on Mininet
    os.system('mn -c')
    print(
        '==========================================================================='
    )
    print(
        '==========================================================================='
    )
    net = Mininet(link=TCLink, host=CPULimitedHost)
    net.start()

    Cl1 = net.addHost('Cl1', ip='192.168.1.2/24')
    Cl2 = net.addHost('Cl2', ip='192.168.2.2/24')
    Cl3 = net.addHost('Cl3', ip='192.168.3.2/24')
    Cl4 = net.addHost('Cl4', ip='192.168.4.2/24')
    Cl5 = net.addHost('Cl5', ip='192.168.5.2/24')
    Cl6 = net.addHost('Cl6', ip='192.168.6.2/24')
    Cl7 = net.addHost('Cl7', ip='192.168.7.2/24')
    Cl8 = net.addHost('Cl8', ip='192.168.8.2/24')

    Se1 = net.addHost('Se1', ip='192.168.10.2/24')
    Se2 = net.addHost('Se2', ip='192.168.20.2/24')
    Se3 = net.addHost('Se3', ip='192.168.30.2/24')
    Se4 = net.addHost('Se4', ip='192.168.40.2/24')
    Se5 = net.addHost('Se5', ip='192.168.50.2/24')
    Se6 = net.addHost('Se6', ip='192.168.60.2/24')
    Se7 = net.addHost('Se7', ip='192.168.70.2/24')
    Se8 = net.addHost('Se8', ip='192.168.80.2/24')

    Ro1 = net.addHost('Router1')

    net.addLink(Cl1, Ro1, bw=100)
    net.addLink(Cl2, Ro1, bw=100)
    net.addLink(Cl3, Ro1, bw=100)
    net.addLink(Cl4, Ro1, bw=100)
    net.addLink(Cl5, Ro1, bw=100)
    net.addLink(Cl6, Ro1, bw=100)
    net.addLink(Cl7, Ro1, bw=100)
    net.addLink(Cl8, Ro1, bw=100)

    net.addLink(Se1, Ro1, bw=BW)  #, max_queue_size = maxQ
    net.addLink(Se2, Ro1, bw=BW)  #
    net.addLink(Se3, Ro1, bw=BW)  #
    net.addLink(Se4, Ro1, bw=BW)  #
    net.addLink(Se5, Ro1, bw=BW)  #
    net.addLink(Se6, Ro1, bw=BW)  #
    net.addLink(Se7, Ro1, bw=BW)  #
    net.addLink(Se8, Ro1, bw=BW)  #

    net.build()
    print(
        '==========================================================================='
    )
    print(
        '==========================================================================='
    )
    Ro1.cmd('ifconfig Router1-eth0 0')
    Ro1.cmd('ifconfig Router1-eth1 0')
    Ro1.cmd('ifconfig Router1-eth2 0')
    Ro1.cmd('ifconfig Router1-eth3 0')
    Ro1.cmd('ifconfig Router1-eth4 0')
    Ro1.cmd('ifconfig Router1-eth5 0')
    Ro1.cmd('ifconfig Router1-eth6 0')
    Ro1.cmd('ifconfig Router1-eth7 0')
    Ro1.cmd('ifconfig Router1-eth8 0')
    Ro1.cmd('ifconfig Router1-eth9 0')
    Ro1.cmd('ifconfig Router1-eth10 0')
    Ro1.cmd('ifconfig Router1-et11 0')
    Ro1.cmd('ifconfig Router1-eth12 0')
    Ro1.cmd('ifconfig Router1-eth13 0')
    Ro1.cmd('ifconfig Router1-eth14 0')
    Ro1.cmd('ifconfig Router1-eth15 0')

    Ro1.cmd('ifconfig Router1-eth0')
    Ro1.cmd('ifconfig Router1-eth1')
    Ro1.cmd('ifconfig Router1-eth2')
    Ro1.cmd('ifconfig Router1-eth3')
    Ro1.cmd('ifconfig Router1-eth4')
    Ro1.cmd('ifconfig Router1-eth5')
    Ro1.cmd('ifconfig Router1-eth6')
    Ro1.cmd('ifconfig Router1-eth7')
    Ro1.cmd('ifconfig Router1-eth8')
    Ro1.cmd('ifconfig Router1-eth9')
    Ro1.cmd('ifconfig Router1-eth10')
    Ro1.cmd('ifconfig Router1-eth11')
    Ro1.cmd('ifconfig Router1-eth12')
    Ro1.cmd('ifconfig Router1-eth13')
    Ro1.cmd('ifconfig Router1-eth14')
    Ro1.cmd('ifconfig Router1-eth15')

    Ro1.cmd("ip addr add 192.168.1.1/24 brd + dev Router1-eth0")
    Ro1.cmd("ip addr add 192.168.2.1/24 brd + dev Router1-eth1")
    Ro1.cmd("ip addr add 192.168.3.1/24 brd + dev Router1-eth2")
    Ro1.cmd("ip addr add 192.168.4.1/24 brd + dev Router1-eth3")
    Ro1.cmd("ip addr add 192.168.5.1/24 brd + dev Router1-eth4")
    Ro1.cmd("ip addr add 192.168.6.1/24 brd + dev Router1-eth5")
    Ro1.cmd("ip addr add 192.168.7.1/24 brd + dev Router1-eth6")
    Ro1.cmd("ip addr add 192.168.8.1/24 brd + dev Router1-eth7")

    Ro1.cmd("ip addr add 192.168.10.1/24 brd + dev Router1-eth8")
    Ro1.cmd("ip addr add 192.168.20.1/24 brd + dev Router1-eth9")
    Ro1.cmd("ip addr add 192.168.30.1/24 brd + dev Router1-eth10")
    Ro1.cmd("ip addr add 192.168.40.1/24 brd + dev Router1-eth11")
    Ro1.cmd("ip addr add 192.168.50.1/24 brd + dev Router1-eth12")
    Ro1.cmd("ip addr add 192.168.60.1/24 brd + dev Router1-eth13")
    Ro1.cmd("ip addr add 192.168.70.1/24 brd + dev Router1-eth14")
    Ro1.cmd("ip addr add 192.168.80.1/24 brd + dev Router1-eth15")

    Ro1.cmd('sysctl -w net.ipv4.ip_forward=1')

    Cl1.cmd('ip route add default via 192.168.1.1')
    Cl2.cmd('ip route add default via 192.168.2.1')
    Cl3.cmd('ip route add default via 192.168.3.1')
    Cl4.cmd('ip route add default via 192.168.4.1')
    Cl5.cmd('ip route add default via 192.168.5.1')
    Cl6.cmd('ip route add default via 192.168.6.1')
    Cl7.cmd('ip route add default via 192.168.7.1')
    Cl8.cmd('ip route add default via 192.168.8.1')

    Se1.cmd('ip route add default via 192.168.10.1')
    Se2.cmd('ip route add default via 192.168.20.1')
    Se3.cmd('ip route add default via 192.168.30.1')
    Se4.cmd('ip route add default via 192.168.40.1')
    Se5.cmd('ip route add default via 192.168.50.1')
    Se6.cmd('ip route add default via 192.168.60.1')
    Se7.cmd('ip route add default via 192.168.70.1')
    Se8.cmd('ip route add default via 192.168.80.1')

    print(
        '=================STARTING SCENARIO 4 (Bufferbloat 8 Device)======================='
    )
    print(
        '==========================================================================='
    )
    Cl1.cmdPrint('sysctl  net.ipv4.tcp_congestion_control')
    Se2.cmdPrint('sysctl  net.ipv4.tcp_congestion_control')
    print("QUEUE_SIZE", maxQ)
    print("LINK_BANDWIDTH, RO-SE ", BW)
    ccName = subprocess.check_output(
        'cat /proc/sys/net/ipv4/tcp_congestion_control', shell=True)
    ccName = ccName.replace("\n", "")

    print(
        '==========================================================================='
    )

    net.pingAll()
    print(
        '==========================================================================='
    )

    # Se2.cmd('iperf -s &')
    Se1.cmd('iperf -s  > dataResult/examine5/' + str(ccName) + '_' +
            str(maxQ) + '_' + str(BW) + '_LL_iperf-server1.txt &')
    Se2.cmd('iperf -s  > dataResult/examine5/' + str(ccName) + '_' +
            str(maxQ) + '_' + str(BW) + '_LL_iperf-server2.txt &')
    Se3.cmd('iperf -s  > dataResult/examine5/' + str(ccName) + '_' +
            str(maxQ) + '_' + str(BW) + '_LL_iperf-server3.txt &')
    Se4.cmd('iperf -s  > dataResult/examine5/' + str(ccName) + '_' +
            str(maxQ) + '_' + str(BW) + '_LL_iperf-server4.txt &')
    Se5.cmd('iperf -s  > dataResult/examine5/' + str(ccName) + '_' +
            str(maxQ) + '_' + str(BW) + '_LL_iperf-server5.txt &')
    Se6.cmd('iperf -s  > dataResult/examine5/' + str(ccName) + '_' +
            str(maxQ) + '_' + str(BW) + '_LL_iperf-server6.txt &')
    Se7.cmd('iperf -s  > dataResult/examine5/' + str(ccName) + '_' +
            str(maxQ) + '_' + str(BW) + '_LL_iperf-server7.txt &')
    Se8.cmd('iperf -s  > dataResult/examine5/' + str(ccName) + '_' +
            str(maxQ) + '_' + str(BW) + '_LL_iperf-server8.txt &')

    print('                          Server Iperf Started')
    Se1.cmd('python -m SimpleHTTPServer &')
    Se2.cmd('python -m SimpleHTTPServer &')
    Se3.cmd('python -m SimpleHTTPServer &')
    Se4.cmd('python -m SimpleHTTPServer &')
    Se5.cmd('python -m SimpleHTTPServer &')
    Se6.cmd('python -m SimpleHTTPServer &')
    Se7.cmd('python -m SimpleHTTPServer &')
    Se8.cmd('python -m SimpleHTTPServer &')

    print(
        '========================================================================='
    )
    ####    STARTING EXAMINE    ####
    print('                TCPDUMP Started Longlived for 65 s Please Wait')
    print('                              Iperf Started')
    Cl1.cmd(
        'tcpdump -G 35 -W 1 -w /home/reghn/Documents/pcapngs/1_LL_.pcapng -i Cl1-eth0 &'
    )  #62s
    Cl1.cmd(
        'iperf -c 192.168.10.2 -t 30 -i 1 > dataResult/examine5/1_LL_iperfRests.txt &'
    )  #30s
    Cl1.cmd(
        'ping 192.168.10.2 -c 30 > dataResult/examine5/1_LL_rttRests.txt & '
    )  #30s
    # Cl1.cmd('ping 192.168.10.2 -c 9 ')

    Cl2.cmd(
        'tcpdump -G 35 -W 1 -w /home/reghn/Documents/pcapngs/2_LL_.pcapng -i Cl2-eth0 &'
    )  #62s
    Cl2.cmd(
        'iperf -c 192.168.20.2 -t 30 -i 1 > dataResult/examine5/2_LL_iperfRests.txt &'
    )  #30s
    Cl2.cmd(
        'ping 192.168.20.2 -c 30 > dataResult/examine5/2_LL_rttRests.txt & '
    )  #30s
    # Cl2.cmd('ping 192.168.20.2 -c 9 ')

    Cl3.cmd(
        'tcpdump -G 35 -W 1 -w /home/reghn/Documents/pcapngs/3_LL_.pcapng -i Cl3-eth0 &'
    )  #62s
    Cl3.cmd(
        'iperf -c 192.168.30.2 -t 30 -i 1 > dataResult/examine5/3_LL_iperfRests.txt &'
    )  #30s
    Cl3.cmd(
        'ping 192.168.30.2 -c 30 > dataResult/examine5/3_LL_rttRests.txt & '
    )  #30s
    # Cl3.cmd('ping 192.168.30.2 -c 9 ')

    Cl4.cmd(
        'tcpdump -G 35 -W 1 -w /home/reghn/Documents/pcapngs/4_LL_.pcapng -i Cl4-eth0 &'
    )  #62s
    Cl4.cmd(
        'iperf -c 192.168.40.2 -t 30 -i 1 > dataResult/examine5/4_LL_iperfRests.txt &'
    )  #30s
    Cl4.cmd(
        'ping 192.168.40.2 -c 30 > dataResult/examine5/4_LL_rttRests.txt & '
    )  #30s
    # Cl4.cmd('ping 192.168.40.2 -c 9 ')

    Cl5.cmd(
        'tcpdump -G 35 -W 1 -w /home/reghn/Documents/pcapngs/5_LL_.pcapng -i Cl5-eth0 &'
    )  #62s
    Cl5.cmd(
        'iperf -c 192.168.50.2 -t 30 -i 1 > dataResult/examine5/5_LL_iperfRests.txt &'
    )  #30s
    Cl5.cmd(
        'ping 192.168.50.2 -c 30 > dataResult/examine5/5_LL_rttRests.txt & '
    )  #30s
    # Cl5.cmd('ping 192.168.50.2 -c 9 ')

    Cl6.cmd(
        'tcpdump -G 35 -W 1 -w /home/reghn/Documents/pcapngs/6_LL_.pcapng -i Cl6-eth0 &'
    )  #62s
    Cl6.cmd(
        'iperf -c 192.168.60.2 -t 30 -i 1 > dataResult/examine5/6_LL_iperfRests.txt &'
    )  #30s
    Cl6.cmd(
        'ping 192.168.60.2 -c 30 > dataResult/examine5/6_LL_rttRests.txt & '
    )  #30s
    # Cl6.cmd('ping 192.168.60.2 -c 9 ')

    Cl7.cmd(
        'tcpdump -G 35 -W 1 -w /home/reghn/Documents/pcapngs/7_LL_.pcapng -i Cl7-eth0 &'
    )  #62s
    Cl7.cmd(
        'iperf -c 192.168.70.2 -t 30 -i 1 > dataResult/examine5/7_LL_iperfRests.txt &'
    )  #30s
    Cl7.cmd(
        'ping 192.168.70.2 -c 30 > dataResult/examine5/7_LL_rttRests.txt & '
    )  #30s
    # Cl7.cmd('ping 192.168.70.2 -c 9 ')

    Cl8.cmd(
        'tcpdump -G 35 -W 1 -w /home/reghn/Documents/pcapngs/8_LL_.pcapng -i Cl8-eth0 &'
    )  #62s
    Cl8.cmd(
        'iperf -c 192.168.80.2 -t 30 -i 1 > dataResult/examine5/8_LL_iperfRests.txt &'
    )  #30s
    Cl8.cmd(
        'ping 192.168.80.2 -c 30 > dataResult/examine5/8_LL_rttRests.txt & '
    )  #30s
    # Cl8.cmd('ping 192.168.80.2 -c 9 ')

    time.sleep(2)

    #pidCode = subprocess.check_output('pidof tcpdump', shell=True)
    #pidCode = pidCode.replace("\n","")
    #Cl1.cmd('kill '+str(pidCode)+'')
    #### rename file ####

    os.system(
        'mv /home/reghn/Documents/pcapngs/1_LL_.pcapng /home/reghn/Documents/pcapngs/'
        + str(ccName) + '_' + str(maxQ) + '_' + str(BW) + '_LL_CL1.pcapng')
    os.system(
        'mv dataResult/examine5/1_LL_iperfRests.txt dataResult/examine5/' +
        str(ccName) + '_' + str(maxQ) + '_' + str(BW) +
        '_LL_iperfRests_Cl1.txt')
    os.system('mv dataResult/examine5/1_LL_rttRests.txt dataResult/examine5/' +
              str(ccName) + '_' + str(maxQ) + '_' + str(BW) +
              '_LL_rttRests._Cl1.txt')

    os.system(
        'mv /home/reghn/Documents/pcapngs/2_LL_.pcapng /home/reghn/Documents/pcapngs/'
        + str(ccName) + '_' + str(maxQ) + '_' + str(BW) + '_LL_CL2.pcapng')
    os.system(
        'mv dataResult/examine5/2_LL_iperfRests.txt dataResult/examine5/' +
        str(ccName) + '_' + str(maxQ) + '_' + str(BW) +
        '_LL_iperfRests_Cl2.txt')
    os.system('mv dataResult/examine5/2_LL_rttRests.txt dataResult/examine5/' +
              str(ccName) + '_' + str(maxQ) + '_' + str(BW) +
              '_LL_rttRests._Cl2.txt')

    os.system(
        'mv /home/reghn/Documents/pcapngs/3_LL_.pcapng /home/reghn/Documents/pcapngs/'
        + str(ccName) + '_' + str(maxQ) + '_' + str(BW) + '_LL_CL3.pcapng')
    os.system(
        'mv dataResult/examine5/3_LL_iperfRests.txt dataResult/examine5/' +
        str(ccName) + '_' + str(maxQ) + '_' + str(BW) +
        '_LL_iperfRests_Cl3.txt')
    os.system('mv dataResult/examine5/3_LL_rttRests.txt dataResult/examine5/' +
              str(ccName) + '_' + str(maxQ) + '_' + str(BW) +
              '_LL_rttRests._Cl3.txt')

    os.system(
        'mv /home/reghn/Documents/pcapngs/4_LL_.pcapng /home/reghn/Documents/pcapngs/'
        + str(ccName) + '_' + str(maxQ) + '_' + str(BW) + '_LL_CL4.pcapng')
    os.system(
        'mv dataResult/examine5/4_LL_iperfRests.txt dataResult/examine5/' +
        str(ccName) + '_' + str(maxQ) + '_' + str(BW) +
        '_LL_iperfRests_Cl4.txt')
    os.system('mv dataResult/examine5/4_LL_rttRests.txt dataResult/examine5/' +
              str(ccName) + '_' + str(maxQ) + '_' + str(BW) +
              '_LL_rttRests._Cl4.txt')

    os.system(
        'mv /home/reghn/Documents/pcapngs/5_LL_.pcapng /home/reghn/Documents/pcapngs/'
        + str(ccName) + '_' + str(maxQ) + '_' + str(BW) + '_LL_CL5.pcapng')
    os.system(
        'mv dataResult/examine5/5_LL_iperfRests.txt dataResult/examine5/' +
        str(ccName) + '_' + str(maxQ) + '_' + str(BW) +
        '_LL_iperfRests_Cl5.txt')
    os.system('mv dataResult/examine5/5_LL_rttRests.txt dataResult/examine5/' +
              str(ccName) + '_' + str(maxQ) + '_' + str(BW) +
              '_LL_rttRests._Cl5.txt')

    os.system(
        'mv /home/reghn/Documents/pcapngs/6_LL_.pcapng /home/reghn/Documents/pcapngs/'
        + str(ccName) + '_' + str(maxQ) + '_' + str(BW) + '_LL_CL6.pcapng')
    os.system(
        'mv dataResult/examine5/6_LL_iperfRests.txt dataResult/examine5/' +
        str(ccName) + '_' + str(maxQ) + '_' + str(BW) +
        '_LL_iperfRests_Cl6.txt')
    os.system('mv dataResult/examine5/6_LL_rttRests.txt dataResult/examine5/' +
              str(ccName) + '_' + str(maxQ) + '_' + str(BW) +
              '_LL_rttRests._Cl6.txt')

    os.system(
        'mv /home/reghn/Documents/pcapngs/7_LL_.pcapng /home/reghn/Documents/pcapngs/'
        + str(ccName) + '_' + str(maxQ) + '_' + str(BW) + '_LL_CL7.pcapng')
    os.system(
        'mv dataResult/examine5/7_LL_iperfRests.txt dataResult/examine5/' +
        str(ccName) + '_' + str(maxQ) + '_' + str(BW) +
        '_LL_iperfRests_Cl7.txt')
    os.system('mv dataResult/examine5/7_LL_rttRests.txt dataResult/examine5/' +
              str(ccName) + '_' + str(maxQ) + '_' + str(BW) +
              '_LL_rttRests._Cl7.txt')

    os.system(
        'mv /home/reghn/Documents/pcapngs/8_LL_.pcapng /home/reghn/Documents/pcapngs/'
        + str(ccName) + '_' + str(maxQ) + '_' + str(BW) + '_LL_CL8.pcapng')
    os.system(
        'mv dataResult/examine5/8_LL_iperfRests.txt dataResult/examine5/' +
        str(ccName) + '_' + str(maxQ) + '_' + str(BW) +
        '_LL_iperfRests_Cl8.txt')
    os.system('mv dataResult/examine5/8_LL_rttRests.txt dataResult/examine5/' +
              str(ccName) + '_' + str(maxQ) + '_' + str(BW) +
              '_LL_rttRests._Cl8.txt')

    print(
        '========================================================================='
    )
    print('                          Python HTTP Server Start')
    print(
        '========================================================================='
    )

    os.system('echo              Shortlived Started for 10 s Please Wait')

    # Cl1.cmd('tcpdump -G 25 -W 1 -w /home/reghn/Documents/pcapngs/_SL_.pcapng -i Cl1-eth0 &')

    Cl1.cmdPrint('wget -q 192.168.10.2:8000 &')
    # os.system('scrot --delay 2 '+str(ccName)+''+str(maxQ)+'_'+str(BW)+'restSL_Cl1.png &')
    #os.system('mv restSL.png restSL'+str(ccName)+''+str(maxQ)+'_'+str(BW)+'_Cl1')

    # os.system('mv /home/reghn/Documents/pcapngs/_SL_.pcapng /home/reghn/Documents/pcapngs/'+str(ccName)+'_'+str(maxQ)+'_'+str(BW)+'_SL_.pcapng')

    Cl2.cmdPrint('wget -q 192.168.20.2:8000 &')
    # os.system('scrot --delay 2 '+str(ccName)+''+str(maxQ)+'_'+str(BW)+'restSL_Cl2.png &')
    # os.system('mv /home/reghn/Documents/pcapngs/_SL_.pcapng /home/reghn/Documents/pcapngs/'+str(ccName)+'_'+str(maxQ)+'_'+str(BW)+'_SL_Cl2.pcapng')
    # os.system('mv restSL.png restSL'+str(ccName)+''+str(maxQ)+'_'+str(BW)+'_Cl2')

    Cl3.cmdPrint('wget -q 192.168.30.2:8000 &')
    # os.system('scrot --delay 2 '+str(ccName)+''+str(maxQ)+'_'+str(BW)+'restSL_Cl3.png &')
    # os.system('mv restSL.png restSL'+str(ccName)+''+str(maxQ)+'_'+str(BW)+'_Cl3')

    Cl4.cmdPrint('wget -q 192.168.40.2:8000 &')
    # os.system('scrot --delay 2 '+str(ccName)+''+str(maxQ)+'_'+str(BW)+'restSL.png &')
    # os.system('mv restSL.png restSL'+str(ccName)+''+str(maxQ)+'_'+str(BW)+'_Cl4')

    Cl5.cmdPrint('wget -q 192.168.50.2:8000 &')
    # os.system('scrot --delay 2 '+str(ccName)+''+str(maxQ)+'_'+str(BW)+'restSL.png &')
    # os.system('mv restSL.png restSL'+str(ccName)+''+str(maxQ)+'_'+str(BW)+'_Cl5')

    Cl6.cmdPrint('wget -q 192.168.60.2:8000 &')
    # os.system('scrot --delay 2 '+str(ccName)+''+str(maxQ)+'_'+str(BW)+'restSL.png &')
    # os.system('mv restSL.png restSL'+str(ccName)+''+str(maxQ)+'_'+str(BW)+'_Cl6')

    Cl7.cmdPrint('wget -q 192.168.70.2:8000 &')
    # os.system('scrot --delay 2 '+str(ccName)+''+str(maxQ)+'_'+str(BW)+'restSL.png &')
    # os.system('mv restSL.png restSL'+str(ccName)+''+str(maxQ)+'_'+str(BW)+'_Cl7')

    Cl8.cmdPrint('wget -q 192.168.80.2:8000 &')
    # os.system('scrot --delay 2 '+str(ccName)+''+str(maxQ)+'_'+str(BW)+'restSL.png &')
    # os.system('mv restSL.png restSL'+str(ccName)+''+str(maxQ)+'_'+str(BW)+'_Cl8')

    print(
        '========================================================================='
    )
    print("                         Processing all file's   ")
    print(
        '========================================================================='
    )
    time.sleep(40)

    # CLI(net)
    net.stop()
Exemple #60
0
def main():
    topo = PyRouterTopo(args)
    net = Mininet(topo=topo, link=TCLink, cleanup=True, controller=None)
    setup_addressing(net)
    disable_ipv6(net)
    net.interact()