def _add_onoff_app(self, start_time, end_time, local, remote, on_time, off_time, data_rate, sport, dport): """add one ns3 onoff application to the network """ # ignore the network prefix length if there is if '/' in remote: remote = remote.rsplit('/')[0] if '/' in local: local = local.rsplit('/')[0] ### Install OnOff Application ### socketType = "ns3::UdpSocketFactory" # socketType = "ns3::TcpSocketFactory" helper = ns3.OnOffHelper(socketType, ns3.InetSocketAddress(remote, dport)) helper.SetAttribute("StartTime", ns3.TimeValue(ns3.Time(str(start_time) + 's'))) helper.SetAttribute("StopTime", ns3.TimeValue(ns3.Time(str(end_time) + 's'))) # helper.SetAttribute("Remote", ns3.AddressValue(ns3.Ipv4Address(remote))) local_inet = ns3.InetSocketAddress(local, sport) helper.SetAttribute("Local", ns3.AddressValue(local_inet)) helper.SetAttribute("DataRate", ns3.StringValue(str(data_rate) + 'b/s')) helper.SetAttribute("OnTime", ns3.RandomVariableValue(on_time.to_ns3())) helper.SetAttribute("OffTime", ns3.RandomVariableValue(off_time.to_ns3())) print('local, ', local) local_node = self.net.search_node(local) helper.Install(local_node) ### Install Sink Application #### sinkLocalAddress = ns3.Address( ns3.InetSocketAddress(ns3.Ipv4Address.GetAny(), dport)) sinkHelper = ns3.PacketSinkHelper(socketType, sinkLocalAddress) helper.SetAttribute("StartTime", ns3.TimeValue(ns3.Time(str(start_time) + 's'))) helper.SetAttribute("StopTime", ns3.TimeValue(ns3.Time(str(end_time) + 's'))) remote_node = self.net.search_node(remote) print('remote, ', remote) sinkHelper.Install(remote_node) print("""add an onoff application with start_time: %f end_time: %f local: %s, remote: %s, on_time: %s, off_time: %s""" % (start_time, end_time, local, remote, on_time, off_time))
def onoff_app(network, client_node, server_node, server_device, start, stop, rate, port=9, packet_size=1024, access_class=None, ontime=1, offtime=0): """Set up a OnOff client + sink server.""" server = network.nodes[server_node] assert server_device in server.devices, \ "Device '%s' not found, available: %s" % (server_device, ", ".join(server.devices)) server_address = server.devices[server_device].interfaces[0].address local_address = ns3.InetSocketAddress(ns3.Ipv4Address.GetAny(), port) sink_helper = ns3.PacketSinkHelper("ns3::UdpSocketFactory", local_address) server_apps = sink_helper.Install(server.ns3_node) server_apps.Start(ns3.Seconds(start)) server_apps.Stop(ns3.Seconds(stop)) client = network.nodes[client_node] remote_address = ns3.InetSocketAddress(server_address, port) onoff_helper = ns3.OnOffHelper("ns3::UdpSocketFactory", ns3.Address()) onoff_helper.SetAttribute( "OnTime", ns3.RandomVariableValue(ns3.ConstantVariable(ontime))) onoff_helper.SetAttribute( "OffTime", ns3.RandomVariableValue(ns3.ConstantVariable(offtime))) onoff_helper.SetAttribute("DataRate", ns3.DataRateValue(ns3.DataRate(rate))) onoff_helper.SetAttribute("PacketSize", ns3.UintegerValue(packet_size)) onoff_helper.SetAttribute("Remote", ns3.AddressValue(remote_address)) # Set QoS Access Class -> Tid # Note that this only works with a patched OnOffApplication with QosTid attribute if access_class is not None: access_class_to_qos_tid = { "ac_vo": 6, # AC_VO (Tid: 6, 7) "ac_vi": 4, # AC_VI (Tid: 4, 5) "ac_be": 0, # AC_BE (Tid: 0) "ac_bk": 1, # AC_BK (Tid: 1, 2) "ac_be_nqos": 3, # AC_BE_NQOS (Tid: 3) } qos_tid = access_class_to_qos_tid[access_class.lower()] onoff_helper.SetAttribute("QosTid", ns3.UintegerValue(qos_tid)) client_apps = onoff_helper.Install(client.ns3_node) client_apps.Start(ns3.Seconds(start)) client_apps.Stop(ns3.Seconds(stop))
def connect(self, sock, addr_port): """Will set Connect callback function. If succeeded, self.recv will be called. otherwise the sock will be closed""" server_addr = self._search_server_addr(addr_port[0]) print 'addr_port, ', addr_port print 'server_addr, ', server_addr print 'serval local, ', self.server_addr_set[0].GetLocal() # import pdb;pdb.set_trace() assert (str(server_addr) == str(self.server_addr_set[0].GetLocal())) # import pdb;pdb.set_trace() inetAddr = ns3.InetSocketAddress( server_addr, # self.server_addr_set[0].GetLocal(), # connect to first server addr_port[1]) def connect_succeeded(sock): print 'Node [%s] connect succeeded' % (self.name) self.logger.debug('Node [%s] connect succeeded' % (self.name)) # self.recv(sock, 512, self.dispatcher) self.after(0, self.recv, sock, 512, self.dispatcher) def connect_failed(sock): self.logger.debug('Node [%s] connect failed' % (self.name)) self.close_sock(sock) sock.SetConnectCallback(connect_succeeded, connect_failed) ret = sock.Connect(inetAddr) if ret == -1: print 'node [%s] cannot connect to server' % (self.name) # raise Exception('node [%s] cannot connect to server'%(self.name) ) print 'node %s connected to server' % (self.name)
def bind(self, sock, addr_port): self.logger.debug('Node [%s] start to bind to %s' % (self.name, addr_port)) addr = self._search_server_addr(addr_port[0]) # import pdb;pdb.set_trace() dst = ns3.InetSocketAddress(addr, addr_port[1]) # dst = ns3.InetSocketAddress (ns3.Ipv4Address('10.0.1.1'), addr_port[1]) sock.Bind(dst)
def testSocket(self): node = ns3.Node() internet = ns3.InternetStackHelper() internet.Install(node) self._received_packet = None def rx_callback(socket): assert self._received_packet is None self._received_packet = socket.Recv() sink = ns3.Socket.CreateSocket(node, ns3.TypeId.LookupByName("ns3::UdpSocketFactory")) sink.Bind(ns3.InetSocketAddress(ns3.Ipv4Address.GetAny(), 80)) sink.SetRecvCallback(rx_callback) source = ns3.Socket.CreateSocket(node, ns3.TypeId.LookupByName("ns3::UdpSocketFactory")) source.SendTo(ns3.Packet(19), 0, ns3.InetSocketAddress(ns3.Ipv4Address("127.0.0.1"), 80)) ns3.Simulator.Run() self.assert_(self._received_packet is not None) self.assertEqual(self._received_packet.GetSize(), 19)
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. # ns3.Config.SetDefault("ns3::OnOffApplication::PacketSize", ns3.StringValue("210")) ns3.Config.SetDefault("ns3::OnOffApplication::DataRate", ns3.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 = ns3.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 = ns3.NodeContainer() backbone.Create(backboneNodes) # # Create the backbone wifi net devices and install them into the nodes in # our container # wifi = ns3.WifiHelper() mac = ns3.NqosWifiMacHelper.Default() mac.SetType("ns3::AdhocWifiMac") wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager", "DataMode", ns3.StringValue("OfdmRate54Mbps")) wifiPhy = ns3.YansWifiPhyHelper.Default() wifiChannel = ns3.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 = ns3.InternetStackHelper() olsr = ns3.OlsrHelper() internet.SetRoutingHelper(olsr) 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 = ns3.Ipv4AddressHelper() ipAddrs.SetBase(ns3.Ipv4Address("192.168.0.0"), ns3.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 = ns3.MobilityHelper() positionAlloc = ns3.ListPositionAllocator() x = 0.0 for i in range(backboneNodes): positionAlloc.Add(ns3.Vector(x, 0.0, 0.0)) x += 5.0 mobility.SetPositionAllocator(positionAlloc) mobility.SetMobilityModel( "ns3::RandomDirection2dMobilityModel", "Bounds", ns3.RectangleValue(ns3.Rectangle(0, 1000, 0, 1000)), "Speed", ns3.RandomVariableValue(ns3.ConstantVariable(2000)), "Pause", ns3.RandomVariableValue(ns3.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(ns3.Ipv4Address("172.16.0.0"), ns3.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 = ns3.NodeContainer() newLanNodes.Create(lanNodes - 1) # Now, create the container with all nodes on this link lan = ns3.NodeContainer(ns3.NodeContainer(backbone.Get(i)), newLanNodes) # # Create the CSMA net devices and install them into the nodes in our # collection. # csma = ns3.CsmaHelper() csma.SetChannelAttribute("DataRate", ns3.DataRateValue(ns3.DataRate(5000000))) csma.SetChannelAttribute("Delay", ns3.TimeValue(ns3.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(ns3.Ipv4Address("10.0.0.0"), ns3.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 = ns3.NodeContainer() stas.Create(infraNodes - 1) # Now, create the container with all nodes on this link infra = ns3.NodeContainer(ns3.NodeContainer(backbone.Get(i)), stas) # # Create another ad hoc network and devices # ssid = ns3.Ssid('wifi-infra' + str(i)) wifiInfra = ns3.WifiHelper.Default() wifiPhy.SetChannel(wifiChannel.Create()) wifiInfra.SetRemoteStationManager('ns3::ArfWifiManager') macInfra = ns3.NqosWifiMacHelper.Default() macInfra.SetType("ns3::NqstaWifiMac", "Ssid", ns3.SsidValue(ssid), "ActiveProbing", ns3.BooleanValue(False)) # setup stas staDevices = wifiInfra.Install(wifiPhy, macInfra, stas) # setup ap. macInfra.SetType("ns3::NqapWifiMac", "Ssid", ns3.SsidValue(ssid), "BeaconGeneration", ns3.BooleanValue(True), "BeaconInterval", ns3.TimeValue(ns3.Seconds(2.5))) apDevices = wifiInfra.Install(wifiPhy, macInfra, backbone.Get(i)) # Collect all of these new devices infraDevices = ns3.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 = ns3.ListPositionAllocator() for j in range(infra.GetN()): subnetAlloc.Add(ns3.Vector(0.0, j, 0.0)) mobility.PushReferenceMobilityModel(backbone.Get(i)) mobility.SetPositionAllocator(subnetAlloc) mobility.SetMobilityModel( "ns3::RandomDirection2dMobilityModel", "Bounds", ns3.RectangleValue(ns3.Rectangle(-25, 25, -25, 25)), "Speed", ns3.RandomVariableValue(ns3.ConstantVariable(30)), "Pause", ns3.RandomVariableValue(ns3.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 = ns3.NodeList.GetNode(11) appSink = ns3.NodeList.GetNode(13) remoteAddr = ns3.Ipv4Address("172.16.0.5") onoff = ns3.OnOffHelper( "ns3::UdpSocketFactory", ns3.Address(ns3.InetSocketAddress(remoteAddr, port))) onoff.SetAttribute("OnTime", ns3.RandomVariableValue(ns3.ConstantVariable(1))) onoff.SetAttribute("OffTime", ns3.RandomVariableValue(ns3.ConstantVariable(0))) apps = onoff.Install(ns3.NodeContainer(appSource)) apps.Start(ns3.Seconds(3.0)) apps.Stop(ns3.Seconds(20.0)) # Create a packet sink to receive these packets sink = ns3.PacketSinkHelper( "ns3::UdpSocketFactory", ns3.InetSocketAddress(ns3.Ipv4Address.GetAny(), port)) apps = sink.Install(ns3.NodeContainer(appSink)) apps.Start(ns3.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 = ns3.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 = ns3.CsmaHelper() csma.EnablePcapAll("mixed-wireless", False) # #ifdef ENABLE_FOR_TRACING_EXAMPLE # Config.Connect("/NodeList/*/$MobilityModel/CourseChange", # MakeCallback(&CourseChangeCallback)) # #endif # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Run simulation # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # print "Run Simulation." ns3.Simulator.Stop(ns3.Seconds(stopTime)) ns3.Simulator.Run() ns3.Simulator.Destroy()
def main(argv): # # Allow the user to override any of the defaults and the above Bind() at # run-time, via command-line arguments # cmd = ns3.CommandLine() cmd.Parse(argv) # # Explicitly create the nodes required by the topology(shown above). # #print "Create nodes." terminals = ns3.NodeContainer() terminals.Create(4) csmaSwitch = ns3.NodeContainer() csmaSwitch.Create(1) #print "Build Topology" csma = ns3.CsmaHelper() csma.SetChannelAttribute("DataRate", ns3.DataRateValue(ns3.DataRate(5000000))) csma.SetChannelAttribute("Delay", ns3.TimeValue(ns3.MilliSeconds(2))) # Create the csma links, from each terminal to the switch terminalDevices = ns3.NetDeviceContainer() switchDevices = ns3.NetDeviceContainer() for i in range(4): link = csma.Install( ns3.NodeContainer(ns3.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 = ns3.BridgeNetDevice() switchNode.AddDevice(bridgeDevice) for portIter in range(switchDevices.GetN()): bridgeDevice.AddBridgePort(switchDevices.Get(portIter)) # Add internet stack to the terminals internet = ns3.InternetStackHelper() internet.Install(terminals) # We've got the "hardware" in place. Now we need to add IP addresses. # #print "Assign IP Addresses." ipv4 = ns3.Ipv4AddressHelper() ipv4.SetBase(ns3.Ipv4Address("10.1.1.0"), ns3.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 = ns3.OnOffHelper( "ns3::UdpSocketFactory", ns3.Address(ns3.InetSocketAddress(ns3.Ipv4Address("10.1.1.2"), port))) onoff.SetAttribute("OnTime", ns3.RandomVariableValue(ns3.ConstantVariable(1))) onoff.SetAttribute("OffTime", ns3.RandomVariableValue(ns3.ConstantVariable(0))) app = onoff.Install(ns3.NodeContainer(terminals.Get(0))) # Start the application app.Start(ns3.Seconds(1.0)) app.Stop(ns3.Seconds(10.0)) # Create an optional packet sink to receive these packets sink = ns3.PacketSinkHelper( "ns3::UdpSocketFactory", ns3.Address(ns3.InetSocketAddress(ns3.Ipv4Address.GetAny(), port))) app = sink.Install(ns3.NodeContainer(terminals.Get(1))) app.Start(ns3.Seconds(0.0)) # # Create a similar flow from n3 to n0, starting at time 1.1 seconds # onoff.SetAttribute( "Remote", ns3.AddressValue( ns3.InetSocketAddress(ns3.Ipv4Address("10.1.1.1"), port))) app = onoff.Install(ns3.NodeContainer(terminals.Get(3))) app.Start(ns3.Seconds(1.1)) app.Stop(ns3.Seconds(10.0)) app = sink.Install(ns3.NodeContainer(terminals.Get(0))) app.Start(ns3.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 = ns3.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." ns3.Simulator.Run() ns3.Simulator.Destroy()
def main(argv): cmd = ns3.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 = ns3.WifiHelper.Default() wifiMac = ns3.NqosWifiMacHelper.Default() wifiPhy = ns3.YansWifiPhyHelper.Default() wifiChannel = ns3.YansWifiChannelHelper.Default() wifiPhy.SetChannel(wifiChannel.Create()) ssid = ns3.Ssid("wifi-default") wifi.SetRemoteStationManager("ns3::ArfWifiManager") wifiMac.SetType("ns3::AdhocWifiMac", "Ssid", ns3.SsidValue(ssid)) internet = ns3.InternetStackHelper() list_routing = ns3.Ipv4ListRoutingHelper() olsr_routing = ns3.OlsrHelper() static_routing = ns3.Ipv4StaticRoutingHelper() list_routing.Add(static_routing, 0) list_routing.Add(olsr_routing, 100) internet.SetRoutingHelper(list_routing) ipv4Addresses = ns3.Ipv4AddressHelper() ipv4Addresses.SetBase(ns3.Ipv4Address("10.0.0.0"), ns3.Ipv4Mask("255.255.255.0")) port = 9 # Discard port(RFC 863) onOffHelper = ns3.OnOffHelper( "ns3::UdpSocketFactory", ns3.Address(ns3.InetSocketAddress(ns3.Ipv4Address("10.0.0.1"), port))) onOffHelper.SetAttribute("DataRate", ns3.DataRateValue(ns3.DataRate("100kbps"))) onOffHelper.SetAttribute("OnTime", ns3.RandomVariableValue(ns3.ConstantVariable(1))) onOffHelper.SetAttribute("OffTime", ns3.RandomVariableValue(ns3.ConstantVariable(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 = ns3.Node() nodes.append(node) internet.Install(ns3.NodeContainer(node)) mobility = ns3.ConstantPositionMobilityModel() mobility.SetPosition(ns3.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", ns3.AddressValue(ns3.InetSocketAddress(destaddr, port))) app = onOffHelper.Install(ns3.NodeContainer(node)) app.Start(ns3.Seconds(ns3.UniformVariable(20, 30).GetValue())) #internet.EnablePcapAll("wifi-olsr") flowmon_helper = ns3.FlowMonitorHelper() #flowmon_helper.SetMonitorAttribute("StartTime", ns3.TimeValue(ns3.Seconds(31))) monitor = flowmon_helper.InstallAll() monitor.SetAttribute("DelayBinWidth", ns3.DoubleValue(0.001)) monitor.SetAttribute("JitterBinWidth", ns3.DoubleValue(0.001)) monitor.SetAttribute("PacketSizeBinWidth", ns3.DoubleValue(20)) ns3.Simulator.Stop(ns3.Seconds(44.0)) ns3.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): # # 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.")
positionAlloc = ns3.ListPositionAllocator() positionAlloc.Add(ns3.Vector(100, 100, 0.0)) positionAlloc.Add(ns3.Vector(100, 200, 0.0)) positionAlloc.Add(ns3.Vector(200, 200, 0.0)) mobility.SetPositionAllocator(positionAlloc) mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel") mobility.Install(nodes) port = 5000 #On off Application onoff = ns3.OnOffHelper( "ns3::UdpSocketFactory", ns3.Address(ns3.InetSocketAddress(ipcontainer.GetAddress(1), port))) onoff.SetAttribute("OnTime", ns3.RandomVariableValue(ns3.ConstantVariable(42))) onoff.SetAttribute("OffTime", ns3.RandomVariableValue(ns3.ConstantVariable(0))) #onoff.SetAttribute ("Remote", ns3.AddressValue (ns3.InetSocketAddress(ipcontainer.GetAddress(1),port))); apps = onoff.Install(nodes.Get(0)) apps.Start(ns3.Seconds(0.1)) apps.Stop(ns3.Seconds(90.0)) sink = ns3.PacketSinkHelper( "ns3::UdpSocketFactory", ns3.InetSocketAddress(ipcontainer.GetAddress(1), port)) appsink = sink.Install(nodes.Get(1)) appsink.Start(ns3.Seconds(0.5))