Example #1
0
    def testSocket(self):
        """! Test socket
        @param self
        @return none
        """
        node = ns.network.Node()
        internet = ns.internet.InternetStackHelper()
        internet.Install(node)
        self._received_packet = None

        def rx_callback(socket):
            """! Receive Callback
            @param socket the socket to receive
            @return none
            """
            assert self._received_packet is None
            self._received_packet = socket.Recv(maxSize=UINT32_MAX, flags=0)

        sink = ns.network.Socket.CreateSocket(node, ns.core.TypeId.LookupByName("ns3::UdpSocketFactory"))
        sink.Bind(ns.network.InetSocketAddress(ns.network.Ipv4Address.GetAny(), 80))
        sink.SetRecvCallback(rx_callback)

        source = ns.network.Socket.CreateSocket(node, ns.core.TypeId.LookupByName("ns3::UdpSocketFactory"))
        source.SendTo(ns.network.Packet(19), 0, ns.network.InetSocketAddress(ns.network.Ipv4Address("127.0.0.1"), 80))

        Simulator.Run()
        self.assertTrue(self._received_packet is not None)
        self.assertEqual(self._received_packet.GetSize(), 19)
Example #2
0
    def testSocket(self):
        node = ns.network.Node()
        internet = ns.internet.InternetStackHelper()
        internet.Install(node)
        self._received_packet = None

        def rx_callback(socket):
            assert self._received_packet is None
            self._received_packet = socket.Recv()

        sink = ns.network.Socket.CreateSocket(
            node, ns.core.TypeId.LookupByName("ns3::UdpSocketFactory"))
        sink.Bind(
            ns.network.InetSocketAddress(ns.network.Ipv4Address.GetAny(), 80))
        sink.SetRecvCallback(rx_callback)

        source = ns.network.Socket.CreateSocket(
            node, ns.core.TypeId.LookupByName("ns3::UdpSocketFactory"))
        source.SendTo(
            ns.network.Packet(19), 0,
            ns.network.InetSocketAddress(ns.network.Ipv4Address("127.0.0.1"),
                                         80))

        Simulator.Run()
        self.assert_(self._received_packet is not None)
        self.assertEqual(self._received_packet.GetSize(), 19)
def main(argv):
  
  
  
  
  cmd = ns.core.CommandLine()
  cmd.Parse(argv)

  
  
  
  
  ns.core.GlobalValue.Bind("SimulatorImplementationType", ns.core.StringValue("ns3::RealtimeSimulatorImpl"))

  
  
  
  print "Create nodes."
  n = ns.network.NodeContainer()
  n.Create(4)

  internet = ns.internet.InternetStackHelper()
  internet.Install(n)

  
  
  
  print ("Create channels.")
  csma = ns.csma.CsmaHelper()
  csma.SetChannelAttribute("DataRate", ns.network.DataRateValue(ns.network.DataRate(5000000)))
  csma.SetChannelAttribute("Delay", ns.core.TimeValue(ns.core.MilliSeconds(2)));
  csma.SetDeviceAttribute("Mtu", ns.core.UintegerValue(1400))
  d = csma.Install(n)

  
  
  
  print ("Assign IP Addresses.")
  ipv4 = ns.internet.Ipv4AddressHelper()
  ipv4.SetBase(ns.network.Ipv4Address("10.1.1.0"), ns.network.Ipv4Mask("255.255.255.0"))
  i = ipv4.Assign(d)

  print ("Create Applications.")

  
  
  
  port = 9  
  server = ns.applications.UdpEchoServerHelper(port)
  apps = server.Install(n.Get(1))
  apps.Start(ns.core.Seconds(1.0))
  apps.Stop(ns.core.Seconds(10.0))

  
  
  
  
  packetSize = 1024
  maxPacketCount = 500
  interPacketInterval = ns.core.Seconds(0.01)
  client = ns.applications.UdpEchoClientHelper(i.GetAddress (1), port)
  client.SetAttribute("MaxPackets", ns.core.UintegerValue(maxPacketCount))
  client.SetAttribute("Interval", ns.core.TimeValue(interPacketInterval))
  client.SetAttribute("PacketSize", ns.core.UintegerValue(packetSize))
  apps = client.Install(n.Get(0))
  apps.Start(ns.core.Seconds(2.0))
  apps.Stop(ns.core.Seconds(10.0))

  ascii = ns.network.AsciiTraceHelper()
  csma.EnableAsciiAll(ascii.CreateFileStream("realtime-udp-echo.tr"))
  csma.EnablePcapAll("realtime-udp-echo", False)

  
  
  
  print ("Run Simulation.")
  ns.core.Simulator.Run()
  ns.core.Simulator.Destroy()
  print ("Done.")
Example #4
0
def main(argv):
    sfqLinkDataRate = "1.5Mbps"
    sfqLinkDelay = "20ms"

    pathOut = "."
    writeForPlot = ""
    writePcap = ""
    flowMonitor = ""

    printSfqStats = True

    global_start_time = 0.0
    sink_start_time = global_start_time
    client_start_time = global_start_time + 1.5
    global_stop_time = 7.0
    sink_stop_time = global_stop_time + 3.0
    client_stop_time = global_stop_time - 2.0

    pathOut = "."  # Current directory
    cmd = ns.core.CommandLine()
    cmd.AddValue(
        "pathOut",
        "Path to save results from --writeForPlot/--writePcap/--writeFlowMonitor",
        pathOut)
    cmd.AddValue("writeForPlot", "<0/1> to write results for plot (gnuplot)",
                 writeForPlot)
    cmd.AddValue("writePcap", "<0/1> to write results in pcapfile", writePcap)
    cmd.AddValue("writeFlowMonitor",
                 "<0/1> to enable Flow Monitor and write their results",
                 flowMonitor)

    cmd.Parse(sys.argv)

    print("Create nodes")
    c = ns.network.NodeContainer()
    c.Create(6)
    ns.core.Names.Add("N0", c.Get(0))
    ns.core.Names.Add("N1", c.Get(1))
    ns.core.Names.Add("N2", c.Get(2))
    ns.core.Names.Add("N3", c.Get(3))
    ns.core.Names.Add("N4", c.Get(4))
    ns.core.Names.Add("N5", c.Get(5))
    n0n2 = ns.network.NodeContainer(ns.network.NodeContainer(c.Get(0)),
                                    ns.network.NodeContainer(c.Get(2)))
    n1n2 = ns.network.NodeContainer(ns.network.NodeContainer(c.Get(1)),
                                    ns.network.NodeContainer(c.Get(2)))
    n2n3 = ns.network.NodeContainer(ns.network.NodeContainer(c.Get(2)),
                                    ns.network.NodeContainer(c.Get(3)))
    n3n4 = ns.network.NodeContainer(ns.network.NodeContainer(c.Get(3)),
                                    ns.network.NodeContainer(c.Get(4)))
    n3n5 = ns.network.NodeContainer(ns.network.NodeContainer(c.Get(3)),
                                    ns.network.NodeContainer(c.Get(5)))

    ns.core.Config.SetDefault("ns3::TcpL4Protocol::SocketType",
                              ns.core.StringValue("ns3::TcpNewReno"))

    ns.core.Config.SetDefault("ns3::TcpSocket::SegmentSize",
                              ns.core.UintegerValue(1000 - 42))
    ns.core.Config.SetDefault("ns3::TcpSocket::DelAckCount",
                              ns.core.UintegerValue(1))
    ns.core.GlobalValue.Bind("ChecksumEnabled", ns.core.BooleanValue(False))

    print("Set SFQ params")
    ns.core.Config.SetDefault("ns3::SfqQueueDisc::Interval",
                              ns.core.StringValue("100ms"))
    ns.core.Config.SetDefault("ns3::SfqQueueDisc::Target",
                              ns.core.StringValue("5ms"))
    ns.core.Config.SetDefault("ns3::SfqQueueDisc::PacketLimit",
                              ns.core.UintegerValue(10 * 1024))
    ns.core.Config.SetDefault("ns3::SfqQueueDisc::Flows",
                              ns.core.UintegerValue(1024))
    ns.core.Config.SetDefault("ns3::SfqQueueDisc::DropBatchSize",
                              ns.core.UintegerValue(64))

    print("Install internet stack on all nodes.")
    internet = ns.internet.InternetStackHelper()
    internet.Install(c)

    tchPfifo = ns.traffic_control.TrafficControlHelper()
    handle = tchPfifo.SetRootQueueDisc("ns3::PfifoFastQueueDisc")
    tchPfifo.AddInternalQueues(handle, 3, "ns3::DropTailQueue", "MaxPackets",
                               UintegerValue(10 * 1024))

    tchSfq = ns.traffic_control.TrafficControlHelper()
    tchSfq.SetRootQueueDisc("ns3::SfqQueueDisc")
    tchSfq.AddPacketFilter(handle, "ns3::SfqIpv4PacketFilter")
    tchSfq.AddPacketFilter(handle, "ns3::SfqIpv6PacketFilter")

    print("Create channels")

    p2p = ns.point_to_point.PointToPointHelper()

    devn0n2 = ns.network.NetDeviceContainer()
    devn1n2 = ns.network.NetDeviceContainer()
    devn2n3 = ns.network.NetDeviceContainer()
    devn3n4ns.network.NetDeviceContainer()
    devn3n5ns.network.NetDeviceContainer()

    queueDiscs = ns.traffic_control.QueueDiscContainer()
    p2p.SetQueue("ns3::DropTailQueue")

    p2p.SetDeviceAttribute("DataRate", ns.core.StringValue("10Mbps"))
    p2p.SetChannelAttribute("Delay", ns.core.StringValue("2ms"))
    devn0n2 = p2p.Install(n0n2)
    tchPfifo.Install(devn0n2)

    p2p.SetQueue("ns3::DropTailQueue")
    p2p.SetDeviceAttribute("DataRate", ns.core.StringValue("10Mbps"))
    p2p.SetChannelAttribute("Delay", ns.core.StringValue("3ms"))
    devn1n2 = p2p.Install(n1n2)
    tchPfifo.Install(devn1n2)

    p2p.SetQueue("ns3::DropTailQueue")
    p2p.SetDeviceAttribute("DataRate", ns.core.StringValue(sfqLinkDataRate))
    p2p.SetChannelAttribute("Delay", ns.core.StringValue(sfqLinkDelay))
    devn2n3 = p2p.Install(n2n3)

    queueDiscs = tchSfq.Install(devn2n3)

    p2p.SetQueue("ns3::DropTailQueue")
    p2p.SetDeviceAttribute("DataRate", ns.core.StringValue("10Mbps"))
    p2p.SetChannelAttribute("Delay", ns.core.StringValue("4ms"))
    devn3n4 = p2p.Install(n3n4)
    tchPfifo.Install(devn3n4)

    p2p.SetQueue("ns3::DropTailQueue")
    p2p.SetDeviceAttribute("DataRate", ns.core.StringValue("10Mbps"))
    p2p.SetChannelAttribute("Delay", ns.core.StringValue("5ms"))
    devn3n5 = p2p.Install(n3n5)
    tchPfifo.Install(devn3n5)

    print("Assign IP Addresses")

    ipv4 = ns.internet.Ipv4AddressHelper()

    ipv4.SetBase(ns.network.Ipv4Address("10.1.1.0"),
                 ns.network.Ipv4Mask("255.255.255.0"))

    i0i2 = ipv4.Assign(devn0n2)

    ipv4.SetBase(ns.network.Ipv4Address("10.1.2.0"),
                 ns.network.Ipv4Mask("255.255.255.0"))
    i1i2 = ipv4.Assign(devn1n2)

    ipv4.SetBase(ns.network.Ipv4Address("10.1.3.0"),
                 ns.network.Ipv4Mask("255.255.255.0"))
    i2i3 = ipv4.Assign(devn2n3)

    ipv4.SetBase(ns.network.Ipv4Address("10.1.4.0"),
                 ns.network.Ipv4Mask("255.255.255.0"))
    i3i4 = ipv4.Assign(devn3n4)

    ipv4.SetBase(ns.network.Ipv4Address("10.1.5.0"),
                 ns.network.Ipv4Mask("255.255.255.0"))
    i3i5 = ipv4.Assign(devn3n5)

    ns.internet.Ipv4GlobalRoutingHelper.PopulateRoutingTables()
    BuildAppsTest()

    if (writePcap):
        ptp = ns.point_to_point.PointToPointHelper()
        print pathOut + "/sfq"
        ptp.EnablePcapAll(c_str())

    if (flowMonitor):
        flowmonHelper = ns.flow_monitor.FlowMonitorHelper
        flowmon = flowmonHelper.InstallAll()

    if (writeForPlot):
        print pathOut + "/sfq-queue-disc.plotme"
        print pathOut + "/sfq-queue-disc_avg.plotme"
        queue = queueDiscs.Get(0)

    ns.core.Simulator.Stop(ns.core.Seconds(sink_stop_time))
    ns.core.Simulator.Run()
    st = ns.traffic_control.QueueDisc.Stats()
    st = queueDiscs.Get(0).GetStats()

    if (flowMonitor):
        stmp = pathOut + "/pie.flowmon"
        flowmon.SerializeToXmlFile(stmp.c_str(), False, False)
    ns.core.Simulator.Destroy()
def main(argv):

    cmd = ns.core.CommandLine()

    cmd.NumNodesSide = None
    cmd.AddValue(
        "NumNodesSide",
        "Grid side number of nodes (total number of nodes will be this number squared)"
    )

    cmd.Results = None
    cmd.AddValue("Results", "Write XML results to file")

    cmd.Plot = None
    cmd.AddValue("Plot", "Plot the results using the matplotlib python module")

    cmd.Parse(argv)

    wifi = ns.wifi.WifiHelper.Default()
    wifiMac = ns.wifi.NqosWifiMacHelper.Default()
    wifiPhy = ns.wifi.YansWifiPhyHelper.Default()
    wifiChannel = ns.wifi.YansWifiChannelHelper.Default()
    wifiPhy.SetChannel(wifiChannel.Create())
    ssid = ns.wifi.Ssid("wifi-default")
    wifi.SetRemoteStationManager("ns3::ArfWifiManager")
    wifiMac.SetType("ns3::AdhocWifiMac", "Ssid", ns.wifi.SsidValue(ssid))

    internet = ns.internet.InternetStackHelper()
    list_routing = ns.internet.Ipv4ListRoutingHelper()
    olsr_routing = ns.olsr.OlsrHelper()
    static_routing = ns.internet.Ipv4StaticRoutingHelper()
    list_routing.Add(static_routing, 0)
    list_routing.Add(olsr_routing, 100)
    internet.SetRoutingHelper(list_routing)

    ipv4Addresses = ns.internet.Ipv4AddressHelper()
    ipv4Addresses.SetBase(ns.network.Ipv4Address("10.0.0.0"),
                          ns.network.Ipv4Mask("255.255.255.0"))

    port = 9  # Discard port(RFC 863)
    onOffHelper = ns.applications.OnOffHelper(
        "ns3::UdpSocketFactory",
        ns.network.Address(
            ns.network.InetSocketAddress(ns.network.Ipv4Address("10.0.0.1"),
                                         port)))
    onOffHelper.SetAttribute(
        "DataRate", ns.network.DataRateValue(ns.network.DataRate("100kbps")))
    onOffHelper.SetAttribute(
        "OnTime",
        ns.core.StringValue("ns3::ConstantRandomVariable[Constant=1]"))
    onOffHelper.SetAttribute(
        "OffTime",
        ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0]"))

    addresses = []
    nodes = []

    if cmd.NumNodesSide is None:
        num_nodes_side = NUM_NODES_SIDE
    else:
        num_nodes_side = int(cmd.NumNodesSide)

    for xi in range(num_nodes_side):
        for yi in range(num_nodes_side):

            node = ns.network.Node()
            nodes.append(node)

            internet.Install(ns.network.NodeContainer(node))

            mobility = ns.mobility.ConstantPositionMobilityModel()
            mobility.SetPosition(
                ns.core.Vector(xi * DISTANCE, yi * DISTANCE, 0))
            node.AggregateObject(mobility)

            devices = wifi.Install(wifiPhy, wifiMac, node)
            ipv4_interfaces = ipv4Addresses.Assign(devices)
            addresses.append(ipv4_interfaces.GetAddress(0))

    for i, node in enumerate(nodes):
        destaddr = addresses[(len(addresses) - 1 - i) % len(addresses)]
        #print i, destaddr
        onOffHelper.SetAttribute(
            "Remote",
            ns.network.AddressValue(
                ns.network.InetSocketAddress(destaddr, port)))
        app = onOffHelper.Install(ns.network.NodeContainer(node))
        urv = ns.core.UniformRandomVariable()
        app.Start(ns.core.Seconds(urv.GetValue(20, 30)))

    #internet.EnablePcapAll("wifi-olsr")
    flowmon_helper = ns.flow_monitor.FlowMonitorHelper()
    #flowmon_helper.SetMonitorAttribute("StartTime", ns.core.TimeValue(ns.core.Seconds(31)))
    monitor = flowmon_helper.InstallAll()
    monitor = flowmon_helper.GetMonitor()
    monitor.SetAttribute("DelayBinWidth", ns.core.DoubleValue(0.001))
    monitor.SetAttribute("JitterBinWidth", ns.core.DoubleValue(0.001))
    monitor.SetAttribute("PacketSizeBinWidth", ns.core.DoubleValue(20))

    ns.core.Simulator.Stop(ns.core.Seconds(44.0))
    ns.core.Simulator.Run()

    def print_stats(os, st):
        print >> os, "  Tx Bytes: ", st.txBytes
        print >> os, "  Rx Bytes: ", st.rxBytes
        print >> os, "  Tx Packets: ", st.txPackets
        print >> os, "  Rx Packets: ", st.rxPackets
        print >> os, "  Lost Packets: ", st.lostPackets
        if st.rxPackets > 0:
            print >> os, "  Mean{Delay}: ", (st.delaySum.GetSeconds() /
                                             st.rxPackets)
            print >> os, "  Mean{Jitter}: ", (st.jitterSum.GetSeconds() /
                                              (st.rxPackets - 1))
            print >> os, "  Mean{Hop Count}: ", float(
                st.timesForwarded) / st.rxPackets + 1

        if 0:
            print >> os, "Delay Histogram"
            for i in range(st.delayHistogram.GetNBins()):
                print >> os, " ",i,"(", st.delayHistogram.GetBinStart (i), "-", \
                    st.delayHistogram.GetBinEnd (i), "): ", st.delayHistogram.GetBinCount (i)
            print >> os, "Jitter Histogram"
            for i in range(st.jitterHistogram.GetNBins()):
                print >> os, " ",i,"(", st.jitterHistogram.GetBinStart (i), "-", \
                    st.jitterHistogram.GetBinEnd (i), "): ", st.jitterHistogram.GetBinCount (i)
            print >> os, "PacketSize Histogram"
            for i in range(st.packetSizeHistogram.GetNBins()):
                print >> os, " ",i,"(", st.packetSizeHistogram.GetBinStart (i), "-", \
                    st.packetSizeHistogram.GetBinEnd (i), "): ", st.packetSizeHistogram.GetBinCount (i)

        for reason, drops in enumerate(st.packetsDropped):
            print "  Packets dropped by reason %i: %i" % (reason, drops)
        #for reason, drops in enumerate(st.bytesDropped):
        #    print "Bytes dropped by reason %i: %i" % (reason, drops)

    monitor.CheckForLostPackets()
    classifier = flowmon_helper.GetClassifier()

    if cmd.Results is None:
        for flow_id, flow_stats in monitor.GetFlowStats():
            t = classifier.FindFlow(flow_id)
            proto = {6: 'TCP', 17: 'UDP'}[t.protocol]
            print "FlowID: %i (%s %s/%s --> %s/%i)" % \
                (flow_id, proto, t.sourceAddress, t.sourcePort, t.destinationAddress, t.destinationPort)
            print_stats(sys.stdout, flow_stats)
    else:
        print monitor.SerializeToXmlFile(cmd.Results, True, True)

    if cmd.Plot is not None:
        import pylab
        delays = []
        for flow_id, flow_stats in monitor.GetFlowStats():
            tupl = classifier.FindFlow(flow_id)
            if tupl.protocol == 17 and tupl.sourcePort == 698:
                continue
            delays.append(flow_stats.delaySum.GetSeconds() /
                          flow_stats.rxPackets)
        pylab.hist(delays, 20)
        pylab.xlabel("Delay (s)")
        pylab.ylabel("Number of Flows")
        pylab.show()

    return 0
