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): cmd = ns3.CommandLine() cmd.Parse(argv) # Create nodes print "Create nodes" n0 = ns3.Node() r = ns3.Node() n1 = ns3.Node() net1 = ns3.NodeContainer() net1.Add(n0) net1.Add(r) net2 = ns3.NodeContainer() net2.Add(r) net2.Add(n1) all = ns3.NodeContainer() all.Add(n0) all.Add(r) all.Add(n1) # Create IPv6 Internet Stack internetv6 = ns3.InternetStackHelper() internetv6.Install(all) # Create channels csma = ns3.CsmaHelper() csma.SetChannelAttribute("DataRate", ns3.DataRateValue(ns3.DataRate(5000000))) csma.SetChannelAttribute("Delay", ns3.TimeValue(ns3.MilliSeconds(2))) d1 = csma.Install(net1) d2 = csma.Install(net2) # Create networks and assign IPv6 Addresses print "Addressing" ipv6 = ns3.Ipv6AddressHelper() ipv6.NewNetwork(ns3.Ipv6Address("2001:1::"), ns3.Ipv6Prefix(64)) i1 = ipv6.Assign(d1) i1.SetRouter(1, True) ipv6.NewNetwork(ns3.Ipv6Address("2001:2::"), ns3.Ipv6Prefix(64)) i2 = ipv6.Assign(d2) i2.SetRouter(0, True) # Create a Ping6 application to send ICMPv6 echo request from n0 to n1 via r print "Application" packetSize = 1024 maxPacketCount = 5 interPacketInterval = ns3.Seconds(1.) ping6 = ns3.Ping6Helper() ping6.SetLocal(i1.GetAddress(0, 1)) ping6.SetRemote(i2.GetAddress(1, 1)) ping6.SetAttribute("MaxPackets", ns3.UintegerValue(maxPacketCount)) ping6.SetAttribute("Interval", ns3.TimeValue(interPacketInterval)) ping6.SetAttribute("PacketSize", ns3.UintegerValue(packetSize)) apps = ping6.Install(ns3.NodeContainer(net1.Get(0))) apps.Start(ns3.Seconds(2.0)) apps.Stop(ns3.Seconds(20.0)) print "Tracing" ascii = ns3.ofstream("simple-routing-ping6.tr") ns3.CsmaHelper.EnableAsciiAll(ascii) ns3.CsmaHelper.EnablePcapAll("simple-routing-ping6", True) # Run Simulation ns3.Simulator.Run() ns3.Simulator.Destroy()
def create_network(report): """Create a network Struct from a RadioMobile parsed text report.""" nodes = {} for name, attrs in report.units.iteritems(): node = Struct("Node", name=name, ns3_node=ns3.Node(), devices={}) nodes[name] = node ns3node_to_node = dict( (node.ns3_node.GetId(), node) for node in nodes.values()) # Internet stack stack = ns3.InternetStackHelper() for name, node in nodes.iteritems(): stack.Install(node.ns3_node) for net_index, (name, network) in enumerate(report.nets.iteritems()): node_members = radiomobile.get_units_for_network(network, "Node") if not node_members: continue node_member = node_members[0] terminal_members = radiomobile.get_units_for_network( network, "Terminal") ap_node = nodes[node_member].ns3_node sta_nodes = ns3.NodeContainer() debug("Add network '%s'\n ap_node = '%s'\n sta_nodes = %s" % (name, node_member, terminal_members)) for name in terminal_members: sta_nodes.Add(nodes[name].ns3_node) # Wifi channel channel = ns3.YansWifiChannelHelper.Default() phy = ns3.YansWifiPhyHelper.Default() phy.SetChannel(channel.Create()) # STA devices wifi = ns3.WifiHelper.Default() wifi.SetRemoteStationManager("ns3::AarfWifiManager") mac = ns3.NqosWifiMacHelper.Default() ssid = ns3.Ssid("ns-3-ssid") mac.SetType("ns3::NqstaWifiMac", "Ssid", ns3.SsidValue(ssid), "ActiveProbing", ns3.BooleanValue(False)) sta_devices = wifi.Install(phy, mac, sta_nodes) add_devices_to_node(network, ns3node_to_node, sta_nodes, sta_devices, phy) # AP devices mac = ns3.NqosWifiMacHelper.Default() mac.SetType("ns3::NqapWifiMac", "Ssid", ns3.SsidValue(ssid), "BeaconGeneration", ns3.BooleanValue(True), "BeaconInterval", ns3.TimeValue(ns3.Seconds(2.5))) ap_devices = wifi.Install(phy, mac, ap_node) add_devices_to_node(network, ns3node_to_node, ap_node, ap_devices, phy) # Set IP addresses address = ns3.Ipv4AddressHelper() netaddr = "10.1.%d.0" % net_index address.SetBase(ns3.Ipv4Address(netaddr), ns3.Ipv4Mask("255.255.255.0")) ap_interfaces = address.Assign(ap_devices) sta_interfaces = address.Assign(sta_devices) add_interfaces_to_device(network, ns3node_to_node, ap_node, ap_interfaces) add_interfaces_to_device(network, ns3node_to_node, sta_nodes, sta_interfaces) # Mobility mobility = ns3.MobilityHelper() mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel") mobility.Install(ap_node) mobility = ns3.MobilityHelper() mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel") mobility.Install(sta_nodes) ns3.Ipv4GlobalRoutingHelper.PopulateRoutingTables() return Struct("Network", nodes=nodes)
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 create_network(netinfo): """Create a network Struct from a RadioMobile parsed text report.""" nodes = {} for name, attrs in netinfo["units"].iteritems(): node = lib.Struct("Node", name=name, location=attrs["location"], ns3_node=ns3.Node(), devices={}) nodes[name] = node ns3node_to_node = dict( (node.ns3_node.GetId(), node) for node in nodes.values()) def get_node_from_ns3node(ns3_node): return ns3node_to_node[ns3_node.GetId()] # Internet stack stack = ns3.InternetStackHelper() for name, node in nodes.iteritems(): stack.Install(node.ns3_node) networks = {} for net_index, (net_name, network) in enumerate(netinfo["networks"].iteritems()): # Nodes node = network["node"] node_member = node["name"] terminal_members = [ terminal["name"] for terminal in network["terminals"] ] ap_node = nodes[node_member].ns3_node sta_nodes = ns3.NodeContainer() for name in terminal_members: sta_nodes.Add(nodes[name].ns3_node) networks[name] = lib.Struct("network", node=node_member, terminals=terminal_members) mode = network["mode"] network_info = dict( (d["name"], d) for d in [network["node"]] + network["terminals"]) # Configure WiFi or WiMax devices if mode["standard"].startswith("wifi"): wifi_network(network_info, net_index, net_name, mode["wifi_mode"], nodes, get_node_from_ns3node, node_member, terminal_members) elif mode["standard"].startswith("wimax"): scheduler = getattr( ns3.WimaxHelper, "SCHED_TYPE_" + mode["wimax_scheduler"].upper()) wimax_network(network_info, net_index, net_name, nodes, get_node_from_ns3node, node_member, terminal_members, scheduler) else: raise ValueError, ("Network name must be 'name [wifi_with_ns3_mode" + "| wimax-scheduler]': %s") % ns3_mode # Mobility mobility = ns3.MobilityHelper() mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel") for member in [node_member] + terminal_members: node = nodes[member] allocator = ns3.ListPositionAllocator() position = tuple(node.location) + (0, ) #position = (0, 0, 0) # debug allocator.Add(ns3.Vector(*position)) mobility.SetPositionAllocator(allocator) mobility.Install(node.ns3_node) ns3.Ipv4GlobalRoutingHelper.PopulateRoutingTables() return lib.Struct("Network", nodes=nodes, networks=networks)