mininet(一)实验环境搭建
mininet(二)简单的路由实验
mininet(三)简单的NAT实验

在网上找了 好几个代码都是不能直接复现成功,这里把自己实现成功的代码给大家演示一下。

实验的拓扑结构如下:
这里写图片描述
试验中利用 一台主机代替router,开启ip_forward选项,来链接两个子网。

#!/usr/bin/python
import time
from mininet.net import Mininet
from mininet.node import Controller, RemoteController, OVSKernelSwitch,UserSwitch
from mininet.cli import CLI
from mininet.log import setLogLevel
from mininet.link import Link, TCLink

def topology():

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

    print "*** Creating nodes ***"
    h1 = net.addHost( 'h1', mac='00:00:00:00:00:01', ip='10.0.10.1/24' )
    h2 = net.addHost( 'h2', mac='00:00:00:00:00:02', ip='10.0.10.2/24' )
    h3 = net.addHost( 'h3', mac='00:00:00:00:00:03', ip='10.0.1.1/24' )
    s1 = net.addSwitch( 's1', listenPort=6673, mac='00:00:00:00:00:11' )
    s2 = net.addSwitch( 's2', listenPort=6674, mac='00:00:00:00:00:12' )
    c0 = net.addController( 'c0', controller=RemoteController, ip='127.0.0.1', port=6633 )

    print "*** Creating links ***"
    net.addLink(s1, h1, 1, 0)
    net.addLink(s2, h3, 1, 0)

    Link(h2, s1, intfName1='h2-eth0')
    Link(h2, s2, intfName1='h2-eth1')
    h2.cmd('ifconfig h2-eth1 10.0.1.2 netmask 255.255.255.0')
    h2.cmd('sysctl net.ipv4.ip_forward=1')

    h1.cmd('route add default gw 10.0.10.2')
    h3.cmd('route add default gw 10.0.1.2')

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

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

    print "*** Stopping network ***"
    net.stop()

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

试验时,运行./Router.py 然后利用h1 ping h3还是不通。
给两个交换机下发转发 规则

 # ovs-ofctl add-flow s1 in_port=1,actions=output:2
 # ovs-ofctl add-flow s1 in_port=2,actions=output:1
 # ovs-ofctl add-flow s2 in_port=1,actions=output:2
 # ovs-ofctl add-flow s2 in_port=2,actions=output:1
h1 route add default gw 10.0.10.2
h3 route add default gw 10.0.1.2

此时可以利用

h1 ping 10.0.10.2
h3 ping 100.1.2

但是h1 ping h3 仍然不通。开启ip_forward转发

h2 sysctl net.ipv4.ip_forward=1

此时h1 ping h3 就可以通了

ps:我在Router.py中明明写了

    h2.cmd('sysctl net.ipv4.ip_forward=1')
    h1.cmd('route add default gw 10.0.10.2')
    h3.cmd('route add default gw 10.0.1.2')

但是好像没有起作用,只有手动添加之后才生效,没有找到具体原因。还有实验时竟然将h1 的default gw 配置成 10.0.10.0 了,h3 的default gw 配置成 10.0.1.0 了,导致一直不通。基本网络知识没有过关。

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