def main(argv):
    ns.core.LogComponentEnable("PieQueueDisc", ns.core.LOG_LEVEL_INFO)
    pieLinkDataRate = "1.5Mbps"
    pieLinkDelay = "20ms"

    n0n2 = ns.network.NodeContainer()
    n1n2 = ns.network.NodeContainer()
    n2n3 = ns.network.NodeContainer()
    n3n4 = ns.network.NodeContainer()
    n3n5 = ns.network.NodeContainer()

    i0i2 = ns.internet.Ipv4InterfaceContainer()
    i1i2 = ns.internet.Ipv4InterfaceContainer()
    i2i3 = ns.internet.Ipv4InterfaceContainer()
    i3i4 = ns.internet.Ipv4InterfaceContainer()
    i3i5 = ns.internet.Ipv4InterfaceContainer()

    writeForPlot = 0
    writePcap = 0
    flowMonitor = 0

    printPieStats = 1

    global_start_time = 0.0
    sink_start_time = global_start_time
    client_start_time = global_start_time + 1.5
    global_stop_time = 7.0
    sink_stop_time = global_stop_time + 3.0
    client_stop_time = global_stop_time - 2.0

    checkTimes = 0

    # Configuration and command line parameter parsing
    # Will only save in the directory if enable opts below
    pathOut = "."  # Current directory

    cmd = ns.core.CommandLine()
    cmd.isMinstrelPie = 0
    cmd.AddValue(
        "pathOut",
        "Path to save results from --writeForPlot/--writePcap/--writeFlowMonitor"
    )
    cmd.AddValue("writeForPlot", "<0/1> to write results for plot (gnuplot)")
    cmd.AddValue("writePcap", "<0/1> to write results in pcapfile")
    cmd.AddValue("writeFlowMonitor",
                 "<0/1> to enable Flow Monitor and write their results")
    cmd.AddValue(
        "isMinstrelPie",
        "<0/1> to enable/disable Minstrel PIE",
    )

    cmd.Parse(sys.argv)

    isMinstrelPie = int(cmd.isMinstrelPie)

    print "Create nodes"

    c = ns.network.NodeContainer()
    c.Create(6)
    ns.core.Names.Add("N0", c.Get(0))
    ns.core.Names.Add("N1", c.Get(1))
    ns.core.Names.Add("N2", c.Get(2))
    ns.core.Names.Add("N3", c.Get(3))
    ns.core.Names.Add("N4", c.Get(4))
    ns.core.Names.Add("N5", c.Get(5))

    n0n2 = ns.network.NodeContainer(ns.network.NodeContainer(c.Get(0)),
                                    ns.network.NodeContainer(c.Get(2)))
    n1n2 = ns.network.NodeContainer(ns.network.NodeContainer(c.Get(1)),
                                    ns.network.NodeContainer(c.Get(2)))
    n2n3 = ns.network.NodeContainer(ns.network.NodeContainer(c.Get(2)),
                                    ns.network.NodeContainer(c.Get(3)))
    n3n4 = ns.network.NodeContainer(ns.network.NodeContainer(c.Get(3)),
                                    ns.network.NodeContainer(c.Get(4)))
    n3n5 = ns.network.NodeContainer(ns.network.NodeContainer(c.Get(3)),
                                    ns.network.NodeContainer(c.Get(5)))

    ns.core.Config.SetDefault("ns3::TcpL4Protocol::SocketType",
                              ns.core.StringValue("ns3::TcpNewReno"))
    # 42 = headers size
    ns.core.Config.SetDefault("ns3::TcpSocket::SegmentSize",
                              ns.core.UintegerValue(1000 - 42))
    ns.core.Config.SetDefault("ns3::TcpSocket::DelAckCount",
                              ns.core.UintegerValue(1))
    ns.core.GlobalValue.Bind("ChecksumEnabled", ns.core.BooleanValue(0))

    meanPktSize = 1000

    # PIE params
    print "Set PIE params"

    ns.core.Config.SetDefault("ns3::PieQueueDisc::Mode",
                              ns.core.StringValue("QUEUE_DISC_MODE_PACKETS"))
    ns.core.Config.SetDefault("ns3::PieQueueDisc::MeanPktSize",
                              ns.core.UintegerValue(meanPktSize))
    ns.core.Config.SetDefault("ns3::PieQueueDisc::DequeueThreshold",
                              ns.core.UintegerValue(10000))
    ns.core.Config.SetDefault("ns3::PieQueueDisc::QueueDelayReference",
                              ns.core.TimeValue(ns.core.Seconds(0.02)))
    ns.core.Config.SetDefault("ns3::PieQueueDisc::MaxBurstAllowance",
                              ns.core.TimeValue(ns.core.Seconds(0.1)))
    ns.core.Config.SetDefault("ns3::PieQueueDisc::QueueLimit",
                              ns.core.UintegerValue(100))
    ns.core.Config.SetDefault("ns3::PieQueueDisc::MinstrelPIE",
                              ns.core.BooleanValue(isMinstrelPie))

    print "Install internet stack on all nodes."

    internet = ns.internet.InternetStackHelper()
    internet.Install(c)

    tchPfifo = ns.traffic_control.TrafficControlHelper()
    handle = tchPfifo.SetRootQueueDisc("ns3::PfifoFastQueueDisc")
    tchPfifo.AddInternalQueues(handle, 3, "ns3::DropTailQueue", "MaxPackets",
                               ns.core.UintegerValue(1000))

    tchPie = ns.traffic_control.TrafficControlHelper()
    tchPie.SetRootQueueDisc("ns3::PieQueueDisc")

    print "Create channels"

    p2p = ns.point_to_point.PointToPointHelper()

    devn0n2 = ns.network.NetDeviceContainer()
    devn1n2 = ns.network.NetDeviceContainer()
    devn2n3 = ns.network.NetDeviceContainer()
    devn3n4 = ns.network.NetDeviceContainer()
    devn3n5 = ns.network.NetDeviceContainer()

    queueDiscs = ns.traffic_control.QueueDiscContainer()

    p2p.SetQueue("ns3::DropTailQueue")
    p2p.SetDeviceAttribute("DataRate", ns.core.StringValue("10Mbps"))
    p2p.SetChannelAttribute("Delay", ns.core.StringValue("2ms"))
    devn0n2 = p2p.Install(n0n2)
    tchPfifo.Install(devn0n2)

    p2p.SetQueue("ns3::DropTailQueue")
    p2p.SetDeviceAttribute("DataRate", ns.core.StringValue("10Mbps"))
    p2p.SetChannelAttribute("Delay", ns.core.StringValue("3ms"))
    devn1n2 = p2p.Install(n1n2)
    tchPfifo.Install(devn1n2)

    p2p.SetQueue("ns3::DropTailQueue")
    p2p.SetDeviceAttribute("DataRate", ns.core.StringValue(pieLinkDataRate))
    p2p.SetChannelAttribute("Delay", ns.core.StringValue(pieLinkDelay))
    devn2n3 = p2p.Install(n2n3)

    ## only backbone link has PIE queue disc
    queueDiscs = tchPie.Install(devn2n3)

    p2p.SetQueue("ns3::DropTailQueue")
    p2p.SetDeviceAttribute("DataRate", ns.core.StringValue("10Mbps"))
    p2p.SetChannelAttribute("Delay", ns.core.StringValue("4ms"))
    devn3n4 = p2p.Install(n3n4)
    tchPfifo.Install(devn3n4)

    p2p.SetQueue("ns3::DropTailQueue")
    p2p.SetDeviceAttribute("DataRate", ns.core.StringValue("10Mbps"))
    p2p.SetChannelAttribute("Delay", ns.core.StringValue("5ms"))
    devn3n5 = p2p.Install(n3n5)
    tchPfifo.Install(devn3n5)

    print "Assign IP Addressess"

    ipv4 = ns.internet.Ipv4AddressHelper()

    ipv4.SetBase(ns.network.Ipv4Address("10.1.1.0"),
                 ns.network.Ipv4Mask("255.255.255.0"))
    i0i2 = ipv4.Assign(devn0n2)

    ipv4.SetBase(ns.network.Ipv4Address("10.1.2.0"),
                 ns.network.Ipv4Mask("255.255.255.0"))
    i1i2 = ipv4.Assign(devn1n2)

    ipv4.SetBase(ns.network.Ipv4Address("10.1.3.0"),
                 ns.network.Ipv4Mask("255.255.255.0"))
    i2i3 = ipv4.Assign(devn2n3)

    ipv4.SetBase(ns.network.Ipv4Address("10.1.4.0"),
                 ns.network.Ipv4Mask("255.255.255.0"))
    i3i4 = ipv4.Assign(devn3n4)

    ipv4.SetBase(ns.network.Ipv4Address("10.1.5.0"),
                 ns.network.Ipv4Mask("255.255.255.0"))
    i3i5 = ipv4.Assign(devn3n5)

    #set up the routing
    ns.internet.Ipv4GlobalRoutingHelper.PopulateRoutingTables()

    def BuildAppsTest():
        #SINK is in the right side
        port = 50000
        address = ns.network.InetSocketAddress(ns.network.Ipv4Address.GetAny(),
                                               port)

        sinkHelper = ns.applications.PacketSinkHelper("ns3::TcpSocketFactory",
                                                      address)
        sinkApp = ns.network.ApplicationContainer()

        sinkApp = sinkHelper.Install(n3n4.Get(1))

        sinkApp.Start(ns.core.Seconds(sink_start_time))
        sinkApp.Stop(ns.core.Seconds(sink_stop_time))

        #Connection 1

        # Clients are in left side

        # Create the OnOff applications to send TCP to the server
        # onoffhelper is a client that send data to TCP destination

        clientHelper1 = ns.applications.OnOffHelper("ns3::TcpSocketFactory",
                                                    ns.network.Address())
        clientHelper1.SetAttribute(
            "OnTime",
            ns.core.StringValue("ns3::ConstantRandomVariable[Constant=1]"))
        clientHelper1.SetAttribute(
            "OffTime",
            ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0]"))
        clientHelper1.SetAttribute("PacketSize", ns.core.UintegerValue(1000))
        clientHelper1.SetAttribute(
            "DataRate",
            ns.network.DataRateValue(ns.network.DataRate("10Mb/s")))

        #Connection 2
        clientHelper2 = ns.applications.OnOffHelper("ns3::TcpSocketFactory",
                                                    ns.network.Address())
        clientHelper2.SetAttribute(
            "OnTime",
            ns.core.StringValue("ns3::ConstantRandomVariable[Constant=1]"))
        clientHelper2.SetAttribute(
            "OffTime",
            ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0]"))
        clientHelper2.SetAttribute("PacketSize", ns.core.UintegerValue(1000))
        clientHelper2.SetAttribute(
            "DataRate",
            ns.network.DataRateValue(ns.network.DataRate("10Mb/s")))

        clientApps1 = ns.network.ApplicationContainer()
        remoteAddress = ns.network.AddressValue()
        remoteAddress = ns.network.AddressValue(
            ns.network.InetSocketAddress(i3i4.GetAddress(1), port))
        clientHelper1.SetAttribute("Remote", remoteAddress)
        clientApps1.Add(clientHelper1.Install(n0n2.Get(0)))
        clientApps1.Start(ns.core.Seconds(client_start_time))
        clientApps1.Stop(ns.core.Seconds(client_stop_time))

        clientApps2 = ns.network.ApplicationContainer()
        remoteAddress = ns.network.AddressValue(
            ns.network.InetSocketAddress(i3i4.GetAddress(1), port))
        clientHelper2.SetAttribute("Remote", remoteAddress)
        clientApps2.Add(clientHelper2.Install(n1n2.Get(0)))
        clientApps2.Start(ns.core.Seconds(client_start_time))
        clientApps2.Stop(ns.core.Seconds(client_stop_time))

    BuildAppsTest()

    if writePcap:
        ptp = ns.point_to_point.PointToPointHelper()
        print pathOut + "/pie"
        ptp.EnablePcapAll(c_str())

    if flowMonitor:
        flowmonHelper = ns.flow_monitor.FlowMonitorHelper
        flowmon = flowmonHelper.InstallAll()

    if writeForPlot:
        print pathOut + "/pie-queue-disc.plotme"
        print pathOut + "/pie-queue-disc_avg.plotme"

        queue = queueDiscs.Get(0)
        ns.core.Simulator.ScheduleNow(CheckQueueDiscSize, queue)

    ns.core.Simulator.Stop(ns.core.Seconds(sink_stop_time))
    ns.core.Simulator.Run()

    def CheckQueueDiscSize(queue):
        qSize = queue.GetQueueSize()

        avgQueueDiscSize = avgQueueDiscSize + qSize
        checkTimes = checkTimes + 1

        #check queue disc size every 1/100 of a second
        ns.core.Simulator.Schedule(ns.core.Seconds(0.01), ChecckQueueDiscSize,
                                   queue)

        print ns.core.Simulator.Now().GetSeconds() + " " + str(qsize) + "\n"

        print ns.core.Simulator.Now().GetSeconds() + " " + str(
            avgQueueDiscSize / checkTimes) + "\n"

    st = queueDiscs.Get(0).GetStats()

    if st.GetNDroppedPackets(ns.traffic_control.PieQueueDisc.FORCED_DROP) != 0:
        print "There should be no drops due to queue full\n"
        exit(1)

    if flowMonitor:
        stmp = pathOut + "/pie.flowmon"
        flowmon.SerializeToXmlFile(stmp.c_str(), 0, 0)

    if printPieStats:
        print "*** PIE stats from Node 2 queue ***"
        print "\t" + str(
            st.GetNDroppedPackets(ns.traffic_control.PieQueueDisc.UNFORCED_DROP
                                  )) + " drops due to prob mark" + "\n"
        print "\t" + str(
            st.GetNDroppedPackets(ns.traffic_control.PieQueueDisc.FORCED_DROP)
        ) + " drops due to queue limits" + "\n"

    ns.core.Simulator.Destroy()
Example #7
0
mac = ns3.NqosWifiMacHelper.Default()
mac.SetType("ns3::AdhocWifiMac")
 
wifiHelper.SetRemoteStationManager(
	"ns3::ConstantRateWifiManager", 
	"DataMode", ns3.StringValue("DsssRate1Mbps"), 
	"ControlMode", ns3.StringValue("DsssRate1Mbps"))
devices = wifiHelper.Install(wifiPhy,mac,nodes)

olsr = ns3.OlsrHelper()
    
#Add the IPv4 protocol stack to the nodes in our container
internet=ns3.InternetStackHelper()
internet.SetRoutingHelper (olsr)
 
internet.Install (nodes)
ipAddrss= ns3.Ipv4AddressHelper()
ipAddrss.SetBase(
	ns3.Ipv4Address("192.168.0.0"), 
	ns3.Ipv4Mask("255.255.255.0"));
ipContainer = ipAddrss.Assign(devices);

mobility = ns3.MobilityHelper()
positionAlloc = ns3.ListPositionAllocator()
positionAlloc.Add(ns3.Vector (100,100,0.0))
positionAlloc.Add(ns3.Vector (100,200,0.0))

mobility.SetPositionAllocator(positionAlloc)
mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel");
mobility.Install(nodes)
Example #8
0
csma.SetChannelAttribute ("DataRate", ns.network.DataRateValue(ns.network.DataRate(100000000)))
csma.SetChannelAttribute ("Delay", ns.core.TimeValue (ns.core.MicroSeconds (200)))

nodes = ns.network.NodeContainer()
nodes.Create(cmd.MaxNodes)

ethInterfaces = ns.network.NetDeviceContainer(csma.Install(nodes))

internet = ns.internet.InternetStackHelper ()
internet.SetTcp ("ns3::NscTcpL4Protocol","Library",ns.core.StringValue("liblinux2.6.26.so"))

'''
 this switches nodes 0 and 1 to NSCs Linux 2.6.26 stack.
'''
internet.Install (nodes.Get (0));
internet.Install (nodes.Get (1));

'''
this disables TCP SACK, wscale and timestamps on node 1 (the attributes represent sysctl-values)
'''

ns.core.Config.Set("/NodeList/1/$ns3::Ns3NscStack<linux2.6.26>/net.ipv4.tcp_sack",ns.core.StringValue("0"))
ns.core.Config.Set("/NodeList/1/$ns3::Ns3NscStack<linux2.6.26>/net.ipv4.tcp_timestamps",ns.core.StringValue("0"))
ns.core.Config.Set("/NodeList/1/$ns3::Ns3NscStack<linux2.6.26>/net.ipv4.tcp_window_scaling",ns.core.StringValue("0"))

if MaxNodes > 2 :
	internet.Install(nodes.Get(2))

if MaxNodes > 3 :
	'''
Example #9
0
def main(argv):
    #
    # Allow the user to override any of the defaults and the above Bind() at
    # run-time, via command-line arguments
    #
    cmd = ns.core.CommandLine()
    cmd.Parse(argv)

    #
    # But since this is a realtime script, don't allow the user to mess with
    # that.
    #
    ns.core.GlobalValue.Bind("SimulatorImplementationType",
                             ns.core.StringValue("ns3::RealtimeSimulatorImpl"))

    #
    # Explicitly create the nodes required by the topology (shown above).
    #
    print "Create nodes."
    n = ns.network.NodeContainer()
    n.Create(4)

    internet = ns.internet.InternetStackHelper()
    internet.Install(n)

    #
    # Explicitly create the channels required by the topology (shown above).
    #
    print("Create channels.")
    csma = ns.csma.CsmaHelper()
    csma.SetChannelAttribute(
        "DataRate", ns.network.DataRateValue(ns.network.DataRate(5000000)))
    csma.SetChannelAttribute("Delay",
                             ns.core.TimeValue(ns.core.MilliSeconds(2)))
    csma.SetDeviceAttribute("Mtu", ns.core.UintegerValue(1400))
    d = csma.Install(n)

    #
    # We've got the "hardware" in place.  Now we need to add IP addresses.
    #
    print("Assign IP Addresses.")
    ipv4 = ns.internet.Ipv4AddressHelper()
    ipv4.SetBase(ns.network.Ipv4Address("10.1.1.0"),
                 ns.network.Ipv4Mask("255.255.255.0"))
    i = ipv4.Assign(d)

    print("Create Applications.")

    #
    # Create a UdpEchoServer application on node one.
    #
    port = 9  # well-known echo port number
    server = ns.applications.UdpEchoServerHelper(port)
    apps = server.Install(n.Get(1))
    apps.Start(ns.core.Seconds(1.0))
    apps.Stop(ns.core.Seconds(10.0))

    #
    # Create a UdpEchoClient application to send UDP datagrams from node zero to
    # node one.
    #
    packetSize = 1024
    maxPacketCount = 500
    interPacketInterval = ns.core.Seconds(0.01)
    client = ns.applications.UdpEchoClientHelper(i.GetAddress(1), port)
    client.SetAttribute("MaxPackets", ns.core.UintegerValue(maxPacketCount))
    client.SetAttribute("Interval", ns.core.TimeValue(interPacketInterval))
    client.SetAttribute("PacketSize", ns.core.UintegerValue(packetSize))
    apps = client.Install(n.Get(0))
    apps.Start(ns.core.Seconds(2.0))
    apps.Stop(ns.core.Seconds(10.0))

    ascii = ns.network.AsciiTraceHelper()
    csma.EnableAsciiAll(ascii.CreateFileStream("realtime-udp-echo.tr"))
    csma.EnablePcapAll("realtime-udp-echo", False)

    #
    # Now, do the actual simulation.
    #
    print("Run Simulation.")
    ns.core.Simulator.Run()
    ns.core.Simulator.Destroy()
    print("Done.")
Example #10
0
wifi = ns.wifi.WifiHelper()
mac = ns.wifi.WifiMacHelper()
mac.SetType("ns3::AdhocWifiMac")
wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager", "DataMode",
                             ns.core.StringValue("OfdmRate54Mbps"))

wifiPhy = ns.wifi.YansWifiPhyHelper.Default()
wifiChannel = ns.wifi.YansWifiChannelHelper.Default()
wifiPhy.SetChannel(wifiChannel.Create())
wifiDevices = wifi.Install(wifiPhy, mac, wifiNodes)
#
#  Add the IPv4 protocol stack to the nodes in our container
#

internet = ns.internet.InternetStackHelper()
internet.Install(wifiNodes)

#  Assign IPv4 addresses to the device drivers(actually to the associated
#  IPv4 interfaces) we just created.

ipAddrs = ns.internet.Ipv4AddressHelper()
ipAddrs.SetBase(ns.network.Ipv4Address("192.168.0.0"),
                ns.network.Ipv4Mask("255.255.255.0"))
ipAddrs.Assign(wifiDevices)

#mobility = ns.mobility.MobilityHelper()
#mobility.SetPositionAllocator("ns3::GridPositionAllocator",
# "MinX", ns.core.DoubleValue(20.0),
# "MinY", ns.core.DoubleValue(20.0),
# "DeltaX", ns.core.DoubleValue(20.0),
# "DeltaY", ns.core.DoubleValue(20.0),
Example #11
0
def main(argv):
	ns.core.LogComponentEnable("UdpClient", ns.core.LOG_LEVEL_INFO)
	ns.core.LogComponentEnable("UdpServer", ns.core.LOG_LEVEL_INFO)
	cmd = ns.core.CommandLine ()
	cmd.useIpv6 = "False"
	cmd.AddValue ("useIpv6", "Use Ipv6")
	cmd.Parse (argv)

	print "Create nodes."
	n = ns.network.NodeContainer ()
	n.Create (2)

	internet = ns.internet.InternetStackHelper ()
	internet.Install (n)

	print "Create channels."
	csma = ns.csma.CsmaHelper ()
	csma.SetChannelAttribute ("DataRate", ns.core.StringValue ("5000000"))
	csma.SetChannelAttribute ("Delay", ns.core.TimeValue (ns.core.MilliSeconds (2)))
	csma.SetDeviceAttribute ("Mtu", ns.core.UintegerValue (1400))
	d = csma.Install (n)

	print "Assign IP Addresses."
	if (cmd.useIpv6 == "False"):
		ipv4 = ns.internet.Ipv4AddressHelper ()
		ipv4.SetBase (ns.network.Ipv4Address ("10.1.1.0"), ns.network.Ipv4Mask ("255.255.255.0"))
		i = ipv4.Assign (d)
		serverAddress = ns.network.Address (i.GetAddress (1))

	else:
		ipv6 = ns.internet.Ipv6AddressHelper ()
		ipv6.SetBase (ns.network.Ipv6Address ("2001:0000:f00d:cafe::"), ns.network.Ipv6Prefix (64))
		i6 = ipv6.Assign (d)
		serverAddress = ns.network.Address (i6.GetAddress (1, 1))


	print "Create Applications."


	port = 4000
	server = ns.applications.UdpEchoServerHelper (port)
	serverapps = server.Install (n.Get (1))
	serverapps.Start (ns.core.Seconds (1.0))
	serverapps.Stop (ns.core.Seconds (10.0))

	MaxPacketSize = 1024;
	interPacketInterval = ns.core.Seconds (0.05)
	maxPacketCount = 320;

	client = ns.applications.UdpEchoClientHelper ( serverAddress, port)


	client.SetAttribute ("MaxPackets", ns.core.UintegerValue (maxPacketCount))
  	client.SetAttribute ("Interval", ns.core.TimeValue (interPacketInterval))
 	client.SetAttribute ("PacketSize", ns.core.UintegerValue (MaxPacketSize))

	clientapps = client.Install (n.Get (0))
	serverapps.Start (ns.core.Seconds (2.0))
	serverapps.Stop (ns.core.Seconds (10.0))



	ascii = ns.network.AsciiTraceHelper ()
	csma.EnableAsciiAll (ascii.CreateFileStream ("udp-client-serv.tr"))
	csma.EnablePcapAll ("udp-client-serv", False)
	print "Run Simulation."
	ns.core.Simulator.Run ()
	ns.core.Simulator.Destroy ()
	print "Done."
def main(argv): 
    
    
    
    
    backboneNodes = 10
    infraNodes = 5
    lanNodes = 5
    stopTime = 10

    
    
    
    
    ns.core.Config.SetDefault("ns3::OnOffApplication::PacketSize", ns.core.StringValue("210"))
    ns.core.Config.SetDefault("ns3::OnOffApplication::DataRate", ns.core.StringValue("448kb/s"))

    
    
    
    
    
    cmd = ns.core.CommandLine()
    
    
    
    

    
    
    
    
    cmd.Parse(argv)

    
    
    
    
    

    
    
    
    
    backbone = ns.network.NodeContainer()
    backbone.Create(backboneNodes)
    
    
    
    
    wifi = ns.wifi.WifiHelper()
    mac = ns.wifi.NqosWifiMacHelper.Default()
    mac.SetType("ns3::AdhocWifiMac")
    wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager",
                                  "DataMode", ns.core.StringValue("OfdmRate54Mbps"))
    wifiPhy = ns.wifi.YansWifiPhyHelper.Default()
    wifiChannel = ns.wifi.YansWifiChannelHelper.Default()
    wifiPhy.SetChannel(wifiChannel.Create())
    backboneDevices = wifi.Install(wifiPhy, mac, backbone)
    
    
    
    print "Enabling OLSR routing on all backbone nodes"
    internet = ns.internet.InternetStackHelper()
    olsr = ns.olsr.OlsrHelper()
    internet.SetRoutingHelper(olsr); 
    internet.Install(backbone);
    
    internet.Reset()
    
    
    
    
    ipAddrs = ns.internet.Ipv4AddressHelper()
    ipAddrs.SetBase(ns.network.Ipv4Address("192.168.0.0"), ns.network.Ipv4Mask("255.255.255.0"))
    ipAddrs.Assign(backboneDevices)

    
    
    
    
    mobility = ns.mobility.MobilityHelper()
    positionAlloc = ns.mobility.ListPositionAllocator()
    x = 0.0
    for i in range(backboneNodes):
        positionAlloc.Add(ns.core.Vector(x, 0.0, 0.0))
        x += 5.0
    mobility.SetPositionAllocator(positionAlloc)
    mobility.SetMobilityModel("ns3::RandomDirection2dMobilityModel",
                               "Bounds", ns.mobility.RectangleValue(ns.mobility.Rectangle(0, 1000, 0, 1000)),
                               "Speed", ns.core.RandomVariableValue(ns.core.ConstantVariable(2000)),
                               "Pause", ns.core.RandomVariableValue(ns.core.ConstantVariable(0.2)))
    mobility.Install(backbone)

    
    
    
    
    

    
    
    ipAddrs.SetBase(ns.network.Ipv4Address("172.16.0.0"), ns.network.Ipv4Mask("255.255.255.0"))

    for i in range(backboneNodes):
        print "Configuring local area network for backbone node ", i
        
        
        
        
        
        newLanNodes = ns.network.NodeContainer()
        newLanNodes.Create(lanNodes - 1)
        
        lan = ns.network.NodeContainer(ns.network.NodeContainer(backbone.Get(i)), newLanNodes)
        
        
        
        
        csma = ns.csma.CsmaHelper()
        csma.SetChannelAttribute("DataRate", ns.network.DataRateValue(ns.network.DataRate(5000000)))
        csma.SetChannelAttribute("Delay", ns.core.TimeValue(ns.core.MilliSeconds(2)))
        lanDevices = csma.Install(lan)
        
        
        
        internet.Install(newLanNodes)
        
        
        
        
        ipAddrs.Assign(lanDevices)
        
        
        
        
        ipAddrs.NewNetwork()

    
    
    
    
    

    
    
    ipAddrs.SetBase(ns.network.Ipv4Address("10.0.0.0"), ns.network.Ipv4Mask("255.255.255.0"))

    for i in range(backboneNodes):
        print "Configuring wireless network for backbone node ", i
        
        
        
        
        
        stas = ns.network.NodeContainer()
        stas.Create(infraNodes - 1)
        
        infra = ns.network.NodeContainer(ns.network.NodeContainer(backbone.Get(i)), stas)
        
        
        
        ssid = ns.wifi.Ssid('wifi-infra' + str(i))
        wifiInfra = ns.wifi.WifiHelper.Default()
        wifiPhy.SetChannel(wifiChannel.Create())
        wifiInfra.SetRemoteStationManager('ns3::ArfWifiManager')
        macInfra = ns.wifi.NqosWifiMacHelper.Default();
        macInfra.SetType("ns3::StaWifiMac",
                         "Ssid", ns.wifi.SsidValue(ssid),
                         "ActiveProbing", ns.core.BooleanValue(False))

        
        staDevices = wifiInfra.Install(wifiPhy, macInfra, stas)
        
        macInfra.SetType("ns3::ApWifiMac",
                         "Ssid", ns.wifi.SsidValue(ssid),
                         "BeaconGeneration", ns.core.BooleanValue(True),
                         "BeaconInterval", ns.core.TimeValue(ns.core.Seconds(2.5)))
        apDevices = wifiInfra.Install(wifiPhy, macInfra, backbone.Get(i))
        
        infraDevices = ns.network.NetDeviceContainer(apDevices, staDevices)

        
        
        internet.Install(stas)
        
        
        
        
        ipAddrs.Assign(infraDevices)
        
        
        
        
        ipAddrs.NewNetwork()
        
        
        
        
        subnetAlloc = ns.mobility.ListPositionAllocator()
        for j in range(infra.GetN()):
            subnetAlloc.Add(ns.core.Vector(0.0, j, 0.0))

        mobility.PushReferenceMobilityModel(backbone.Get(i))
        mobility.SetPositionAllocator(subnetAlloc)
        mobility.SetMobilityModel("ns3::RandomDirection2dMobilityModel",
                                  "Bounds", ns.mobility.RectangleValue(ns.mobility.Rectangle(-25, 25, -25, 25)),
                                  "Speed", ns.core.RandomVariableValue(ns.core.ConstantVariable(30)),
                                  "Pause", ns.core.RandomVariableValue(ns.core.ConstantVariable(0.4)))
        mobility.Install(infra)

    
    
    
    
    

    
    
    print "Create Applications."
    port = 9   

    
    
    assert(lanNodes >= 5)
    appSource = ns.network.NodeList.GetNode(11)
    appSink = ns.network.NodeList.GetNode(13)
    remoteAddr = ns.network.Ipv4Address("172.16.0.5")

    onoff = ns.applications.OnOffHelper("ns3::UdpSocketFactory", 
                            ns.network.Address(ns.network.InetSocketAddress(remoteAddr, port)))
    onoff.SetAttribute("OnTime", ns.core.RandomVariableValue(ns.core.ConstantVariable(1)))
    onoff.SetAttribute("OffTime", ns.core.RandomVariableValue(ns.core.ConstantVariable(0)))
    apps = onoff.Install(ns.network.NodeContainer(appSource))
    apps.Start(ns.core.Seconds(3.0))
    apps.Stop(ns.core.Seconds(20.0))

    
    sink = ns.applications.PacketSinkHelper("ns3::UdpSocketFactory", 
                                ns.network.InetSocketAddress(ns.network.Ipv4Address.GetAny(), port))
    apps = sink.Install(ns.network.NodeContainer(appSink))
    apps.Start(ns.core.Seconds(3.0))

    
    
    
    
    

    print "Configure Tracing."
    
    
    
    
    
    
    
    
    print "(tracing not done for Python)"
    
    
    

    
    wifiPhy.EnablePcap("mixed-wireless", backboneDevices)
    
    csma = ns.csma.CsmaHelper()
    csma.EnablePcapAll("mixed-wireless", False)







    
    
    
    
    

    print "Run Simulation."
    ns.core.Simulator.Stop(ns.core.Seconds(stopTime))
    ns.core.Simulator.Run()
    ns.core.Simulator.Destroy()
def main(argv):

    numUes = 1
    numEnbs = 2
    numBearersPerUe = 0
    distance = 500.0  # m
    yForUe = 500.0  # m
    speed = 20.0  # m/s
    simTime = float(numEnbs +
                    1) * distance / speed  # 1500 m / 20 m/s = 75 secs
    enbTxPowerDbm = 46.0

    # Enable logging
    ns.core.LogComponentEnable("A2A4RsrqHandoverAlgorithm",
                               ns.core.LOG_LEVEL_LOGIC)

    # change some default attributes so that they are reasonable for
    # this scenario, but do this before processing command line
    # arguments, so that the user is allowed to override these settings
    #ns.core.Config.SetDefault ("ns3::UdpClient::Interval", ns.core.TimeValue (ns.core.MilliSeconds (10)))
    #ns.core.Config.SetDefault ("ns3::UdpClient::MaxPackets", ns.core.UintegerValue (1000000))
    ns.core.Config.SetDefault("ns3::LteHelper::UseIdealRrc",
                              ns.core.BooleanValue(1))

    # Command line arguments
    #cmd = ns.core.CommandLine()
    #cmd.AddValue ("simTime", "Total duration of the simulation (in seconds)", simTime)
    #cmd.AddValue ("speed", "Speed of the UE (default = 20 m/s)", speed);
    #cmd.AddValue ("enbTxPowerDbm", "TX power [dBm] used by HeNBs (default = 46.0)", enbTxPowerDbm)
    #cmd.Parse(argv)

    lteHelper = ns.lte.LteHelper()
    epcHelper = ns.lte.PointToPointEpcHelper()
    lteHelper.SetEpcHelper(epcHelper)

    lteHelper.SetSchedulerType("ns3::RrFfMacScheduler")

    lteHelper.SetHandoverAlgorithmType("ns3::A2A4RsrqHandoverAlgorithm")
    lteHelper.SetHandoverAlgorithmAttribute("ServingCellThreshold",
                                            ns.core.UintegerValue(30))
    lteHelper.SetHandoverAlgorithmAttribute("NeighbourCellOffset",
                                            ns.core.UintegerValue(1))

    pgw = epcHelper.GetPgwNode()

    # Create a single RemoteHost
    remoteHostContainer = ns.network.NodeContainer()
    remoteHostContainer.Create(1)
    remoteHost = remoteHostContainer.Get(0)

    internet = ns.internet.InternetStackHelper()
    internet.Install(remoteHostContainer)

    # Create the Internet
    p2ph = ns.point_to_point.PointToPointHelper()
    p2ph.SetDeviceAttribute(
        "DataRate", ns.network.DataRateValue(ns.network.DataRate("100Gb/s")))
    p2ph.SetDeviceAttribute("Mtu", ns.core.UintegerValue(1500))
    p2ph.SetChannelAttribute("Delay",
                             ns.core.TimeValue(ns.core.Seconds(0.010)))
    internetDevices = p2ph.Install(pgw, remoteHost)
    ipv4h = ns.internet.Ipv4AddressHelper()
    ipv4h.SetBase(ns.network.Ipv4Address("1.0.0.0"),
                  ns.network.Ipv4Mask("255.0.0.0"))
    internetIpIfaces = ipv4h.Assign(internetDevices)
    remoteHostAddr = internetIpIfaces.GetAddress(1)

    # Routing of the Internet Host (towards the LTE network)
    ipv4RoutingHelper = ns.internet.Ipv4StaticRoutingHelper()
    remoteHostStaticRouting = ipv4RoutingHelper.GetStaticRouting(
        remoteHost.GetObject(ns.internet.Ipv4.GetTypeId()))
    # interface 0 is localhost, 1 is the p2p device
    remoteHostStaticRouting.AddNetworkRouteTo(
        ns.network.Ipv4Address("7.0.0.0"), ns.network.Ipv4Mask("255.0.0.0"), 1)

    #    * Network topology:
    #    *
    #    *      |     + --------------------------------------------------------->
    #    *      |     UE
    #    *      |
    #    *      |               d                   d                   d
    #    *    y |     |-------------------x-------------------x-------------------
    #    *      |     |                 eNodeB              eNodeB
    #    *      |   d |
    #    *      |     |
    #    *      |     |                                             d = distance
    #    *            o (0, 0, 0)                                   y = yForUe

    enbNodes = ns.network.NodeContainer()
    ueNodes = ns.network.NodeContainer()
    enbNodes.Create(numEnbs)
    ueNodes.Create(numUes)

    # Install Mobility Model in eNB
    enbPositionAlloc = ns.mobility.ListPositionAllocator()
    for i in range(0, numEnbs):
        enbPosition = ns.core.Vector(distance * (i + 1), distance, 0)
        enbPositionAlloc.Add(enbPosition)

    enbMobility = ns.mobility.MobilityHelper()
    enbMobility.SetMobilityModel("ns3::ConstantPositionMobilityModel")
    enbMobility.SetPositionAllocator(enbPositionAlloc)
    enbMobility.Install(enbNodes)

    # Install Mobility Model in UE
    ueMobility = ns.mobility.MobilityHelper()
    ueMobility.SetMobilityModel("ns3::ConstantVelocityMobilityModel")
    ueMobility.Install(ueNodes)
    ueNodes.Get(0).GetObject(
        ns.mobility.MobilityModel.GetTypeId()).SetPosition(
            ns.core.Vector(0, yForUe, 0))
    ueNodes.Get(0).GetObject(
        ns.mobility.ConstantVelocityMobilityModel.GetTypeId()).SetVelocity(
            ns.core.Vector(speed, 0, 0))

    # Install LTE Devices in eNB and UEs
    ns.core.Config.SetDefault("ns3::LteEnbPhy::TxPower",
                              ns.core.DoubleValue(enbTxPowerDbm))
    enbLteDevs = lteHelper.InstallEnbDevice(enbNodes)
    ueLteDevs = lteHelper.InstallUeDevice(ueNodes)

    # Install the IP stack on the UEs
    internet.Install(ueNodes)
    ueIpIfaces = epcHelper.AssignUeIpv4Address(ueLteDevs)

    # Attach all UEs to the first eNodeB
    for i in range(0, numUes):
        lteHelper.Attach(ueLteDevs.Get(i), enbLteDevs.Get(0))

    # NS_LOG_LOGIC ("setting up applications");
    # Install and start applications on UEs and remote host
    dlPort = 10000
    ulPort = 20000

    # randomize a bit start times to avoid simulation artifacts
    # (e.g., buffer overflows due to packet transmissions happening
    # exactly at the same time)
    startTimeSeconds = ns.core.UniformRandomVariable()
    startTimeSeconds.SetAttribute("Min", ns.core.DoubleValue(0))
    startTimeSeconds.SetAttribute("Max", ns.core.DoubleValue(0.010))

    for u in range(0, numUes):
        ue = ueNodes.Get(u)
        ueTmpContainer = ns.network.NodeContainer()
        ueTmpContainer.Add(ue)
        # Set the default gateway for the UE
        ueStaticRouting = ipv4RoutingHelper.GetStaticRouting(
            ue.GetObject(ns.internet.Ipv4.GetTypeId()))
        ueStaticRouting.SetDefaultRoute(epcHelper.GetUeDefaultGatewayAddress(),
                                        1)
        for b in range(0, numBearersPerUe):
            dlPort += 1
            ulPort += 1
            clientApps = ns.network.ApplicationContainer()
            serverApps = ns.network.ApplicationContainer()

            # NS_LOG_LOGIC ("installing UDP DL app for UE " << u);
            dlClientHelper = ns.applications.UdpClientHelper(
                ueIpIfaces.GetAddress(u), dlPort)
            clientApps.Add(dlClientHelper.Install(remoteHostContainer))
            dlPacketSinkHelper = ns.applications.PacketSinkHelper("ns3::UdpSocketFactory", \
                                                                  ns.network.InetSocketAddress (ns.network.Ipv4Address.GetAny (), dlPort))
            serverApps.Add(dlPacketSinkHelper.Install(ueTmpContainer))

            # NS_LOG_LOGIC ("installing UDP UL app for UE " << u);
            #              ulClientHelper = ns.applications.UdpClientHelper(remoteHostAddr, ulPort)
            #              clientApps.Add (ulClientHelper.Install (ueTmpContainer))
            #              ulPacketSinkHelper = ns.applications.PacketSinkHelper("ns3::UdpSocketFactory", \
            #                                                                    ns.network.InetSocketAddress (ns.network.Ipv4Address.GetAny (), ulPort))
            #              serverApps.Add (ulPacketSinkHelper.Install (remoteHostContainer))

            tft = ns.lte.EpcTft()
            dlpf = ns.lte.EpcTft.PacketFilter()
            dlpf.localPortStart = dlPort
            dlpf.localPortEnd = dlPort
            tft.Add(dlpf)
            ulpf = ns.lte.EpcTft.PacketFilter()
            ulpf.remotePortStart = ulPort
            ulpf.remotePortEnd = ulPort
            tft.Add(ulpf)
            bearer = ns.lte.EpsBearer(ns.lte.EpsBearer.NGBR_VIDEO_TCP_DEFAULT)
            lteHelper.ActivateDedicatedEpsBearer(ueLteDevs.Get(u), bearer, tft)

            startTime = ns.core.Seconds(startTimeSeconds.GetValue())
            serverApps.Start(startTime)
            clientApps.Start(startTime)

    # Add X2 interface
    lteHelper.AddX2Interface(enbNodes)

    lteHelper.EnablePhyTraces()
    lteHelper.EnableMacTraces()
    lteHelper.EnableRlcTraces()
    lteHelper.EnablePdcpTraces()

    rlcStats = lteHelper.GetRlcStats()
    rlcStats.SetAttribute("EpochDuration",
                          ns.core.TimeValue(ns.core.Seconds(1.0)))
    pdcpStats = lteHelper.GetPdcpStats()
    pdcpStats.SetAttribute("EpochDuration",
                           ns.core.TimeValue(ns.core.Seconds(1.0)))

    # Set RRC callbacks
    #     ns.core.Config.Connect ("/NodeList/*/DeviceList/*/LteUeRrc/ConnectionEstablished", \
    #                             NotifyConnectionEstablishedUe)
    enbLteDevs.Get(0).GetRrc().SetConnectionEstablishedCallback(
        NotifyConnectionEstablishedEnb)
    enbLteDevs.Get(0).GetRrc().SetHandoverJoiningTimeoutCallback(
        NotifyHandoverJoiningTimeout)
    enbLteDevs.Get(0).GetRrc().SetHandoverLeavingTimeoutCallback(
        NotifyHandoverLeavingTimeout)

    print("Run Simulation.")
    ns.core.Simulator.Stop(ns.core.Seconds(simTime))
    ns.core.Simulator.Run()
    ns.core.Simulator.Destroy()
Example #14
0
ripRouting.ExcludeInterface(d, 3)

ripRouting.SetInterfaceMetric(c, 3, 10)
ripRouting.SetInterfaceMetric(d, 1, 10)

listRH = ns.internet.Ipv4ListRoutingHelper()
listRH.Add(ripRouting, 0)
'''
//  Ipv4StaticRoutingHelper staticRh;
//  listRH.Add (staticRh, 5);
'''

internet = ns.internet.InternetStackHelper()
internet.SetIpv6StackInstall(False)
internet.SetRoutingHelper(listRH)
internet.Install(routers)

internetNodes = ns.internet.InternetStackHelper()
internetNodes.SetIpv6StackInstall(False)
internetNodes.Install(nodes)

#Assign addresses.
#The source and destination networks have global addresses
#The "core" network just needs link-local addresses for routing.
#We assign global addresses to the routers as well to receive
#ICMPv6 errors.

print "Assign IPv4 Addresses."
ipv4 = ns.internet.Ipv4AddressHelper()

ipv4.SetBase(ns.network.Ipv4Address("10.0.0.0"),
Example #15
0
    def Run(self, *positional_parameters, **keyword_parameters):
        ns.network.Packet.EnablePrinting()

        if "SINKS" in os.environ:
            self.m_nSinks = int(os.environ["SINKS"])
        if "TXP" in os.environ:
            self.m_txp = float(os.environ["TXP"])
        if "TOTAL_TIME" in os.environ:
            self.m_total_time = int(os.environ["TOTAL_TIME"])
        if "NODES" in os.environ:
            self.m_nodes = int(os.environ["NODES"])
        if "PROTOCOL" in os.environ:
            self.m_protocol = int(os.environ["PROTOCOL"])
        if "NODE_SPEED" in os.environ:
            self.m_node_speed = int(os.environ["NODE_SPEED"])
        if "NODE_PAUSE" in os.environ:
            self.m_node_pause = int(os.environ["NODE_PAUSE"])
        if "FILE_NAME" in os.environ:
            self.m_CSVfileName = os.environ["FILE_NAME"]

        if 'nSinks' in keyword_parameters:
            self.m_nSinks = keyword_parameters['nSinks']
        if 'txp' in keyword_parameters:
            self.m_txp = keyword_parameters['txp']
        if 'TotalTime' in keyword_parameters:
            self.m_total_time = keyword_parameters['TotalTime']
        if 'Nodes' in keyword_parameters:
            self.m_nodes = keyword_parameters['Nodes']
        if 'Protocol' in keyword_parameters:
            self.m_protocol = keyword_parameters['Protocol']
        if 'NodeSpeed' in keyword_parameters:
            self.m_node_speed = keyword_parameters['NodeSpeed']
        if 'NodePause' in keyword_parameters:
            self.m_node_pause = keyword_parameters['NodePause']
        if 'CSVfileName' in keyword_parameters:
            self.m_CSVfileName = keyword_parameters['CSVfileName']

        self.m_CSVfileName += "." + str(time.time())
        rate = "2048bps"
        phyMode = "DsssRate11Mbps"
        tr_name = self.m_CSVfileName + "-compare"
        self.m_protocolName = "protocol"

        ns.core.Config.SetDefault("ns3::OnOffApplication::PacketSize",
                                  ns.core.StringValue("64"))
        ns.core.Config.SetDefault("ns3::OnOffApplication::DataRate",
                                  ns.core.StringValue(rate))

        ns.core.Config.SetDefault(
            "ns3::WifiRemoteStationManager::NonUnicastMode",
            ns.core.StringValue(phyMode))

        adhocNodes = ns.network.NodeContainer()
        adhocNodes.Create(self.m_nodes)

        wifi = ns.wifi.WifiHelper()
        wifi.SetStandard(ns.wifi.WIFI_PHY_STANDARD_80211b)

        wifiPhy = ns.wifi.YansWifiPhyHelper.Default()
        wifiChannel = ns.wifi.YansWifiChannelHelper()
        wifiChannel.SetPropagationDelay(
            "ns3::ConstantSpeedPropagationDelayModel")
        wifiChannel.AddPropagationLoss("ns3::FriisPropagationLossModel")
        wifiPhy.SetChannel(wifiChannel.Create())

        wifiMac = ns.wifi.WifiMacHelper()
        wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager",
                                     "DataMode", ns.core.StringValue(phyMode),
                                     "ControlMode",
                                     ns.core.StringValue(phyMode))

        wifiPhy.Set("TxPowerStart", ns.core.DoubleValue(self.m_txp))
        wifiPhy.Set("TxPowerEnd", ns.core.DoubleValue(self.m_txp))

        wifiMac.SetType("ns3::AdhocWifiMac")
        adhocDevices = wifi.Install(wifiPhy, wifiMac,
                                    adhocNodes)  # type: NetDeviceContainer

        mobilityAdhoc = ns.mobility.MobilityHelper()
        streamIndex = 0  # used to get consistent mobility across scenarios

        pos = ns.core.ObjectFactory()
        pos.SetTypeId("ns3::RandomRectanglePositionAllocator")
        pos.Set(
            "X",
            ns.core.StringValue(
                "ns3::UniformRandomVariable[Min=0.0|Max=300.0]"))
        pos.Set(
            "Y",
            ns.core.StringValue(
                "ns3::UniformRandomVariable[Min=0.0|Max=1500.0]"))

        # Same as: Ptr<PositionAllocator> taPositionAlloc = pos.Create ()->GetObject<PositionAllocator> ();
        taPositionAlloc = pos.Create().GetObject(
            ns.mobility.PositionAllocator.GetTypeId(
            ))  # type: Ptr<PositionAllocator>
        streamIndex += taPositionAlloc.AssignStreams(streamIndex)

        ssSpeed = "ns3::UniformRandomVariable[Min=0.0|Max=%s]" % self.m_node_speed
        ssPause = "ns3::ConstantRandomVariable[Constant=%s]" % self.m_node_pause

        mobilityAdhoc.SetMobilityModel("ns3::RandomWaypointMobilityModel",
                                       "Speed", ns.core.StringValue(ssSpeed),
                                       "Pause", ns.core.StringValue(ssPause),
                                       "PositionAllocator",
                                       ns.core.PointerValue(taPositionAlloc))
        mobilityAdhoc.SetPositionAllocator(taPositionAlloc)
        mobilityAdhoc.Install(adhocNodes)
        streamIndex += mobilityAdhoc.AssignStreams(adhocNodes, streamIndex)
        # NS_UNUSED(streamIndex) # From this point, streamIndex is unused

        aodv = ns.aodv.AodvHelper()
        olsr = ns.olsr.OlsrHelper()
        dsdv = ns.dsdv.DsdvHelper()
        dsr = ns.dsr.DsrHelper()
        dsrMain = ns.dsr.DsrMainHelper()
        list = ns.internet.Ipv4ListRoutingHelper()
        internet = ns.internet.InternetStackHelper()

        if self.m_protocol == 1:
            list.Add(olsr, 100)
            self.m_protocolName = "OLSR"
        elif self.m_protocol == 2:
            list.Add(aodv, 100)
            self.m_protocolName = "AODV"
        elif self.m_protocol == 3:
            list.Add(dsdv, 100)
            self.m_protocolName = "DSDV"
        elif self.m_protocol == 4:
            self.m_protocolName = "DSR"
        else:
            print("No such protocol:%s" % str(self.m_protocol)
                  )  # NS_FATAL_ERROR ("No such protocol:" << m_protocol);

        if self.m_protocol < 4:
            internet.SetRoutingHelper(list)
            internet.Install(adhocNodes)
        elif self.m_protocol == 4:
            internet.Install(adhocNodes)
            dsrMain.Install(dsr, adhocNodes)

        print("assigning ip address")

        addressAdhoc = ns.internet.Ipv4AddressHelper()
        addressAdhoc.SetBase(ns.network.Ipv4Address("10.1.1.0"),
                             ns.network.Ipv4Mask("255.255.255.0"))
        adhocInterfaces = addressAdhoc.Assign(adhocDevices)

        onoff1 = ns.applications.OnOffHelper("ns3::UdpSocketFactory",
                                             ns.network.Address())
        onoff1.SetAttribute(
            "OnTime",
            ns.core.StringValue("ns3::ConstantRandomVariable[Constant=1.0]"))
        onoff1.SetAttribute(
            "OffTime",
            ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0.0]"))

        for i in range(0, self.m_nSinks):
            # Ptr<Socket> sink = SetupPacketReceive (adhocInterfaces.GetAddress (i), adhocNodes.Get (i));
            sink = self.SetupPacketReceive(adhocInterfaces.GetAddress(i),
                                           adhocNodes.Get(i))

            remoteAddress = ns.network.AddressValue(
                ns.network.InetSocketAddress(adhocInterfaces.GetAddress(i),
                                             self.port))
            onoff1.SetAttribute("Remote", remoteAddress)

            # Ptr<UniformRandomVariable> var = CreateObject<UniformRandomVariable> ();
            posURV = ns.core.ObjectFactory()
            posURV.SetTypeId("ns3::UniformRandomVariable")
            var = posURV.Create().GetObject(
                ns.core.UniformRandomVariable.GetTypeId())

            temp = onoff1.Install(
                adhocNodes.Get(i +
                               self.m_nSinks))  # type: ApplicationContainer
            temp.Start(ns.core.Seconds(var.GetValue(100.0, 101.0)))
            temp.Stop(ns.core.Seconds(self.m_total_time))

        ss = self.m_nSinks
        nodes = str(ss)

        ss2 = self.m_node_speed
        sNodeSpeed = str(ss2)

        ss3 = self.m_node_pause
        sNodePause = str(ss3)

        ss4 = rate
        sRate = str(ss4)

        tr_name = tr_name + "_" + \
                  self.m_protocolName + "_" + \
                  nodes + "sinks_" + \
                  sNodeSpeed + "speed_" + \
                  sNodePause + "pause_" + \
                  sRate + "rate"

        self.m_CSVfileName = tr_name

        ascii = ns.network.AsciiTraceHelper()

        ns.mobility.MobilityHelper.EnableAsciiAll(
            ascii.CreateFileStream(
                os.path.join(__workdir__, "%s.mob" % tr_name)))

        flowmon_helper = ns.flow_monitor.FlowMonitorHelper()

        monitor = flowmon_helper.InstallAll()
        monitor = flowmon_helper.GetMonitor()
        monitor.SetAttribute("DelayBinWidth", ns.core.DoubleValue(0.001))
        monitor.SetAttribute("JitterBinWidth", ns.core.DoubleValue(0.001))
        monitor.SetAttribute("PacketSizeBinWidth", ns.core.DoubleValue(20))

        print("Run Simulation.")

        self.WriteHeaderCsv()
        self.CheckThroughput()

        ns.core.Simulator.Stop(ns.core.Seconds(self.m_total_time))
        ns.core.Simulator.Run()

        monitor.CheckForLostPackets()
        classifier = flowmon_helper.GetClassifier()

        if self.m_debugger:
            for flow_id, flow_stats in monitor.GetFlowStats():

                with open(
                        os.path.join(__workdir__,
                                     (self.m_CSVfileName + ".txt")),
                        'a') as file:

                    t = classifier.FindFlow(flow_id)
                    proto = {6: 'TCP', 17: 'UDP'}[t.protocol]
                    file.write("FlowID: %i (%s %s/%s --> %s/%i)\n" % \
                      (flow_id, proto, t.sourceAddress, t.sourcePort, t.destinationAddress, t.destinationPort))
                    self.print_stats(file, flow_stats)
                    file.close()

        monitor.SerializeToXmlFile(
            os.path.join(__workdir__, "%s.flowmon" % tr_name), True, True)

        delays = []
        for flow_id, flow_stats in monitor.GetFlowStats():
            tupl = classifier.FindFlow(flow_id)
            if tupl.protocol == 17 and tupl.sourcePort == 698:
                continue

            if flow_stats.rxPackets == 0:
                delays.append(0)
            else:
                delays.append(flow_stats.delaySum.GetSeconds() /
                              flow_stats.rxPackets)

        plt.hist(delays, 20)
        plt.xlabel("Delay (s)")
        plt.ylabel("Number of Flows")
        plt.savefig(os.path.join(__workdir__, '%s.png' % tr_name), dpi=75)
        plt.show()

        ns.core.Simulator.Destroy()
Example #16
0
def main(argv):

    #
    # Allow the user to override any of the defaults and the above Bind() at
    # run-time, via command-line arguments
    #
    cmd = ns.core.CommandLine()

    cmd.packetSize = 1024
    cmd.packetCount = 10
    cmd.packetInterval = 1.0

    # Socket options for IPv4, currently TOS, TTL, RECVTOS, and RECVTTL
    cmd.ipTos = 0
    cmd.ipRecvTos = True
    cmd.ipTtl = 0
    cmd.ipRecvTtl = True

    cmd.AddValue("PacketSize", "Packet size in bytes")
    cmd.AddValue("PacketCount", "Number of packets to send")
    cmd.AddValue("Interval", "Interval between packets")
    cmd.AddValue("IP_TOS", "IP_TOS")
    cmd.AddValue("IP_RECVTOS", "IP_RECVTOS")
    cmd.AddValue("IP_TTL", "IP_TTL")
    cmd.AddValue("IP_RECVTTL", "IP_RECVTTL")
    cmd.Parse(argv)

    packetSize = int(cmd.packetSize)
    packetCount = int(cmd.packetCount)
    packetInterval = float(cmd.packetInterval)
    ipTos = int(cmd.ipTos)
    ipRecvTos = bool(cmd.ipRecvTos)
    ipTtl = int(cmd.ipTtl)
    ipRecvTtl = bool(cmd.ipRecvTtl)

    print("Create nodes.")
    n = ns.network.NodeContainer()
    n.Create(2)

    internet = ns.internet.InternetStackHelper()
    internet.Install(n)

    print("Create channels.")
    csma = ns.csma.CsmaHelper()
    csma.SetChannelAttribute(
        "DataRate", ns.network.DataRateValue(ns.network.DataRate(5000000)))
    csma.SetChannelAttribute("Delay",
                             ns.core.TimeValue(ns.core.MilliSeconds(2)))
    csma.SetDeviceAttribute("Mtu", ns.core.UintegerValue(1400))
    d = csma.Install(n)

    print("Assign IP addresses.")
    ipv4 = ns.internet.Ipv4AddressHelper()
    ipv4.SetBase(ns.network.Ipv4Address("10.1.1.0"),
                 ns.network.Ipv4Mask("255.255.255.0"))
    i = ipv4.Assign(d)
    serverAddress = ns.network.Address(i.GetAddress(1))

    print("Create sockets.")
    # Receiver socket on n1
    tid = ns3.TypeId.LookupByName("ns3::UdpSocketFactory")
    recvSink = ns3.Socket.CreateSocket(n.Get(1), tid)
    local = ns3.InetSocketAddress(ns3.Ipv4Address.GetAny(), 4477)
    recvSink.SetIpRecvTos(ipRecvTos)
    recvSink.SetIpRecvTtl(ipRecvTtl)
    recvSink.Bind(local)
    recvSink.SetRecvCallback(ReceivePacket)

    # Sender socket on n0
    source = ns3.Socket.CreateSocket(n.Get(0), tid)
    remote = ns.network.InetSocketAddress(i.GetAddress(1), 4477)

    # Set socket options, it is also possible to set the options after the socket has been created/connected.
    if ipTos > 0:
        source.SetIpTos(ipTos)

    if ipTtl > 0:
        source.SetIpTtl(ipTtl)
    source.Connect(remote)

    ascii = ns.network.AsciiTraceHelper()
    csma.EnableAsciiAll(ascii.CreateFileStream("socket-options-ipv4.tr"))
    csma.EnablePcapAll("socket-options-ipv4", False)

    # Schedule SendPacket
    interPacketInterval = ns.core.Seconds(packetInterval)
    ns.core.Simulator.ScheduleWithContext(source.GetNode().GetId(),
                                          ns.core.Seconds(1.0), SendPacket,
                                          source, packetSize, packetCount,
                                          interPacketInterval)

    print("Run Simulation.")
    ns.core.Simulator.Run()
    ns.core.Simulator.Destroy()
    print("Done.")
Example #17
0
def main(argv):

    cmd = ns.core.CommandLine()

    cmd.NumNodesSide = None
    cmd.AddValue(
        "NumNodesSide",
        "Grid side number of nodes (total number of nodes will be this number squared)"
    )

    cmd.Results = None
    cmd.AddValue("Results", "Write XML results to file")

    cmd.Plot = None
    cmd.AddValue("Plot", "Plot the results using the matplotlib python module")

    cmd.Parse(argv)

    wifi = ns.wifi.WifiHelper.Default()
    wifiMac = ns.wifi.NqosWifiMacHelper.Default()
    wifiPhy = ns.wifi.YansWifiPhyHelper.Default()
    wifiChannel = ns.wifi.YansWifiChannelHelper.Default()
    wifiPhy.SetChannel(wifiChannel.Create())
    ssid = ns.wifi.Ssid("wifi-default")
    wifi.SetRemoteStationManager("ns3::ArfWifiManager")
    wifiMac.SetType("ns3::AdhocWifiMac", "Ssid", ns.wifi.SsidValue(ssid))

    internet = ns.internet.InternetStackHelper()
    list_routing = ns.internet.Ipv4ListRoutingHelper()
    olsr_routing = ns.olsr.OlsrHelper()
    static_routing = ns.internet.Ipv4StaticRoutingHelper()
    list_routing.Add(static_routing, 0)
    list_routing.Add(olsr_routing, 100)
    internet.SetRoutingHelper(list_routing)

    ipv4Addresses = ns.internet.Ipv4AddressHelper()
    ipv4Addresses.SetBase(ns.network.Ipv4Address("10.0.0.0"),
                          ns.network.Ipv4Mask("255.255.255.0"))

    port = 9
    onOffHelper = ns.applications.OnOffHelper(
        "ns3::UdpSocketFactory",
        ns.network.Address(
            ns.network.InetSocketAddress(ns.network.Ipv4Address("10.0.0.1"),
                                         port)))
    onOffHelper.SetAttribute(
        "DataRate", ns.network.DataRateValue(ns.network.DataRate("100kbps")))
    onOffHelper.SetAttribute(
        "OnTime",
        ns.core.StringValue("ns3::ConstantRandomVariable[Constant=1]"))
    onOffHelper.SetAttribute(
        "OffTime",
        ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0]"))

    addresses = []
    nodes = []

    num_nodes_side = NUM_NODES_SIDE
    for xi in range(num_nodes_side):
        for yi in range(num_nodes_side):

            node = ns.network.Node()
            nodes.append(node)

            internet.Install(ns.network.NodeContainer(node))

            mobility = ns.mobility.ConstantPositionMobilityModel()
            mobility.SetPosition(
                ns.core.Vector(xi * DISTANCE, yi * DISTANCE, 0))
            node.AggregateObject(mobility)

            devices = wifi.Install(wifiPhy, wifiMac, node)
            ipv4_interfaces = ipv4Addresses.Assign(devices)
            addresses.append(ipv4_interfaces.GetAddress(0))
    for e in range(500):

        for i, node in enumerate(nodes):
            destaddr = addresses[(len(addresses) - 1 - i) % len(addresses)]
            onOffHelper.SetAttribute(
                "Remote",
                ns.network.AddressValue(
                    ns.network.InetSocketAddress(destaddr, port)))
            app = onOffHelper.Install(ns.network.NodeContainer(node))
            urv = ns.core.UniformRandomVariable()
            app.Start(ns.core.Seconds(urv.GetValue(20, 30)))

        flowmon_helper = ns.flow_monitor.FlowMonitorHelper()
        monitor = flowmon_helper.InstallAll()
        monitor = flowmon_helper.GetMonitor()
        monitor.SetAttribute("DelayBinWidth", ns.core.DoubleValue(0.001))
        monitor.SetAttribute("JitterBinWidth", ns.core.DoubleValue(0.001))
        monitor.SetAttribute("PacketSizeBinWidth", ns.core.DoubleValue(20))

        ns.core.Simulator.Stop(ns.core.Seconds(44.0))
        ns.core.Simulator.Run()

        monitor.CheckForLostPackets()
        classifier = flowmon_helper.GetClassifier()
        monitor.SerializeToXmlFile("wififlow.xml", True, True)
        flow_stats_inputs = monitor.GetFlowStats()
        flow_array = [
        ]  # this is original array which store the original inputs to the model
        # this are the inputs to the model which will stored in flow_array
        flow_array.append(flow_stat_inputs.txBytes)
        flow_array.append(flow_stat_inputs.rxBytes)
        flow_array.append(flow_stat_inputs.txPackets)
        flow_array.append(flow_stat_inputs.rxPackets)
        flow_array.append(flow_stat_inputs.lostPackets)
        if st.rxPackets > 0:
            mean_delay = (flow_stat_inputs.delaySum.GetSeconds() /
                          flow_stat_inputs.rxPackets)
            flow_array.append(mean_delay)
        mean_jitter = (flow_stat_inputs.jitterSum.GetSeconds() /
                       (flow_stat_inputs.rxPackets - 1))
        flow_array.append(mean_jitter)
        np.array(
            flow_array
        )  # then convert the flow array to numpy array reason to convert is numpy array will be a matrix and our model will only accept matrix inputs
        # data preprocessing part here we normalized the dataset into range between 1 and 0 and then convert to time sequence dataset since our model is recurrent network it only accept time sequence data
        df = DataFrame(data=d, index=index)
        min_max_scaler = preprocessing.MinMaxScaler()
        np_scaled = min_max_scaler.fit_transform(df)
        df_normalized = pd.DataFrame(np_scaled)
        X_train = sequence.pad_sequences(df_normalized, 10)
        actor = DQNAgent(X_train.shape[1], num_nodes_side)
        for t in range(500):
            action = actor.act(X_train)
            for i, node in enumerate(nodes):
                destaddr = addresses[action]
                onOffHelper.SetAttribute(
                    "Remote",
                    ns.network.AddressValue(
                        ns.network.InetSocketAddress(destaddr, port)))
                app = onOffHelper.Install(ns.network.NodeContainer(node))
                urv = ns.core.UniformRandomVariable()
                app.Start(ns.core.Seconds(urv.GetValue(20, 30)))

            flowmon_helper = ns.flow_monitor.FlowMonitorHelper()
            monitor = flowmon_helper.InstallAll()
            monitor = flowmon_helper.GetMonitor()
            monitor.SetAttribute("DelayBinWidth", ns.core.DoubleValue(0.001))
            monitor.SetAttribute("JitterBinWidth", ns.core.DoubleValue(0.001))
            monitor.SetAttribute("PacketSizeBinWidth", ns.core.DoubleValue(20))

            ns.core.Simulator.Stop(ns.core.Seconds(44.0))
            ns.core.Simulator.Run()

            monitor.CheckForLostPackets()
            classifier = flowmon_helper.GetClassifier()
            monitor.SerializeToXmlFile("wififlow.xml", True, True)
            # similar process describe in ahead happens here inside the loop
            flow_stats_inputs_next = monitor.GetFlowStats()
            flow_array_next = []
            flow_array_next.append(flow_stat_inputs_next.txBytes)
            flow_array_next.append(flow_stat_inputs_next.rxBytes)
            flow_array_next.append(flow_stat_inputs_next.txPackets)
            flow_array_next.append(flow_stat_inputs_next.rxPackets)
            flow_array_next.append(flow_stat_inputs_next.lostPackets)
            if st.rxPackets > 0:
                mean_delay = (flow_stat_inputs_next.delaySum.GetSeconds() /
                              flow_stat_inputs.rxPackets)
                flow_array.append(mean_delay)
            mean_jitter = (flow_stat_inputs_next.jitterSum.GetSeconds() /
                           (flow_stat_inputs.rxPackets - 1))
            flow_array_next.append(mean_jitter)
            np.array(flow_array_next)
            df_next = DataFrame(data=d, index=index)
            min_max_scaler_next = preprocessing.MinMaxScaler()
            np_scaled_next = min_max_scaler_next.fit_transform(df_next)
            df_normalized_next = pd.DataFrame(np_scaled_next)
            X_next = sequence.pad_sequences(df_normalized_next, 10)
            # here we calculate the reward this has to be improve here i calculate the reward based only on loss packets which is not good way another few factors to be added it has to be discussed
            if (flow_stat_inputs_next.lostPackets > 10):
                reward = -10
            else:
                reward = 20
            actor.remember(
                X_train, action, X_next
            )  # finally saved the current step in model memory for experience replay module
            print("episode: {}/{}, score: {}".format(e, 500, t))
        actor.replay(
            32
        )  # after 500 times of training then apply the experiece replay task to use what it learn so far

    import pylab
    delays = []
    for flow_id, flow_stats in monitor.GetFlowStats():
        tupl = classifier.FindFlow(flow_id)
        if tupl.protocol == 17 and tupl.sourcePort == 698:
            continue
        delays.append(flow_stats.delaySum.GetSeconds() / flow_stats.rxPackets)
    pylab.hist(delays, 20)
    pylab.xlabel("Delay (s)")
    pylab.ylabel("Number of Flows")
    pylab.show()
    return 0
Example #18
0
def main():
    framework.start()

    # First, we initialize a few local variables that control some
    #  simulation parameters.
    cmd = ns.core.CommandLine()
    cmd.backboneNodes = {{backbone_nodes}}
    cmd.infraNodes = {{infra_nodes}}
    cmd.lanNodes = {{lan_nodes}}
    cmd.stopTime = {{exec_time}}

    #  Simulation defaults are typically set next, before command line
    #  arguments are parsed.
    ns.core.Config.SetDefault("ns3::OnOffApplication::PacketSize",
                              ns.core.StringValue("1472"))
    ns.core.Config.SetDefault("ns3::OnOffApplication::DataRate",
                              ns.core.StringValue("100kb/s"))

    backboneNodes = int(cmd.backboneNodes)
    infraNodes = int(cmd.infraNodes)
    lanNodes = int(cmd.lanNodes)
    stopTime = int(cmd.stopTime)

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #                                                                        #
    #  Construct the backbone                                                #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #  Create a container to manage the nodes of the adhoc(backbone) network.
    #  Later we'll create the rest of the nodes we'll need.
    backbone = ns.network.NodeContainer()
    backbone.Create(backboneNodes)

    #  Create the backbone wifi net devices and install them into the nodes in
    #  our container
    wifi = ns.wifi.WifiHelper()
    mac = ns.wifi.WifiMacHelper()
    mac.SetType("ns3::AdhocWifiMac")
    wifi.SetRemoteStationManager(
        "ns3::ConstantRateWifiManager", "DataMode",
        ns.core.StringValue("OfdmRate{}Mbps".format({{ofdm_rate}})))
    wifiPhy = ns.wifi.YansWifiPhyHelper.Default()
    wifiChannel = ns.wifi.YansWifiChannelHelper.Default()
    wifiPhy.SetChannel(wifiChannel.Create())
    backboneDevices = wifi.Install(wifiPhy, mac, backbone)

    #  Add the IPv4 protocol stack to the nodes in our container
    print("Enabling OLSR routing on all backbone nodes")
    internet = ns.internet.InternetStackHelper()
    olsr = ns.olsr.OlsrHelper()
    internet.SetRoutingHelper(olsr)
    # has effect on the next Install ()
    internet.Install(backbone)

    #  Assign IPv4 addresses to the device drivers(actually to the associated
    #  IPv4 interfaces) we just created.
    ipAddrs = ns.internet.Ipv4AddressHelper()
    ipAddrs.SetBase(ns.network.Ipv4Address("192.168.0.0"),
                    ns.network.Ipv4Mask("255.255.255.0"))
    ipAddrs.Assign(backboneDevices)

    #  The ad-hoc network nodes need a mobility model so we aggregate one to
    #  each of the nodes we just finished building.
    mobility = ns.mobility.MobilityHelper()
    mobility.SetPositionAllocator("ns3::GridPositionAllocator", "MinX",
                                  ns.core.DoubleValue(20.0), "MinY",
                                  ns.core.DoubleValue(20.0), "DeltaX",
                                  ns.core.DoubleValue(20.0), "DeltaY",
                                  ns.core.DoubleValue(20.0), "GridWidth",
                                  ns.core.UintegerValue(5), "LayoutType",
                                  ns.core.StringValue("RowFirst"))
    mobility.SetMobilityModel(
        "ns3::RandomDirection2dMobilityModel", "Bounds",
        ns.mobility.RectangleValue(ns.mobility.Rectangle(-500, 500, -500,
                                                         500)), "Speed",
        ns.core.StringValue("ns3::ConstantRandomVariable[Constant=2]"),
        "Pause",
        ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0.2]"))
    mobility.Install(backbone)

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #                                                                        #
    #  Construct the LANs                                                    #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #  Reset the address base-- all of the CSMA networks will be in
    #  the "172.16 address space
    ipAddrs.SetBase(ns.network.Ipv4Address("172.16.0.0"),
                    ns.network.Ipv4Mask("255.255.255.0"))

    for i in range(backboneNodes):
        #  Create a container to manage the nodes of the LAN.  We need
        #  two containers here; one with all of the new nodes, and one
        #  with all of the nodes including new and existing nodes
        newLanNodes = ns.network.NodeContainer()
        newLanNodes.Create(lanNodes - 1)
        lan = ns.network.NodeContainer(
            ns.network.NodeContainer(backbone.Get(i)), newLanNodes)

        #  Create the CSMA net devices and install them into the nodes in our
        #  collection.
        csma = ns.csma.CsmaHelper()
        csma.SetChannelAttribute(
            "DataRate",
            ns.network.DataRateValue(ns.network.DataRate({{datarate}})))
        csma.SetChannelAttribute(
            "Delay", ns.core.TimeValue(ns.core.MilliSeconds({{delay}})))
        lanDevices = csma.Install(lan)

        #  Add the IPv4 protocol stack to the new LAN nodes
        internet.Install(newLanNodes)

        #  Assign IPv4 addresses to the device drivers(actually to the
        #  associated IPv4 interfaces) we just created.
        ipAddrs.Assign(lanDevices)

        #  Assign a new network prefix for the next LAN, according to the
        #  network mask initialized above
        ipAddrs.NewNetwork()

        # The new LAN nodes need a mobility model so we aggregate one
        # to each of the nodes we just finished building.
        mobilityLan = ns.mobility.MobilityHelper()
        positionAlloc = ns.mobility.ListPositionAllocator()
        for j in range(newLanNodes.GetN()):
            positionAlloc.Add(ns.core.Vector(0.0, (j * 10 + 10), 0.0))

        mobilityLan.SetPositionAllocator(positionAlloc)
        mobilityLan.PushReferenceMobilityModel(backbone.Get(i))
        mobilityLan.SetMobilityModel("ns3::ConstantPositionMobilityModel")
        mobilityLan.Install(newLanNodes)

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #                                                                        #
    #  Construct the mobile networks                                         #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #  Reset the address base-- all of the 802.11 networks will be in
    #  the "10.0" address space
    ipAddrs.SetBase(ns.network.Ipv4Address("10.0.0.0"),
                    ns.network.Ipv4Mask("255.255.255.0"))

    for i in range(backboneNodes):
        #  Create a container to manage the nodes of the LAN.  We need
        #  two containers here; one with all of the new nodes, and one
        #  with all of the nodes including new and existing nodes
        stas = ns.network.NodeContainer()
        stas.Create(infraNodes - 1)
        infra = ns.network.NodeContainer(
            ns.network.NodeContainer(backbone.Get(i)), stas)

        #  Create another ad hoc network and devices
        ssid = ns.wifi.Ssid('wifi-infra' + str(i))
        wifiInfra = ns.wifi.WifiHelper()
        wifiPhy.SetChannel(wifiChannel.Create())
        wifiInfra.SetRemoteStationManager('ns3::ArfWifiManager')
        macInfra = ns.wifi.WifiMacHelper()
        macInfra.SetType("ns3::StaWifiMac", "Ssid", ns.wifi.SsidValue(ssid))

        # setup stas
        staDevices = wifiInfra.Install(wifiPhy, macInfra, stas)
        # setup ap.
        macInfra.SetType("ns3::ApWifiMac", "Ssid", ns.wifi.SsidValue(ssid),
                         "BeaconInterval",
                         ns.core.TimeValue(ns.core.Seconds(2.5)))
        apDevices = wifiInfra.Install(wifiPhy, macInfra, backbone.Get(i))
        # Collect all of these new devices
        infraDevices = ns.network.NetDeviceContainer(apDevices, staDevices)

        #  Add the IPv4 protocol stack to the nodes in our container
        internet.Install(stas)

        #  Assign IPv4 addresses to the device drivers(actually to the associated
        #  IPv4 interfaces) we just created.
        ipAddrs.Assign(infraDevices)

        #  Assign a new network prefix for each mobile network, according to
        #  the network mask initialized above
        ipAddrs.NewNetwork()

        #  The new wireless nodes need a mobility model so we aggregate one
        #  to each of the nodes we just finished building.
        subnetAlloc = ns.mobility.ListPositionAllocator()
        for j in range(infra.GetN()):
            subnetAlloc.Add(ns.core.Vector(0.0, j, 0.0))

        mobility.PushReferenceMobilityModel(backbone.Get(i))
        mobility.SetPositionAllocator(subnetAlloc)
        mobility.SetMobilityModel(
            "ns3::RandomDirection2dMobilityModel", "Bounds",
            ns.mobility.RectangleValue(ns.mobility.Rectangle(-10, 10, -10,
                                                             10)), "Speed",
            ns.core.StringValue("ns3::ConstantRandomVariable[Constant=3]"),
            "Pause",
            ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0.4]"))
        mobility.Install(stas)

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #                                                                        #
    #  Application configuration                                             #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #  Create the OnOff application to send UDP datagrams of size
    #  210 bytes at a rate of 448 Kb/s, between two nodes
    port = 9  #  Discard port(RFC 863)

    appSource = ns.network.NodeList.GetNode(backboneNodes)
    lastNodeIndex = backboneNodes + backboneNodes * (
        lanNodes - 1) + backboneNodes * (infraNodes - 1) - 1
    appSink = ns.network.NodeList.GetNode(lastNodeIndex)
    # Let's fetch the IP address of the last node, which is on Ipv4Interface 1
    remoteAddr = appSink.GetObject(ns.internet.Ipv4.GetTypeId()).GetAddress(
        1, 0).GetLocal()

    onoff = ns.applications.OnOffHelper(
        "ns3::UdpSocketFactory",
        ns.network.Address(ns.network.InetSocketAddress(remoteAddr, port)))
    apps = onoff.Install(ns.network.NodeContainer(appSource))
    apps.Start(ns.core.Seconds(3))
    apps.Stop(ns.core.Seconds(stopTime - 1))

    #  Create a packet sink to receive these packets
    sink = ns.applications.PacketSinkHelper(
        "ns3::UdpSocketFactory",
        ns.network.InetSocketAddress(ns.network.Ipv4Address.GetAny(), port))
    apps = sink.Install(ns.network.NodeContainer(appSink))
    apps.Start(ns.core.Seconds(3))

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #                                                                        #
    #  Tracing configuration                                                 #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    csma = ns.csma.CsmaHelper()

    #  Let's set up some ns-2-like ascii traces, using another helper class
    #
    ascii = ns.network.AsciiTraceHelper()
    stream = ascii.CreateFileStream("mixed-wireless.tr")
    wifiPhy.EnableAsciiAll(stream)
    csma.EnableAsciiAll(stream)
    internet.EnableAsciiIpv4All(stream)

    mob = ascii.CreateFileStream("mixed-wireless.mob")
    mobility.EnableAsciiAll(mob)

    #  Csma captures in non-promiscuous mode
    csma.EnablePcapAll("mixed-wireless", False)
    #  Let's do a pcap trace on the backbone devices
    wifiPhy.EnablePcap("mixed-wireless", backboneDevices)
    wifiPhy.EnablePcap("mixed-wireless", appSink.GetId(), 0)

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    #                                                                        #
    #  Run simulation                                                        #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    ns.core.Simulator.Stop(ns.core.Seconds(stopTime))
    ns.core.Simulator.Run()
    ns.core.Simulator.Destroy()

    framework.addBinaryFile("mixed-wireless.tr")
    framework.addBinaryFile("mixed-wireless.mob")

    path = "*.pcap"
    for filename in glob.glob(path):
        framework.addBinaryFile(filename)

    framework.stop()
n1n2.Add(c.Get(1))
n1n2.Add(c.Get(2))
n5n6 = ns.network.NodeContainer()
n5n6.Add(c.Get(5))
n5n6.Add(c.Get(6))
n1n6 = ns.network.NodeContainer()
n1n6.Add(c.Get(1))
n1n6.Add(c.Get(6))
n2345 = ns.network.NodeContainer()
n2345.Add(c.Get(2))
n2345.Add(c.Get(3))
n2345.Add(c.Get(4))
n2345.Add(c.Get(5))

internet = ns.internet.InternetStackHelper()
internet.Install(c)

#We create the channels first without any IP addressing information
print("Create channels.")
p2p = ns.point_to_point.PointToPointHelper()
p2p.SetDeviceAttribute("DataRate", ns.core.StringValue("5Mbps"))
p2p.SetChannelAttribute("Delay", ns.core.StringValue("2ms"))
d0d2 = p2p.Install(n0n2)
d1d6 = p2p.Install(n1n6)

d1d2 = p2p.Install(n1n2)

p2p.SetDeviceAttribute("DataRate", ns.core.StringValue("1500kbps"))
p2p.SetChannelAttribute("Delay", ns.core.StringValue("10ms"))
d5d6 = p2p.Install(n5n6)
Example #20
0
def main(argv):
    #
    # Allow the user to override any of the defaults and the above Bind() at
    # run-time, via command-line arguments
    #
    cmd = ns.core.CommandLine()

    cmd.packetSize = 1024
    cmd.packetCount = 10
    cmd.packetInterval = 1.0

    #Socket options for IPv6, currently TCLASS, HOPLIMIT, RECVTCLASS, and RECVHOPLIMIT
    cmd.ipv6Tclass = 0
    cmd.ipv6RecvTclass = True
    cmd.ipv6Hoplimit = 0
    cmd.ipv6RecvHoplimit = True

    cmd.AddValue("PacketSize", "Packet size in bytes")
    cmd.AddValue("PacketCount", "Number of packets to send")
    cmd.AddValue("Interval", "Interval between packets")
    cmd.AddValue("IPV6_TCLASS", "IPV6_TCLASS")
    cmd.AddValue("IPV6_RECVTCLASS", "IPV6_RECVTCLASS")
    cmd.AddValue("IPV6_HOPLIMIT", "IPV6_HOPLIMIT")
    cmd.AddValue("IPV6_RECVHOPLIMIT", "IPV6_RECVHOPLIMIT")
    cmd.Parse(argv)

    packetSize = int(cmd.packetSize)
    packetCount = int(cmd.packetCount)
    packetInterval = float(cmd.packetInterval)
    ipv6Tclass = int(cmd.ipv6Tclass)
    ipv6RecvTclass = bool(cmd.ipv6RecvTclass)
    ipv6Hoplimit = int(cmd.ipv6Hoplimit)
    ipv6RecvHoplimit = bool(cmd.ipv6RecvHoplimit)

    print("Create nodes.")
    n = ns.network.NodeContainer()
    n.Create(2)

    internet = ns.internet.InternetStackHelper()
    internet.Install(n)

    print("Create channels.")
    csma = ns.csma.CsmaHelper()
    csma.SetChannelAttribute("DataRate", ns.core.StringValue("5000000"))
    csma.SetChannelAttribute("Delay",
                             ns.core.TimeValue(ns.core.MilliSeconds(2)))
    csma.SetDeviceAttribute("Mtu", ns.core.UintegerValue(1400))
    d = csma.Install(n)

    print("Assign IP Addresses.")
    ipv6 = ns.internet.Ipv6AddressHelper()
    ipv6.SetBase(ns.network.Ipv6Address("2001:0000:f00d:cafe::"),
                 ns.network.Ipv6Prefix(64))
    i6 = ipv6.Assign(d)
    serverAddress = ns.network.Address(i6.GetAddress(1, 1))

    print("Create sockets.")
    #Receiver socket on n1
    tid = ns3.TypeId.LookupByName("ns3::UdpSocketFactory")
    recvSink = ns3.Socket.CreateSocket(n.Get(1), tid)
    local = ns3.Inet6SocketAddress(ns3.Ipv6Address.GetAny(), 4477)
    recvSink.SetIpv6RecvTclass(ipv6RecvTclass)
    recvSink.SetIpv6RecvHopLimit(ipv6RecvHoplimit)
    recvSink.Bind(local)
    recvSink.SetRecvCallback(ReceivePacket)

    #Sender socket on n0
    source = ns3.Socket.CreateSocket(n.Get(0), tid)
    remote = ns3.Inet6SocketAddress(i6.GetAddress(1, 1), 4477)

    #Set socket options, it is also possible to set the options after the socket has been created/connected.
    if ipv6Tclass != 0:
        source.SetIpv6Tclass(ipv6Tclass)

    if ipv6Hoplimit > 0:
        source.SetIpv6HopLimit(ipv6Hoplimit)

    source.Connect(remote)

    ascii = ns.network.AsciiTraceHelper()
    csma.EnableAsciiAll(ascii.CreateFileStream("socket-options-ipv6-py.tr"))
    csma.EnablePcapAll("socket-options-ipv6", False)

    #Schedule SendPacket
    interPacketInterval = ns.core.Seconds(packetInterval)
    ns.core.Simulator.ScheduleWithContext(source.GetNode().GetId(),
                                          ns.core.Seconds(1.0), SendPacket,
                                          source, packetSize, packetCount,
                                          interPacketInterval)

    print("Run Simulation.")
    ns.core.Simulator.Run()
    ns.core.Simulator.Destroy()
    print("Done.")
Example #21
0
def main(argv):
    #
    #  First, we declare and initialize a few local variables that control some
    #  simulation parameters.
    #
    backboneNodes = 10
    infraNodes = 5
    lanNodes = 5
    stopTime = 10

    #
    #  Simulation defaults are typically set next, before command line
    #  arguments are parsed.
    #
    ns.core.Config.SetDefault("ns3::OnOffApplication::PacketSize",
                              ns.core.StringValue("210"))
    ns.core.Config.SetDefault("ns3::OnOffApplication::DataRate",
                              ns.core.StringValue("448kb/s"))

    #
    #  For convenience, we add the local variables to the command line argument
    #  system so that they can be overridden with flags such as
    #  "--backboneNodes=20"
    #
    cmd = ns.core.CommandLine()
    #cmd.AddValue("backboneNodes", "number of backbone nodes", backboneNodes)
    #cmd.AddValue("infraNodes", "number of leaf nodes", infraNodes)
    #cmd.AddValue("lanNodes", "number of LAN nodes", lanNodes)
    #cmd.AddValue("stopTime", "simulation stop time(seconds)", stopTime)

    #
    #  The system global variables and the local values added to the argument
    #  system can be overridden by command line arguments by using this call.
    #
    cmd.Parse(argv)

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #                                                                        #
    #  Construct the backbone                                                #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /

    #
    #  Create a container to manage the nodes of the adhoc(backbone) network.
    #  Later we'll create the rest of the nodes we'll need.
    #
    backbone = ns.network.NodeContainer()
    backbone.Create(backboneNodes)
    #
    #  Create the backbone wifi net devices and install them into the nodes in
    #  our container
    #
    wifi = ns.wifi.WifiHelper()
    mac = ns.wifi.NqosWifiMacHelper.Default()
    mac.SetType("ns3::AdhocWifiMac")
    wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager", "DataMode",
                                 ns.core.StringValue("OfdmRate54Mbps"))
    wifiPhy = ns.wifi.YansWifiPhyHelper.Default()
    wifiChannel = ns.wifi.YansWifiChannelHelper.Default()
    wifiPhy.SetChannel(wifiChannel.Create())
    backboneDevices = wifi.Install(wifiPhy, mac, backbone)
    #
    #  Add the IPv4 protocol stack to the nodes in our container
    #
    print "Enabling OLSR routing on all backbone nodes"
    internet = ns.internet.InternetStackHelper()
    olsr = ns.olsr.OlsrHelper()
    internet.SetRoutingHelper(olsr)
    # has effect on the next Install ()
    internet.Install(backbone)
    # re-initialize for non-olsr routing.
    internet.Reset()
    #
    #  Assign IPv4 addresses to the device drivers(actually to the associated
    #  IPv4 interfaces) we just created.
    #
    ipAddrs = ns.internet.Ipv4AddressHelper()
    ipAddrs.SetBase(ns.network.Ipv4Address("192.168.0.0"),
                    ns.network.Ipv4Mask("255.255.255.0"))
    ipAddrs.Assign(backboneDevices)

    #
    #  The ad-hoc network nodes need a mobility model so we aggregate one to
    #  each of the nodes we just finished building.
    #
    mobility = ns.mobility.MobilityHelper()
    positionAlloc = ns.mobility.ListPositionAllocator()
    x = 0.0
    for i in range(backboneNodes):
        positionAlloc.Add(ns.core.Vector(x, 0.0, 0.0))
        x += 5.0
    mobility.SetPositionAllocator(positionAlloc)
    mobility.SetMobilityModel(
        "ns3::RandomDirection2dMobilityModel", "Bounds",
        ns.mobility.RectangleValue(ns.mobility.Rectangle(0, 1000, 0,
                                                         1000)), "Speed",
        ns.core.RandomVariableValue(ns.core.ConstantVariable(2000)), "Pause",
        ns.core.RandomVariableValue(ns.core.ConstantVariable(0.2)))
    mobility.Install(backbone)

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #                                                                        #
    #  Construct the LANs                                                    #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /

    #  Reset the address base-- all of the CSMA networks will be in
    #  the "172.16 address space
    ipAddrs.SetBase(ns.network.Ipv4Address("172.16.0.0"),
                    ns.network.Ipv4Mask("255.255.255.0"))

    for i in range(backboneNodes):
        print "Configuring local area network for backbone node ", i
        #
        #  Create a container to manage the nodes of the LAN.  We need
        #  two containers here; one with all of the new nodes, and one
        #  with all of the nodes including new and existing nodes
        #
        newLanNodes = ns.network.NodeContainer()
        newLanNodes.Create(lanNodes - 1)
        #  Now, create the container with all nodes on this link
        lan = ns.network.NodeContainer(
            ns.network.NodeContainer(backbone.Get(i)), newLanNodes)
        #
        #  Create the CSMA net devices and install them into the nodes in our
        #  collection.
        #
        csma = ns.csma.CsmaHelper()
        csma.SetChannelAttribute(
            "DataRate", ns.network.DataRateValue(ns.network.DataRate(5000000)))
        csma.SetChannelAttribute("Delay",
                                 ns.core.TimeValue(ns.core.MilliSeconds(2)))
        lanDevices = csma.Install(lan)
        #
        #  Add the IPv4 protocol stack to the new LAN nodes
        #
        internet.Install(newLanNodes)
        #
        #  Assign IPv4 addresses to the device drivers(actually to the
        #  associated IPv4 interfaces) we just created.
        #
        ipAddrs.Assign(lanDevices)
        #
        #  Assign a new network prefix for the next LAN, according to the
        #  network mask initialized above
        #
        ipAddrs.NewNetwork()

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #                                                                        #
    #  Construct the mobile networks                                         #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /

    #  Reset the address base-- all of the 802.11 networks will be in
    #  the "10.0" address space
    ipAddrs.SetBase(ns.network.Ipv4Address("10.0.0.0"),
                    ns.network.Ipv4Mask("255.255.255.0"))

    for i in range(backboneNodes):
        print "Configuring wireless network for backbone node ", i
        #
        #  Create a container to manage the nodes of the LAN.  We need
        #  two containers here; one with all of the new nodes, and one
        #  with all of the nodes including new and existing nodes
        #
        stas = ns.network.NodeContainer()
        stas.Create(infraNodes - 1)
        #  Now, create the container with all nodes on this link
        infra = ns.network.NodeContainer(
            ns.network.NodeContainer(backbone.Get(i)), stas)
        #
        #  Create another ad hoc network and devices
        #
        ssid = ns.wifi.Ssid('wifi-infra' + str(i))
        wifiInfra = ns.wifi.WifiHelper.Default()
        wifiPhy.SetChannel(wifiChannel.Create())
        wifiInfra.SetRemoteStationManager('ns3::ArfWifiManager')
        macInfra = ns.wifi.NqosWifiMacHelper.Default()
        macInfra.SetType("ns3::StaWifiMac", "Ssid", ns.wifi.SsidValue(ssid),
                         "ActiveProbing", ns.core.BooleanValue(False))

        # setup stas
        staDevices = wifiInfra.Install(wifiPhy, macInfra, stas)
        # setup ap.
        macInfra.SetType("ns3::ApWifiMac", "Ssid",
                         ns.wifi.SsidValue(ssid), "BeaconGeneration",
                         ns.core.BooleanValue(True), "BeaconInterval",
                         ns.core.TimeValue(ns.core.Seconds(2.5)))
        apDevices = wifiInfra.Install(wifiPhy, macInfra, backbone.Get(i))
        # Collect all of these new devices
        infraDevices = ns.network.NetDeviceContainer(apDevices, staDevices)

        #  Add the IPv4 protocol stack to the nodes in our container
        #
        internet.Install(stas)
        #
        #  Assign IPv4 addresses to the device drivers(actually to the associated
        #  IPv4 interfaces) we just created.
        #
        ipAddrs.Assign(infraDevices)
        #
        #  Assign a new network prefix for each mobile network, according to
        #  the network mask initialized above
        #
        ipAddrs.NewNetwork()
        #
        #  The new wireless nodes need a mobility model so we aggregate one
        #  to each of the nodes we just finished building.
        #
        subnetAlloc = ns.mobility.ListPositionAllocator()
        for j in range(infra.GetN()):
            subnetAlloc.Add(ns.core.Vector(0.0, j, 0.0))

        mobility.PushReferenceMobilityModel(backbone.Get(i))
        mobility.SetPositionAllocator(subnetAlloc)
        mobility.SetMobilityModel(
            "ns3::RandomDirection2dMobilityModel", "Bounds",
            ns.mobility.RectangleValue(ns.mobility.Rectangle(-25, 25, -25,
                                                             25)), "Speed",
            ns.core.RandomVariableValue(ns.core.ConstantVariable(30)), "Pause",
            ns.core.RandomVariableValue(ns.core.ConstantVariable(0.4)))
        mobility.Install(infra)

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #                                                                        #
    #  Application configuration                                             #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /

    #  Create the OnOff application to send UDP datagrams of size
    #  210 bytes at a rate of 448 Kb/s, between two nodes
    print "Create Applications."
    port = 9  #  Discard port(RFC 863)

    #  Let's make sure that the user does not define too few LAN nodes
    #  to make this example work.  We need lanNodes >= 5
    assert (lanNodes >= 5)
    appSource = ns.network.NodeList.GetNode(11)
    appSink = ns.network.NodeList.GetNode(13)
    remoteAddr = ns.network.Ipv4Address("172.16.0.5")

    onoff = ns.applications.OnOffHelper(
        "ns3::UdpSocketFactory",
        ns.network.Address(ns.network.InetSocketAddress(remoteAddr, port)))
    onoff.SetAttribute(
        "OnTime", ns.core.RandomVariableValue(ns.core.ConstantVariable(1)))
    onoff.SetAttribute(
        "OffTime", ns.core.RandomVariableValue(ns.core.ConstantVariable(0)))
    apps = onoff.Install(ns.network.NodeContainer(appSource))
    apps.Start(ns.core.Seconds(3.0))
    apps.Stop(ns.core.Seconds(20.0))

    #  Create a packet sink to receive these packets
    sink = ns.applications.PacketSinkHelper(
        "ns3::UdpSocketFactory",
        ns.network.InetSocketAddress(ns.network.Ipv4Address.GetAny(), port))
    apps = sink.Install(ns.network.NodeContainer(appSink))
    apps.Start(ns.core.Seconds(3.0))

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #                                                                        #
    #  Tracing configuration                                                 #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /

    print "Configure Tracing."
    #
    #  Let's set up some ns-2-like ascii traces, using another helper class
    #
    #std.ofstream ascii
    #ascii = ns.core.AsciiTraceHelper();
    #stream = ascii.CreateFileStream("mixed-wireless.tr");
    #wifiPhy.EnableAsciiAll(stream);
    #csma.EnableAsciiAll(stream);
    print "(tracing not done for Python)"
    #  Look at nodes 11, 13 only
    # WifiHelper.EnableAscii(ascii, 11, 0);
    # WifiHelper.EnableAscii(ascii, 13, 0);

    #  Let's do a pcap trace on the backbone devices
    wifiPhy.EnablePcap("mixed-wireless", backboneDevices)
    #  Let's additionally trace the application Sink, ifIndex 0
    csma = ns.csma.CsmaHelper()
    csma.EnablePcapAll("mixed-wireless", False)

    #   #ifdef ENABLE_FOR_TRACING_EXAMPLE
    #     Config.Connect("/NodeList/*/$MobilityModel/CourseChange",
    #       MakeCallback(&CourseChangeCallback))
    #   #endif

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    #                                                                        #
    #  Run simulation                                                        #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

    print "Run Simulation."
    ns.core.Simulator.Stop(ns.core.Seconds(stopTime))
    ns.core.Simulator.Run()
    ns.core.Simulator.Destroy()
def main (argv):
		# 
		# Users may find it convenient to turn on explicit debugging
		# for selected modules; the below lines suggest how to do this
		
		# Set up some default values for the simulation.  Use the
		ns.core.Config.SetDefault("ns3::OnOffApplication::PacketSize", ns.core.UintegerValue (210))
		ns.core.Config.SetDefault("ns3::OnOffApplication::DataRate", ns.core.StringValue ("448kb/s"))

		#
		# DefaultValue::Bind ("DropTailQueue::m_maxPackets", 30);

		# Allow the user to override any of the defaults and the above
		# DefaultValue::Bind ()s at run-time, via command-line arguments
		#
		cmd = ns.core.CommandLine ()
		cmd.enableFlowMonitor = False
		cmd.AddValue ("EnableMonitor", "Enable Flow Monitor")
		cmd.Parse (argv)
		enableFlowMonitor = bool(cmd.enableFlowMonitor)

		#Here, we will explicitly create four nodes.  In more sophisticated
		# topologies, we could configure a node factory.

		print ("Create nodes.")
		c = ns.network.NodeContainer ()
		c.Create (4)
		n0n2 = ns.network.NodeContainer ()
		n0n2.Add(c.Get(0))
		n0n2.Add(c.Get(2))
		n1n2 = ns.network.NodeContainer ()
		n1n2.Add(c.Get(1))
		n1n2.Add(c.Get(2))
		n3n2 = ns.network.NodeContainer ()
		n3n2.Add(c.Get(3))
		n3n2.Add(c.Get(2))

		internet = ns.internet.InternetStackHelper ()
		internet.Install (c)

		#
		# We create the channels first without any IP addressing information
		#
		print ("Create channels.")
		p2p =ns.point_to_point.PointToPointHelper ()
		p2p.SetDeviceAttribute ("DataRate", ns.core.StringValue ("5Mbps"))
		p2p.SetChannelAttribute ("Delay", ns.core.StringValue ("2ms"))
		d0d2 = p2p.Install (n0n2)
		d1d2 = p2p.Install (n1n2)
		p2p.SetDeviceAttribute ("DataRate", ns.core.StringValue ("1500kbps"))
		p2p.SetChannelAttribute ("Delay", ns.core.StringValue ("10ms"))
		d3d2 = p2p.Install (n3n2)

		#
		# Later, we add IP addresses.
		#
		print ("Assign IP Addresses.")
		ipv4 = ns.internet.Ipv4AddressHelper ()
		ipv4.SetBase (ns.network.Ipv4Address ("10.1.1.0"), ns.network.Ipv4Mask ("255.255.255.0"))
		i0i2 = ipv4.Assign (d0d2)
		ipv4.SetBase (ns.network.Ipv4Address ("10.1.2.0"), ns.network.Ipv4Mask ("255.255.255.0"))
		i1i2 = ipv4.Assign (d1d2)
		ipv4.SetBase (ns.network.Ipv4Address ("10.1.3.0"), ns.network.Ipv4Mask ("255.255.255.0"))
		i3i2 = ipv4.Assign (d3d2)
		
		#
		# Create router nodes, initialize routing database and set up the routing
		# tables in the nodes.
		#
		ns.internet.Ipv4GlobalRoutingHelper.PopulateRoutingTables()

		#
		# Create the OnOff application to send UDP datagrams of size
		# 210 bytes at a rate of 448 Kb/s
		#
		print ("Create Applications.")
		port = 9  # Discard port (RFC 863)

		onoff = ns.applications.OnOffHelper ("ns3::UdpSocketFactory",
											ns.network.InetSocketAddress (i3i2.GetAddress (0), port))
		onoff.SetConstantRate (ns.network.DataRate("448kb/s"))
		apps = onoff.Install (c.Get (0))
		apps.Start (ns.core.Seconds (1.0))
		apps.Stop (ns.core.Seconds (10.0))
		# 
		# Create a packet sink to receive these packets
		# 
		sink = ns.applications.PacketSinkHelper ("ns3::UdpSocketFactory",
												ns.network.InetSocketAddress (ns.network.Ipv4Address.GetAny (), port))
		apps = sink.Install (c.Get (3))
		apps.Start (ns.core.Seconds (1.0))
		apps.Stop (ns.core.Seconds (10.0))

		#
		# Create a similar flow from n3 to n1, starting at time 1.1 seconds
		#  
		onoff.SetAttribute ("Remote",
							ns.network.AddressValue(ns.network.InetSocketAddress (i1i2.GetAddress (0), port)))
		apps = onoff.Install (c.Get (3))
		apps.Start (ns.core.Seconds (1.1))
		apps.Stop (ns.core.Seconds (10.0))

		#
		# Create a packet sink to receive these packets
		#
		apps = sink.Install (c.Get (1))
		apps.Start(ns.core.Seconds (1.1))
		apps.Stop (ns.core.Seconds (10.0))

		ascii = ns.network.AsciiTraceHelper ()
		p2p.EnableAsciiAll (ascii.CreateFileStream ("simple-global-routing.tr"))
		p2p.EnablePcapAll ("simple-global-routing")

		#
		#Flow Monitor
		#
		flowmonHelper = ns.flow_monitor.FlowMonitorHelper ()
		if enableFlowMonitor:
				flowmonHelper.InstallAll()

		print ("Run Simulation.")
		ns.core.Simulator.Stop (ns.core.Seconds (11))
		ns.core.Simulator.Run ()
		print ("Done.")


		if enableFlowMonitor :
			flowmonHelper.SerializeToXmlFile ("simple-global-routing.flowmon", False, False)
		
		ns.core.Simulator.Destroy ()
Example #23
0
def main(argv):
    #
    #  First, we initialize a few local variables that control some
    #  simulation parameters.
    #

    cmd = ns.core.CommandLine()
    cmd.backboneNodes = 10
    cmd.infraNodes = 2
    cmd.lanNodes = 2
    cmd.stopTime = 20

    #
    #  Simulation defaults are typically set next, before command line
    #  arguments are parsed.
    #
    ns.core.Config.SetDefault("ns3::OnOffApplication::PacketSize",
                              ns.core.StringValue("1472"))
    ns.core.Config.SetDefault("ns3::OnOffApplication::DataRate",
                              ns.core.StringValue("100kb/s"))

    #
    #  For convenience, we add the local variables to the command line argument
    #  system so that they can be overridden with flags such as
    #  "--backboneNodes=20"
    #

    cmd.AddValue("backboneNodes", "number of backbone nodes")
    cmd.AddValue("infraNodes", "number of leaf nodes")
    cmd.AddValue("lanNodes", "number of LAN nodes")
    cmd.AddValue("stopTime", "simulation stop time(seconds)")

    #
    #  The system global variables and the local values added to the argument
    #  system can be overridden by command line arguments by using this call.
    #
    cmd.Parse(argv)

    backboneNodes = int(cmd.backboneNodes)
    infraNodes = int(cmd.infraNodes)
    lanNodes = int(cmd.lanNodes)
    stopTime = int(cmd.stopTime)

    if (stopTime < 10):
        print("Use a simulation stop time >= 10 seconds")
        exit(1)
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #                                                                        #
    #  Construct the backbone                                                #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /

    #
    #  Create a container to manage the nodes of the adhoc(backbone) network.
    #  Later we'll create the rest of the nodes we'll need.
    #
    backbone = ns.network.NodeContainer()
    backbone.Create(backboneNodes)
    #
    #  Create the backbone wifi net devices and install them into the nodes in
    #  our container
    #
    wifi = ns.wifi.WifiHelper()
    mac = ns.wifi.WifiMacHelper()
    mac.SetType("ns3::AdhocWifiMac")
    wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager", "DataMode",
                                 ns.core.StringValue("OfdmRate54Mbps"))
    wifiPhy = ns.wifi.YansWifiPhyHelper.Default()
    wifiChannel = ns.wifi.YansWifiChannelHelper.Default()
    wifiPhy.SetChannel(wifiChannel.Create())
    backboneDevices = wifi.Install(wifiPhy, mac, backbone)
    #
    #  Add the IPv4 protocol stack to the nodes in our container
    #
    print("Enabling OLSR routing on all backbone nodes")
    internet = ns.internet.InternetStackHelper()
    olsr = ns.olsr.OlsrHelper()
    internet.SetRoutingHelper(olsr)
    # has effect on the next Install ()
    internet.Install(backbone)
    # re-initialize for non-olsr routing.
    # internet.Reset()
    #
    #  Assign IPv4 addresses to the device drivers(actually to the associated
    #  IPv4 interfaces) we just created.
    #
    ipAddrs = ns.internet.Ipv4AddressHelper()
    ipAddrs.SetBase(ns.network.Ipv4Address("192.168.0.0"),
                    ns.network.Ipv4Mask("255.255.255.0"))
    ipAddrs.Assign(backboneDevices)

    #
    #  The ad-hoc network nodes need a mobility model so we aggregate one to
    #  each of the nodes we just finished building.
    #
    mobility = ns.mobility.MobilityHelper()
    mobility.SetPositionAllocator("ns3::GridPositionAllocator", "MinX",
                                  ns.core.DoubleValue(20.0), "MinY",
                                  ns.core.DoubleValue(20.0), "DeltaX",
                                  ns.core.DoubleValue(20.0), "DeltaY",
                                  ns.core.DoubleValue(20.0), "GridWidth",
                                  ns.core.UintegerValue(5), "LayoutType",
                                  ns.core.StringValue("RowFirst"))
    mobility.SetMobilityModel(
        "ns3::RandomDirection2dMobilityModel", "Bounds",
        ns.mobility.RectangleValue(ns.mobility.Rectangle(-500, 500, -500,
                                                         500)), "Speed",
        ns.core.StringValue("ns3::ConstantRandomVariable[Constant=2]"),
        "Pause",
        ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0.2]"))
    mobility.Install(backbone)

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #                                                                        #
    #  Construct the LANs                                                    #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /

    #  Reset the address base-- all of the CSMA networks will be in
    #  the "172.16 address space
    ipAddrs.SetBase(ns.network.Ipv4Address("172.16.0.0"),
                    ns.network.Ipv4Mask("255.255.255.0"))

    for i in range(backboneNodes):
        print("Configuring local area network for backbone node ", i)
        #
        #  Create a container to manage the nodes of the LAN.  We need
        #  two containers here; one with all of the new nodes, and one
        #  with all of the nodes including new and existing nodes
        #
        newLanNodes = ns.network.NodeContainer()
        newLanNodes.Create(lanNodes - 1)
        #  Now, create the container with all nodes on this link
        lan = ns.network.NodeContainer(
            ns.network.NodeContainer(backbone.Get(i)), newLanNodes)
        #
        #  Create the CSMA net devices and install them into the nodes in our
        #  collection.
        #
        csma = ns.csma.CsmaHelper()
        csma.SetChannelAttribute(
            "DataRate", ns.network.DataRateValue(ns.network.DataRate(5000000)))
        csma.SetChannelAttribute("Delay",
                                 ns.core.TimeValue(ns.core.MilliSeconds(2)))
        lanDevices = csma.Install(lan)
        #
        #  Add the IPv4 protocol stack to the new LAN nodes
        #
        internet.Install(newLanNodes)
        #
        #  Assign IPv4 addresses to the device drivers(actually to the
        #  associated IPv4 interfaces) we just created.
        #
        ipAddrs.Assign(lanDevices)
        #
        #  Assign a new network prefix for the next LAN, according to the
        #  network mask initialized above
        #
        ipAddrs.NewNetwork()
        #
        # The new LAN nodes need a mobility model so we aggregate one
        # to each of the nodes we just finished building.
        #
        mobilityLan = ns.mobility.MobilityHelper()
        positionAlloc = ns.mobility.ListPositionAllocator()
        for j in range(newLanNodes.GetN()):
            positionAlloc.Add(ns.core.Vector(0.0, (j * 10 + 10), 0.0))

        mobilityLan.SetPositionAllocator(positionAlloc)
        mobilityLan.PushReferenceMobilityModel(backbone.Get(i))
        mobilityLan.SetMobilityModel("ns3::ConstantPositionMobilityModel")
        mobilityLan.Install(newLanNodes)

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #                                                                        #
    #  Construct the mobile networks                                         #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /

    #  Reset the address base-- all of the 802.11 networks will be in
    #  the "10.0" address space
    ipAddrs.SetBase(ns.network.Ipv4Address("10.0.0.0"),
                    ns.network.Ipv4Mask("255.255.255.0"))

    for i in range(backboneNodes):
        print("Configuring wireless network for backbone node ", i)
        #
        #  Create a container to manage the nodes of the LAN.  We need
        #  two containers here; one with all of the new nodes, and one
        #  with all of the nodes including new and existing nodes
        #
        stas = ns.network.NodeContainer()
        stas.Create(infraNodes - 1)
        #  Now, create the container with all nodes on this link
        infra = ns.network.NodeContainer(
            ns.network.NodeContainer(backbone.Get(i)), stas)
        #
        #  Create another ad hoc network and devices
        #
        ssid = ns.wifi.Ssid('wifi-infra' + str(i))
        wifiInfra = ns.wifi.WifiHelper()
        wifiPhy.SetChannel(wifiChannel.Create())
        wifiInfra.SetRemoteStationManager('ns3::ArfWifiManager')
        macInfra = ns.wifi.WifiMacHelper()
        macInfra.SetType("ns3::StaWifiMac", "Ssid", ns.wifi.SsidValue(ssid))

        # setup stas
        staDevices = wifiInfra.Install(wifiPhy, macInfra, stas)
        # setup ap.
        macInfra.SetType("ns3::ApWifiMac", "Ssid", ns.wifi.SsidValue(ssid))
        apDevices = wifiInfra.Install(wifiPhy, macInfra, backbone.Get(i))
        # Collect all of these new devices
        infraDevices = ns.network.NetDeviceContainer(apDevices, staDevices)

        #  Add the IPv4 protocol stack to the nodes in our container
        #
        internet.Install(stas)
        #
        #  Assign IPv4 addresses to the device drivers(actually to the associated
        #  IPv4 interfaces) we just created.
        #
        ipAddrs.Assign(infraDevices)
        #
        #  Assign a new network prefix for each mobile network, according to
        #  the network mask initialized above
        #
        ipAddrs.NewNetwork()
        #
        #  The new wireless nodes need a mobility model so we aggregate one
        #  to each of the nodes we just finished building.
        #
        subnetAlloc = ns.mobility.ListPositionAllocator()
        for j in range(infra.GetN()):
            subnetAlloc.Add(ns.core.Vector(0.0, j, 0.0))

        mobility.PushReferenceMobilityModel(backbone.Get(i))
        mobility.SetPositionAllocator(subnetAlloc)
        mobility.SetMobilityModel(
            "ns3::RandomDirection2dMobilityModel", "Bounds",
            ns.mobility.RectangleValue(ns.mobility.Rectangle(-10, 10, -10,
                                                             10)), "Speed",
            ns.core.StringValue("ns3::ConstantRandomVariable[Constant=3]"),
            "Pause",
            ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0.4]"))
        mobility.Install(stas)

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #                                                                        #
    #  Application configuration                                             #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /

    #  Create the OnOff application to send UDP datagrams of size
    #  210 bytes at a rate of 448 Kb/s, between two nodes
    print("Create Applications.")
    port = 9  #  Discard port(RFC 863)

    appSource = ns.network.NodeList.GetNode(backboneNodes)
    lastNodeIndex = backboneNodes + backboneNodes * (
        lanNodes - 1) + backboneNodes * (infraNodes - 1) - 1
    appSink = ns.network.NodeList.GetNode(lastNodeIndex)
    # Let's fetch the IP address of the last node, which is on Ipv4Interface 1
    remoteAddr = appSink.GetObject(ns.internet.Ipv4.GetTypeId()).GetAddress(
        1, 0).GetLocal()

    onoff = ns.applications.OnOffHelper(
        "ns3::UdpSocketFactory",
        ns.network.Address(ns.network.InetSocketAddress(remoteAddr, port)))
    apps = onoff.Install(ns.network.NodeContainer(appSource))
    apps.Start(ns.core.Seconds(3))
    apps.Stop(ns.core.Seconds(stopTime - 1))

    #  Create a packet sink to receive these packets
    sink = ns.applications.PacketSinkHelper(
        "ns3::UdpSocketFactory",
        ns.network.InetSocketAddress(ns.network.Ipv4Address.GetAny(), port))
    apps = sink.Install(ns.network.NodeContainer(appSink))
    apps.Start(ns.core.Seconds(3))

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #                                                                        #
    #  Tracing configuration                                                 #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /

    print("Configure Tracing.")
    csma = ns.csma.CsmaHelper()
    #
    #  Let's set up some ns-2-like ascii traces, using another helper class
    #
    ascii = ns.network.AsciiTraceHelper()
    stream = ascii.CreateFileStream("mixed-wireless.tr")
    wifiPhy.EnableAsciiAll(stream)
    csma.EnableAsciiAll(stream)
    internet.EnableAsciiIpv4All(stream)

    #  Csma captures in non-promiscuous mode
    csma.EnablePcapAll("mixed-wireless", False)
    #  Let's do a pcap trace on the backbone devices
    wifiPhy.EnablePcap("mixed-wireless", backboneDevices)
    wifiPhy.EnablePcap("mixed-wireless", appSink.GetId(), 0)

    #   #ifdef ENABLE_FOR_TRACING_EXAMPLE
    #     Config.Connect("/NodeList/*/$MobilityModel/CourseChange",
    #       MakeCallback(&CourseChangeCallback))
    #   #endif

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    #                                                                        #
    #  Run simulation                                                        #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

    print("Run Simulation.")
    ns.core.Simulator.Stop(ns.core.Seconds(stopTime))
    ns.core.Simulator.Run()
    ns.core.Simulator.Destroy()
Example #24
0
def main(argv):

    cmd = ns.core.CommandLine()
    cmd.Parse(argv)

    terminals = ns.network.NodeContainer()
    terminals.Create(4)

    csmaSwitch = ns.network.NodeContainer()
    csmaSwitch.Create(1)

    csma = ns.csma.CsmaHelper()
    csma.SetChannelAttribute(
        "DataRate", ns.network.DataRateValue(ns.network.DataRate(5000000)))
    csma.SetChannelAttribute("Delay",
                             ns.core.TimeValue(ns.core.MilliSeconds(2)))

    terminalDevices = ns.network.NetDeviceContainer()
    switchDevices = ns.network.NetDeviceContainer()

    for i in range(4):
        link = csma.Install(
            ns.network.NodeContainer(
                ns.network.NodeContainer(terminals.Get(i)), csmaSwitch))
        terminalDevices.Add(link.Get(0))
        switchDevices.Add(link.Get(1))

    switchNode = csmaSwitch.Get(0)
    bridgeDevice = ns.bridge.BridgeNetDevice()
    switchNode.AddDevice(bridgeDevice)

    for portIter in range(switchDevices.GetN()):
        bridgeDevice.AddBridgePort(switchDevices.Get(portIter))

    internet = ns.internet.InternetStackHelper()
    internet.Install(terminals)

    ipv4 = ns.internet.Ipv4AddressHelper()
    ipv4.SetBase(ns.network.Ipv4Address("10.1.1.0"),
                 ns.network.Ipv4Mask("255.255.255.0"))
    ipv4.Assign(terminalDevices)

    port = 9

    onoff = ns.applications.OnOffHelper(
        "ns3::UdpSocketFactory",
        ns.network.Address(
            ns.network.InetSocketAddress(ns.network.Ipv4Address("10.1.1.2"),
                                         port)))
    onoff.SetAttribute(
        "OnTime", ns.core.RandomVariableValue(ns.core.ConstantVariable(1)))
    onoff.SetAttribute(
        "OffTime", ns.core.RandomVariableValue(ns.core.ConstantVariable(0)))

    app = onoff.Install(ns.network.NodeContainer(terminals.Get(0)))

    app.Start(ns.core.Seconds(1.0))
    app.Stop(ns.core.Seconds(10.0))

    sink = ns.applications.PacketSinkHelper(
        "ns3::UdpSocketFactory",
        ns.network.Address(
            ns.network.InetSocketAddress(ns.network.Ipv4Address.GetAny(),
                                         port)))
    app = sink.Install(ns.network.NodeContainer(terminals.Get(1)))
    app.Start(ns.core.Seconds(0.0))

    onoff.SetAttribute(
        "Remote",
        ns.network.AddressValue(
            ns.network.InetSocketAddress(ns.network.Ipv4Address("10.1.1.1"),
                                         port)))
    app = onoff.Install(ns.network.NodeContainer(terminals.Get(3)))
    app.Start(ns.core.Seconds(1.1))
    app.Stop(ns.core.Seconds(10.0))

    app = sink.Install(ns.network.NodeContainer(terminals.Get(0)))
    app.Start(ns.core.Seconds(0.0))

    csma.EnablePcapAll("csma-bridge", False)

    ns.core.Simulator.Run()
    ns.core.Simulator.Destroy()
Example #25
0
def main(argv):

    #
    # Allow the user to override any of the defaults and the above Bind() at
    # run-time, via command-line arguments
    #
    cmd = ns.core.CommandLine()
    cmd.Parse(argv)

    #
    # Explicitly create the nodes required by the topology(shown above).
    #
    #print "Create nodes."
    terminals = ns.network.NodeContainer()
    terminals.Create(4)

    csmaSwitch = ns.network.NodeContainer()
    csmaSwitch.Create(1)

    #print "Build Topology"
    csma = ns.csma.CsmaHelper()
    csma.SetChannelAttribute(
        "DataRate", ns.network.DataRateValue(ns.network.DataRate(5000000)))
    csma.SetChannelAttribute("Delay",
                             ns.core.TimeValue(ns.core.MilliSeconds(2)))

    # Create the csma links, from each terminal to the switch

    terminalDevices = ns.network.NetDeviceContainer()
    switchDevices = ns.network.NetDeviceContainer()

    for i in range(4):
        link = csma.Install(
            ns.network.NodeContainer(
                ns.network.NodeContainer(terminals.Get(i)), csmaSwitch))
        terminalDevices.Add(link.Get(0))
        switchDevices.Add(link.Get(1))

    # Create the bridge netdevice, which will do the packet switching
    switchNode = csmaSwitch.Get(0)
    bridgeDevice = ns.bridge.BridgeNetDevice()
    switchNode.AddDevice(bridgeDevice)

    for portIter in range(switchDevices.GetN()):
        bridgeDevice.AddBridgePort(switchDevices.Get(portIter))

    # Add internet stack to the terminals
    internet = ns.internet.InternetStackHelper()
    internet.Install(terminals)

    # We've got the "hardware" in place.  Now we need to add IP addresses.
    #
    #print "Assign IP Addresses."
    ipv4 = ns.internet.Ipv4AddressHelper()
    ipv4.SetBase(ns.network.Ipv4Address("10.1.1.0"),
                 ns.network.Ipv4Mask("255.255.255.0"))
    ipv4.Assign(terminalDevices)

    #
    # Create an OnOff application to send UDP datagrams from node zero to node 1.
    #
    #print "Create Applications."
    port = 9  # Discard port(RFC 863)

    onoff = ns.applications.OnOffHelper(
        "ns3::UdpSocketFactory",
        ns.network.Address(
            ns.network.InetSocketAddress(ns.network.Ipv4Address("10.1.1.2"),
                                         port)))
    onoff.SetConstantRate(ns.network.DataRate("500kb/s"))

    app = onoff.Install(ns.network.NodeContainer(terminals.Get(0)))
    # Start the application
    app.Start(ns.core.Seconds(1.0))
    app.Stop(ns.core.Seconds(10.0))

    # Create an optional packet sink to receive these packets
    sink = ns.applications.PacketSinkHelper(
        "ns3::UdpSocketFactory",
        ns.network.Address(
            ns.network.InetSocketAddress(ns.network.Ipv4Address.GetAny(),
                                         port)))
    app = sink.Install(ns.network.NodeContainer(terminals.Get(1)))
    app.Start(ns.core.Seconds(0.0))

    #
    # Create a similar flow from n3 to n0, starting at time 1.1 seconds
    #
    onoff.SetAttribute(
        "Remote",
        ns.network.AddressValue(
            ns.network.InetSocketAddress(ns.network.Ipv4Address("10.1.1.1"),
                                         port)))
    app = onoff.Install(ns.network.NodeContainer(terminals.Get(3)))
    app.Start(ns.core.Seconds(1.1))
    app.Stop(ns.core.Seconds(10.0))

    app = sink.Install(ns.network.NodeContainer(terminals.Get(0)))
    app.Start(ns.core.Seconds(0.0))

    #
    # Configure tracing of all enqueue, dequeue, and NetDevice receive events.
    # Trace output will be sent to the file "csma-bridge.tr"
    #
    #print "Configure Tracing."
    #ascii = ns.network.AsciiTraceHelper();
    #csma.EnableAsciiAll(ascii.CreateFileStream ("csma-bridge.tr"));

    #
    # Also configure some tcpdump traces; each interface will be traced.
    # The output files will be named:
    #     csma-bridge.pcap-<nodeId>-<interfaceId>
    # and can be read by the "tcpdump -r" command(use "-tt" option to
    # display timestamps correctly)
    #
    csma.EnablePcapAll("csma-bridge", False)

    #
    # Now, do the actual simulation.
    #
    #print "Run Simulation."
    ns.core.Simulator.Run()
    ns.core.Simulator.Destroy()
Example #26
0
def main():
    if not len(sys.argv[1:]):
        print "Usage: {0} traceFile".format(sys.argv[0])
        sys.exit(0)

    traceFile = sys.argv[1]
    phyMode = "OfdmRate6MbpsBW10MHz"

    nodes = ns.network.NodeContainer()
    nodes.Create(25)

    # ns.core.LogComponentEnable("Ns2MobilityHelper", ns.core.LOG_LEVEL_DEBUG)

    try:
        ns2 = ns.mobility.Ns2MobilityHelper(str(traceFile))
    except Exception as err:
        print "Error: %s" % str(err)
        sys.exit(0)

    mobility = ns.mobility.MobilityHelper()
    # mobility.SetPositionAllocator ("ns3::GridPositionAllocator", "MinX", ns.core.DoubleValue(0.0),
    # 								"MinY", ns.core.DoubleValue (0.0), "DeltaX", ns.core.DoubleValue(5.0), "DeltaY", ns.core.DoubleValue(10.0),
    #                                  "GridWidth", ns.core.UintegerValue(3), "LayoutType", ns.core.StringValue("RowFirst"))
    #
    # mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel")
    mobility.Install(nodes)
    ns2.Install()

    channel = ns.wifi.YansWifiChannelHelper.Default()
    channel.SetPropagationDelay("ns3::ConstantSpeedPropagationDelayModel")
    channel.AddPropagationLoss("ns3::NakagamiPropagationLossModel")
    phy = ns.wifi.YansWifiPhyHelper.Default()
    phy.SetChannel(channel.Create())
    phy.SetPcapDataLinkType(ns.wifi.YansWifiPhyHelper.DLT_IEEE802_11)
    phy.Set("TxGain", ns.core.DoubleValue(4.5))
    phy.Set("RxGain", ns.core.DoubleValue(4.5))
    phy.Set("EnergyDetectionThreshold", ns.core.DoubleValue(-96.0))
    # phy.EnablePcap("vanets_python",nodes)

    wifi80211pMac = ns.wave.NqosWaveMacHelper.Default()
    wifi80211p = ns.wave.Wifi80211pHelper.Default()

    wifi80211p.SetRemoteStationManager("ns3::ConstantRateWifiManager",
                                       "DataMode",
                                       ns.core.StringValue(phyMode),
                                       "ControlMode",
                                       ns.core.StringValue(phyMode))
    devices = wifi80211p.Install(phy, wifi80211pMac, nodes)

    internet = ns.internet.InternetStackHelper()
    internet.Install(nodes)

    ipv4 = ns.internet.Ipv4AddressHelper()
    ipv4.SetBase(ns.network.Ipv4Address("192.168.1.0"),
                 ns.network.Ipv4Mask("255.255.255.0"))

    interfaces = ipv4.Assign(devices)

    packetsize = 64  #bytes
    pktcount = 2
    pktinterval = 0.25  #seconds
    port = 80

    server = random.randint(0, 24)
    print "Server==> %s" % interfaces.GetAddress(server)

    appSink = ns.network.NodeList.GetNode(server)

    for x in range(4):
        client = random.randint(0, 24)
        print "Client==> %s" % interfaces.GetAddress(client)
        appSource = ns.network.NodeList.GetNode(client)

        remoteAddr = appSink.GetObject(
            ns.internet.Ipv4.GetTypeId()).GetAddress(1, 0).GetLocal()
        # sink = ns.network.Socket.CreateSocket(appSink, ns.core.TypeId.LookupByName("ns3::UdpSocketFactory"))
        sink = ns.network.Socket.CreateSocket(
            appSink, ns.core.TypeId.LookupByName("ns3::TcpSocketFactory"))
        sink.Bind(
            ns.network.InetSocketAddress(ns.network.Ipv4Address.GetAny(), 80))
        sink.Listen()
        # print dir(sink)
        sink.SetRecvCallback(RecPkt)

        # source = ns.network.Socket.CreateSocket(appSource, ns.core.TypeId.LookupByName("ns3::UdpSocketFactory"))
        source = ns.network.Socket.CreateSocket(
            appSource, ns.core.TypeId.LookupByName("ns3::TcpSocketFactory"))
        source.Connect(ns.network.InetSocketAddress(remoteAddr, port))
        source.SetRecvCallback(RecPkt)

    # sinkApp = ns.network.ApplicationContainer()
    # port = 50000
    # # apLocalAddress = ns.network.Address (ns.network.InetSocketAddress (ns.network.Ipv4Address.GetAny (), port))
    # for x in range(0,6):
    #     apLocalAddress = ns.network.Address (ns.network.InetSocketAddress (ns.network.Ipv4Address.GetAny (), port))
    #     packetSinkHelper = ns.applications.PacketSinkHelper ("ns3::TcpSocketFactory", apLocalAddress)
    #     sinkApp.Add(packetSinkHelper.Install (nodes.Get (x)))
    #
    # sinkApp.Start (ns.core.Seconds (0.0))
    # sinkApp.Stop (ns.core.Seconds (141.0))
    #
    # onoff = ns.applications.OnOffHelper ("ns3::TcpSocketFactory", ns.network.Ipv4Address.GetAny ())
    # onoff.SetAttribute ("OnTime",  ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=1]"))
    # onoff.SetAttribute ("OffTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=0]"))
    # onoff.SetAttribute ("PacketSize", ns.core.UintegerValue (2048))
    # # onoff.SetAttribute ("DataRate", ns.network.DataRateValue (ns.network.DataRate (100000))) # bit/s
    #
    # apps = ns.network.ApplicationContainer ()
    # # remoteAddress = ns.network.AddressValue (ns.network.InetSocketAddress (interfaces.GetAddress (0), port))
    #
    # for x in range(7,14):
    #     rn = random.randint(0,3)
    #     print "Server >>: {0}".format(rn)
    #     remoteAddress = ns.network.AddressValue (ns.network.InetSocketAddress (interfaces.GetAddress (rn), port))
    #     onoff.SetAttribute ("Remote", remoteAddress)
    #     apps.Add (onoff.Install (nodes.Get (x)))
    #
    # apps.Start (ns.core.Seconds (1.0))
    # apps.Stop (ns.core.Seconds (141.0))

    ns.internet.Ipv4GlobalRoutingHelper.PopulateRoutingTables()

    asciitracer = ns.network.AsciiTraceHelper()
    # phy.EnableAsciiAll (asciitracer.CreateFileStream ("vanets.tr"))
    phy.EnablePcap("vanets", nodes)
    ns.core.Simulator.Schedule(ns.core.Seconds(10.0), SndPkt, source,
                               packetsize, pktcount, pktinterval)

    ns.core.Simulator.Stop(ns.core.Seconds(161.0))
    ns.core.Simulator.Run()
    ns.core.Simulator.Destroy()
Example #27
0
def experiment(enableCtsRts):

    # 0. Enable or disable CTS/RTS
    ctsThr = 100 if enableCtsRts else 2200
    ns.core.Config.SetDefault ("ns3::WifiRemoteStationManager::RtsCtsThreshold", ns.core.UintegerValue (ctsThr))

    # 1. Create 3 nodes
    nodes = ns.network.NodeContainer ()
    nodes.Create (3)

    # 2. Place nodes somehow, this is required by every wireless simulation
    i = 0
    while i < 3:
        nodes.Get (i).AggregateObject (ns.mobility.ConstantPositionMobilityModel ())
        i += 1

    # 3. Create propagation loss matrix
    lossModel = ns.propagation.MatrixPropagationLossModel ()
    lossModel.SetDefaultLoss (200) #set default loss to 200 dB (no link)
    lossModel.SetLoss (nodes.Get (0).GetObject (ns.mobility.MobilityModel.GetTypeId ()), nodes.Get (1).GetObject (ns.mobility.MobilityModel.GetTypeId ()), 50)
    lossModel.SetLoss (nodes.Get (2).GetObject (ns.mobility.MobilityModel.GetTypeId ()), nodes.Get (1).GetObject (ns.mobility.MobilityModel.GetTypeId ()), 50)

    # 4. Create & setup wifi channel
    wifiChannel = ns.wifi.YansWifiChannel ()
    wifiChannel.SetPropagationLossModel (lossModel)
    wifiChannel.SetPropagationDelayModel (ns.propagation.ConstantSpeedPropagationDelayModel ())

    # 5. Install wireless devices
    wifi = ns.wifi.WifiHelper ()
    wifi.SetStandard (ns.wifi.WIFI_PHY_STANDARD_80211b)
    wifi.SetRemoteStationManager ("ns3::ConstantRateWifiManager",
                                  "DataMode", ns.core.StringValue ("DsssRate2Mbps"),
                                  "ControlMode", ns.core.StringValue ("DsssRate1Mbps"))

    wifiPhy = ns.wifi.YansWifiPhyHelper.Default ()
    wifiPhy.SetChannel (wifiChannel)
    wifiMac = ns.wifi.NqosWifiMacHelper.Default ()
    wifiMac.SetType ("ns3::AdhocWifiMac")  # use ad-hoc MAC
    devices = wifi.Install (wifiPhy,wifiMac,nodes)

    # uncomment the following to have athstats output
    # athstats=ns3.AthstatsHelper ()
    # athstats.EnableAthstats ("rtscts-athstats-node-py" if enableCtsRts else "basic-athstats-node-py", nodes)

    # uncomment the following to have pcap output
    # wifiPhy.EnablePcap ("rtscts-pcap-node-py" if enableCtsRts else "basic-pcap-node-py",nodes)

    # 6. Install TCP/IP stack & assign IP addresses
    internet = ns.internet.InternetStackHelper ()
    internet.Install (nodes)
    ipv4 = ns.internet.Ipv4AddressHelper ()
    ipv4.SetBase (ns.network.Ipv4Address ("10.0.0.0"), ns.network.Ipv4Mask ("255.0.0.0"))
    ipv4.Assign (devices)

    # 7. Install applications: two CBR streams each saturating the channel
    cbrApps = ns.network.ApplicationContainer ()
    cbrPort = 12345
    onOffHelper = ns.applications.OnOffHelper ("ns3::UdpSocketFactory", ns.network.InetSocketAddress (ns.network.Ipv4Address ("10.0.0.2"), cbrPort))
    onOffHelper.SetAttribute ("PacketSize", ns.core.UintegerValue (1400))
    onOffHelper.SetAttribute ("OnTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=1]"))
    onOffHelper.SetAttribute ("OffTime", ns.core.StringValue ("ns3::ConstantRandomVariable[Constant=0]"))

    # flow 1:  node 0 -> node 1
    onOffHelper.SetAttribute ("DataRate", ns.core.StringValue ("3000000bps"))
    onOffHelper.SetAttribute ("StartTime", ns.core.TimeValue (ns.core.Seconds (1.000000)))
    cbrApps.Add (onOffHelper.Install (nodes.Get (0)))

    # flow 2:  node 2 -> node 1
    # \internal
    # The slightly different start times and data rates are a workaround
    # for \bugid{388} and \bugid{912}
    #
    onOffHelper.SetAttribute ("DataRate", ns.core.StringValue ("3001100bps"))
    onOffHelper.SetAttribute ("StartTime", ns.core.TimeValue (ns.core.Seconds (1.001)))
    cbrApps.Add (onOffHelper.Install (nodes.Get (2)))

    # \internal
    # We also use separate UDP applications that will send a single
    # packet before the CBR flows start. 
    # This is a workaround for the lack of perfect ARP, see \bugid{187}
    #
    echoPort = 9
    echoClientHelper = ns.applications.UdpEchoClientHelper (ns.network.Ipv4Address ("10.0.0.2"), echoPort)
    echoClientHelper.SetAttribute ("MaxPackets", ns.core.UintegerValue (1))
    echoClientHelper.SetAttribute ("Interval", ns.core.TimeValue (ns.core.Seconds (0.1)))
    echoClientHelper.SetAttribute ("PacketSize", ns.core.UintegerValue (10))
    pingApps = ns.network.ApplicationContainer ()

    # again using different start times to workaround Bug 388 and Bug 912
    echoClientHelper.SetAttribute ("StartTime", ns.core.TimeValue (ns.core.Seconds (0.001)))
    pingApps.Add (echoClientHelper.Install(nodes.Get (0)))
    echoClientHelper.SetAttribute ("StartTime", ns.core.TimeValue (ns.core.Seconds (0.006)))
    pingApps.Add (echoClientHelper.Install (nodes.Get (2)))

    # 8. Install FlowMonitor on all nodes
    flowmon = ns.flow_monitor.FlowMonitorHelper ()
    monitor = flowmon.InstallAll ()

    # 9. Run simulation for 10 seconds
    ns.core.Simulator.Stop (ns.core.Seconds (10))
    ns.core.Simulator.Run ()

    # 10. Print per flow statistics
    monitor.CheckForLostPackets ()
    classifier = ns.flow_monitor.Ipv4FlowClassifier ()
    classifier = flowmon.GetClassifier ()
    stats = monitor.GetFlowStats ()
    for flow_id, flow_stats in monitor.GetFlowStats ():
        # first 2 FlowIds are for ECHO apps, we don't want to display them

        # Duration for throughput measurement is 9.0 seconds, since
        # StartTime of the OnOffApplication is at about "second 1"
        # and
        # Simulator::Stops at "second 10".
        t = classifier.FindFlow(flow_id)
        if flow_id > 2:
            print "FlowID %i (%s -> %s)" % \
            (flow_id-2, t.sourceAddress, t.destinationAddress)
            print >> sys.stdout, "  Tx Packets: ", flow_stats.txPackets
            print >> sys.stdout, "  Tx Bytes: ", flow_stats.txBytes
            print >> sys.stdout, "  TxOffered:  ", flow_stats.txBytes * 8.0 / 9.0 / 1000 / 1000  , " Mbps"
            print >> sys.stdout, "  Rx Packets: ", flow_stats.rxPackets
            print >> sys.stdout, "  Rx Bytes: ", flow_stats.rxBytes
            print >> sys.stdout, "  Throughput: ", flow_stats.rxBytes * 8.0 / 9.0 / 1000 / 1000  , " Mbps"

    # 11. Cleanup
    ns.core.Simulator.Destroy ()
Example #28
0
def main(argv):
    #
    #  Primero, inicializamos algunas variables locales que controlan algunos
    #  parametros de la simulacion.
    #

    cmd = ns.core.CommandLine()
    cmd.backboneNodes = 25
    cmd.stopTime = 20

    ns.core.Config.SetDefault("ns3::OnOffApplication::PacketSize",
                              ns.core.StringValue("1472"))
    ns.core.Config.SetDefault("ns3::OnOffApplication::DataRate",
                              ns.core.StringValue("100kb/s"))

    cmd.AddValue("backboneNodes", "number of backbone nodes")
    cmd.AddValue("stopTime", "simulation stop time(seconds)")

    cmd.Parse(argv)

    backboneNodes = int(cmd.backboneNodes)
    stopTime = int(cmd.stopTime)

    if (stopTime < 10):
        print("Use a simulation stop time >= 10 seconds")
        exit(1)
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /
    #                                                                        #
    #  EL backbone                                                           #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # /

    #
    #  Creamos un contenedor para administrar los nodos de la red adhoc (backbone).
    #
    backbone = ns.network.NodeContainer()
    backbone.Create(backboneNodes)
    #
    #  Creamos los dispositivos de red wifi y los instalamos
    #  en nuestro contenedor
    #
    wifi = ns.wifi.WifiHelper()
    mac = ns.wifi.WifiMacHelper()
    mac.SetType("ns3::AdhocWifiMac")
    wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager", "DataMode",
                                 ns.core.StringValue("OfdmRate54Mbps"))
    wifiPhy = ns.wifi.YansWifiPhyHelper.Default()
    wifiChannel = ns.wifi.YansWifiChannelHelper.Default()
    wifiPhy.SetChannel(wifiChannel.Create())
    backboneDevices = wifi.Install(wifiPhy, mac, backbone)
    #
    #  Agregamos la pila de protocolos IPv4 a los nodos en nuestro contenedor
    #
    internet = ns.internet.InternetStackHelper()
    olsr = ns.olsr.OlsrHelper()
    internet.SetRoutingHelper(olsr)
    internet.Install(backbone)
    # internet.Reset()
    #
    #  Asignamos direcciones IPv4 a los controladores de dispositivo (en realidad a las interfaces
    #  IPv4 asociadas) que acabamos de crear.
    #
    ipAddrs = ns.internet.Ipv4AddressHelper()
    ipAddrs.SetBase(ns.network.Ipv4Address("192.168.0.0"),
                    ns.network.Ipv4Mask("255.255.255.0"))
    ipAddrs.Assign(backboneDevices)
    #
    #  Los nodos de red ad-hoc necesitan un modelo de movilidad, por lo que agregamos uno para
    #  cada uno de los nodos que acabamos de terminar de construir.
    #
    mobility = ns.mobility.MobilityHelper()
    mobility.SetPositionAllocator("ns3::GridPositionAllocator", "MinX",
                                  ns.core.DoubleValue(20.0), "MinY",
                                  ns.core.DoubleValue(20.0), "DeltaX",
                                  ns.core.DoubleValue(20.0), "DeltaY",
                                  ns.core.DoubleValue(20.0), "GridWidth",
                                  ns.core.UintegerValue(5), "LayoutType",
                                  ns.core.StringValue("RowFirst"))
    mobility.SetMobilityModel(
        "ns3::RandomDirection2dMobilityModel", "Bounds",
        ns.mobility.RectangleValue(ns.mobility.Rectangle(-500, 500, -500,
                                                         500)), "Speed",
        ns.core.StringValue("ns3::ConstantRandomVariable[Constant=2]"),
        "Pause",
        ns.core.StringValue("ns3::ConstantRandomVariable[Constant=0.2]"))
    mobility.Install(backbone)

    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    #                                                                        #
    #  Corremos la simulacion                                                #
    #                                                                        #
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    print("Corremos la simulacion.")
    ns.core.Simulator.Stop(ns.core.Seconds(stopTime))
    ns.core.Simulator.Run()
    ns.core.Simulator.Destroy()