def connect_tap_to_bridge(self, bridge_name=None): """Connect a ns-3 tap device to the bridge. Parameters ---------- bridge_name : str The bridge to connect the tap (and ns-3) device to. """ if bridge_name is None: bridge_name = self.bridge_name ipr = IPRoute() logger.debug('Connect %s to bridge %s via %s', self.node.name, bridge_name, self.tap_name) ipr.link('add', ifname=self.tap_name, kind='tuntap', mode='tap') defer(f'disconnect ns3 node {self.node.name}', self.disconnect_tap_from_bridge) ipr.link('set', ifname=self.tap_name, state='up') ipr.link('set', ifname=self.tap_name, master=ipr.link_lookup(ifname=bridge_name)[0]) logger.debug("Adding TapBridge for %s.", self.node.name) tap_helper = tap_bridge.TapBridgeHelper() # ConfigureLocal is used to prevent the TAP / bridged device to use a "learned" MAC address. # So, we can set the CSMA and WiFiNetDevice address to something we control. # Otherwise, WiFi ACK misses happen. tap_helper.SetAttribute('Mode', core.StringValue('ConfigureLocal')) tap_helper.SetAttribute('DeviceName', core.StringValue(self.tap_name)) tap_helper.SetAttribute('MacAddress', ns_net.Mac48AddressValue(ns_net.Mac48Address.Allocate())) tap_helper.Install(self.node.ns3_node, self.ns3_device)
def set_delay(self, delay): logger.info(f'Set delay of channel {self.channel_name} to {delay}') self.delay = delay if self.csma_channel is not None: core.Config.Set( "/ChannelList/" + str(self.csma_channel.GetId()) + "/$ns3::CsmaChannel/Delay", core.StringValue(str(self.delay)))
def __init__(self, network, nodes, delay="0ms", speed="100Mbps"): super().__init__(network, nodes) #: The channel's delay. self.delay = delay #: The channel's speed for transmitting and receiving. #: #: Valid values e.g. are :code:`'100Mbps'` or :code:`'64kbps'`. self.speed = speed #: A helper for connecting nodes via CSMA. self.csma_helper = csma.CsmaHelper() logger.info('Install connection between nodes') self.csma_helper.SetChannelAttribute("DataRate", core.StringValue(self.speed)) self.csma_helper.SetChannelAttribute("Delay", core.StringValue(self.delay)) #: All ns-3 devices on this channel. self.devices_container = self.csma_helper.Install( self.ns3_nodes_container) logger.info('Set IP addresses on nodes') stack_helper = internet.InternetStackHelper() for i, node in enumerate(nodes): ns3_device = self.devices_container.Get(i) address = None if node.wants_ip_stack(): if node.ns3_node.GetObject(internet.Ipv4.GetTypeId()) is None: logger.info('Installing IP stack on %s', node.name) stack_helper.Install(node.ns3_node) device_container = ns_net.NetDeviceContainer(ns3_device) ip_address = self.network.address_helper.Assign( device_container).GetAddress(0) netmask = network.network.prefixlen address = ipaddress.ip_interface(f'{ip_address}/{netmask}') interface = Interface(node=node, ns3_device=ns3_device, address=address) ns3_device.SetAddress(ns_net.Mac48Address(interface.mac_address)) node.add_interface(interface) self.interfaces.append(interface)
def set_data_rate(self, data_rate): logger.info(f'Set speed of channel {self.channel_name} to {data_rate}') self.data_rate = data_rate if self.csma_channel is not None: core.Config.Set( "/ChannelList/" + str(self.csma_channel.GetId()) + "/$ns3::CsmaChannel/DataRate", core.StringValue(self.data_rate))
def __init__(self, network, nodes, frequency=None, channel=1, channel_width=40, antennas=1, tx_power=20.0, standard: WiFiStandard = WiFiStandard.WIFI_802_11b, data_rate: WiFiDataRate = WiFiDataRate.DSSS_RATE_11Mbps): super().__init__(network, nodes) #: The channel to use. self.channel = channel #: The frequency to use. #: #: This could collide with other WiFi channels. self.frequency = frequency #: The width of the channel in MHz. self.channel_width = channel_width #: The number of antennas to use. self.antennas = antennas #: The sending power in dBm. self.tx_power = tx_power #: The WiFi standard to use. self.standard = standard #: The data rate to use. self.data_rate = data_rate logger.debug("Setting up physical layer of WiFi.") self.wifi_phy_helper = wifi.YansWifiPhyHelper.Default() self.wifi_phy_helper.Set("ChannelWidth", core.UintegerValue(self.channel_width)) if self.frequency: self.wifi_phy_helper.Set("Frequency", core.UintegerValue(self.frequency)) else: self.wifi_phy_helper.Set("ChannelNumber", core.UintegerValue(self.channel)) self.wifi_phy_helper.Set("Antennas", core.UintegerValue(self.antennas)) self.wifi_phy_helper.Set("MaxSupportedTxSpatialStreams", core.UintegerValue(self.antennas)) self.wifi_phy_helper.Set("MaxSupportedRxSpatialStreams", core.UintegerValue(self.antennas)) self.wifi_phy_helper.Set("TxPowerStart", core.DoubleValue(self.tx_power)) self.wifi_phy_helper.Set("TxPowerEnd", core.DoubleValue(self.tx_power)) # Enable monitoring of radio headers. self.wifi_phy_helper.SetPcapDataLinkType(wifi.WifiPhyHelper.DLT_IEEE802_11_RADIO) wifi_channel = wifi.YansWifiChannel() self.propagation_delay_model = propagation.ConstantSpeedPropagationDelayModel() wifi_channel.SetAttribute("PropagationDelayModel", core.PointerValue(self.propagation_delay_model)) if self.standard == WiFiChannel.WiFiStandard.WIFI_802_11p: # Loss Model, parameter values from Boockmeyer, A. (2020): # "Hatebefi: Hybrid Application Testbed for Fault Injection" loss_model = propagation.ThreeLogDistancePropagationLossModel() loss_model.SetAttribute("Distance0", core.DoubleValue(27.3)) loss_model.SetAttribute("Distance1", core.DoubleValue(68.4)) loss_model.SetAttribute("Distance2", core.DoubleValue(80.7)) loss_model.SetAttribute("Exponent0", core.DoubleValue(1.332671627050236)) loss_model.SetAttribute("Exponent1", core.DoubleValue(2.6812446718062612)) loss_model.SetAttribute("Exponent2", core.DoubleValue(3.5145944762444183)) loss_model.SetAttribute("ReferenceLoss", core.DoubleValue(83.54330702928374)) wifi_channel.SetAttribute("PropagationLossModel", core.PointerValue(loss_model)) else: loss_model = propagation.LogDistancePropagationLossModel() wifi_channel.SetAttribute("PropagationLossModel", core.PointerValue(loss_model)) self.wifi_phy_helper.SetChannel(wifi_channel) #: Helper for creating the WiFi channel. self.wifi = None #: All ns-3 devices on this channel. self.devices_container = None #: Helper for creating MAC layers. self.wifi_mac_helper = None if self.standard != WiFiChannel.WiFiStandard.WIFI_802_11p: self.wifi = wifi.WifiHelper() self.wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager", "DataMode", core.StringValue(self.data_rate.value), "ControlMode", core.StringValue(self.data_rate.value)) self.wifi.SetStandard(self.standard.value) self.wifi_mac_helper = wifi.WifiMacHelper() # Adhoc network between multiple nodes (no access point). self.wifi_mac_helper.SetType("ns3::AdhocWifiMac") else: self.wifi = wave.Wifi80211pHelper.Default() self.wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager", "DataMode", core.StringValue(self.data_rate.value), "ControlMode", core.StringValue(self.data_rate.value), "NonUnicastMode", core.StringValue(self.data_rate.value)) self.wifi_mac_helper = wave.NqosWaveMacHelper.Default() # Install on all connected nodes. logger.debug("Installing the WiFi channel to %d nodes. Mode is %s (data) / %s (control).", len(nodes), self.standard, self.data_rate) #: All ns-3 devices on this channel. self.devices_container = self.wifi.Install(self.wifi_phy_helper, self.wifi_mac_helper, self.ns3_nodes_container) logger.info('Setting IP addresses on nodes.') stack_helper = internet.InternetStackHelper() for i, node in enumerate(nodes): ns3_device = self.devices_container.Get(i) address = None if node.wants_ip_stack(): if node.ns3_node.GetObject(internet.Ipv4.GetTypeId()) is None: logger.info('Installing IP stack on %s', node.name) stack_helper.Install(node.ns3_node) device_container = ns_net.NetDeviceContainer(ns3_device) ip_address = self.network.address_helper.Assign(device_container).GetAddress(0) netmask = network.network.prefixlen address = ipaddress.ip_interface(f'{ip_address}/{netmask}') interface = Interface(node=node, ns3_device=ns3_device, address=address) ns3_device.GetMac().SetAddress(ns_net.Mac48Address(interface.mac_address)) node.add_interface(interface) self.interfaces.append(interface)
from datetime import datetime from ns import core, internet from pyroute2 import IPRoute import docker from .util import once from .context import defer from .workflow import Workflow from .visualization import Visualization, NoVisualization logger = logging.getLogger(__name__) # This needs to be set to real time, to let the containers speek. core.GlobalValue.Bind("SimulatorImplementationType", core.StringValue("ns3::RealtimeSimulatorImpl")) core.GlobalValue.Bind("ChecksumEnabled", core.BooleanValue(True)) # core.LogComponentEnableAll(core.LOG_LOGIC) # core.LogComponentEnable('TapBridge', core.LOG_DEBUG) # core.LogComponentEnable('TapBridge', core.LOG_WARN) # core.LogComponentEnable('MacLow', core.LOG_DEBUG) # core.LogComponentEnable('Txop', core.LOG_DEBUG) class Simulation: """ The simulation runs ns-3. The simulation is described by a :class:`.Scenario` which also prepares the simulation. It also takes care of preparing networks and nodes. **Do not initialize a simulation yourself.** Use the :class:`.Scenario` instead! Example
from ns import core, internet from pyroute2 import IPRoute import docker from .util import once from .context import defer from .workflow import Workflow from .visualization import Visualization, NoVisualization logger = logging.getLogger(__name__) # This needs to be set to real time, to let the containers speek. core.GlobalValue.Bind("SimulatorImplementationType", core.StringValue("ns3::RealtimeSimulatorImpl")) core.GlobalValue.Bind("ChecksumEnabled", core.BooleanValue(True)) # core.LogComponentEnableAll(core.LOG_LOGIC) # core.LogComponentEnable('TapBridge', core.LOG_DEBUG) # core.LogComponentEnable('TapBridge', core.LOG_WARN) # core.LogComponentEnable('MacLow', core.LOG_DEBUG) # core.LogComponentEnable('Txop', core.LOG_DEBUG) class Simulation: """ The simulation runs ns-3. The simulation is described by a :class:`.Scenario` which also prepares the simulation. It also takes care of preparing networks and nodes. **Do not initialize a simulation yourself.** Use the :class:`.Scenario` instead!
def main(li): p2pNodes = network.NodeContainer() p2pNodes.Create(2) pointToPoint = point_to_point.PointToPointHelper() pointToPoint.SetDeviceAttribute( "DataRate", core.StringValue(str(int(sum([i[0] for i in li]))) + "Mbps")) pointToPoint.SetChannelAttribute("Delay", core.StringValue("20ms")) p2pDevices = pointToPoint.Install(p2pNodes) csmaNodes = network.NodeContainer() csmaNodes.Add(p2pNodes.Get(1)) csmaNodes.Create(3) csma = ccc.CsmaHelper() csma.SetChannelAttribute("DataRate", core.StringValue("100Mbps")) csma.SetChannelAttribute("Delay", core.TimeValue(core.NanoSeconds(6560))) csmaDevices = csma.Install(csmaNodes) wifiStaNodes = network.NodeContainer() wifiStaNodes.Create(3) wifiApNode = p2pNodes.Get(0) channel = www.YansWifiChannelHelper.Default() phy = www.YansWifiPhyHelper.Default() phy.SetChannel(channel.Create()) wifi = www.WifiHelper() # wifi.SetRemoteStationManager("ns3::AarfWifiManager") wifi.SetRemoteStationManager("ns3::ConstantRateWifiManager", "DataMode", core.StringValue("OfdmRate54Mbps")) mac = www.WifiMacHelper() ssid = www.Ssid("ns-3-ssid") mac.SetType("ns3::StaWifiMac", "Ssid", www.SsidValue(ssid), "ActiveProbing", core.BooleanValue(False)) staDevices = wifi.Install(phy, mac, wifiStaNodes) mac.SetType("ns3::ApWifiMac", "Ssid", www.SsidValue(ssid)) apDevices = wifi.Install(phy, mac, wifiApNode) mobility = mob.MobilityHelper() mobility.SetPositionAllocator("ns3::GridPositionAllocator", "MinX", core.DoubleValue(0.0), "MinY", core.DoubleValue(0.0), "DeltaX", core.DoubleValue(5.0), "DeltaY", core.DoubleValue(10.0), "GridWidth", core.UintegerValue(3), "LayoutType", core.StringValue("RowFirst")) mobility.SetMobilityModel("ns3::ConstantPositionMobilityModel") mobility.Install(wifiApNode) mobility.Install(wifiStaNodes) stack = internet.InternetStackHelper() stack.Install(csmaNodes) stack.Install(wifiApNode) stack.Install(wifiStaNodes) address = internet.Ipv4AddressHelper() address.SetBase(network.Ipv4Address("10.1.1.0"), network.Ipv4Mask("255.255.255.0")) address.Assign(p2pDevices) address.SetBase(network.Ipv4Address("10.1.2.0"), network.Ipv4Mask("255.255.255.0")) address.Assign(csmaDevices) address.SetBase(network.Ipv4Address("10.1.3.0"), network.Ipv4Mask("255.255.255.0")) address.Assign(staDevices) address.Assign(apDevices) client = csmaNodes.Get(0) soc = network.Socket.CreateSocket(client, internet.UdpSocketFactory.GetTypeId()) pre = li[0] client.AddApplication(send(soc, pre[0], pre[1], False)) for i in range(1, 4): client = csmaNodes.Get(i) soc = network.Socket.CreateSocket( client, internet.UdpSocketFactory.GetTypeId()) pre = li[i] client.AddApplication(send(soc, pre[0], pre[1])) client = wifiStaNodes.Get(0) soc = network.Socket.CreateSocket(client, internet.UdpSocketFactory.GetTypeId()) client.AddApplication(recv(soc)) client = wifiStaNodes.Get(1) soc = network.Socket.CreateSocket(client, internet.UdpSocketFactory.GetTypeId()) client.AddApplication(recv(soc, False)) internet.Ipv4GlobalRoutingHelper.PopulateRoutingTables() core.Simulator.Stop(core.Seconds(3.0)) # pointToPoint.EnablePcapAll("third") # phy.EnablePcapAll("csma") # csma.EnablePcapAll("third", True) # stack.EnablePcapIpv4All('ics') core.Simulator.Run() core.Simulator.Destroy()
def __init__(self, network, nodes, frequency=None, channel=1, channel_width=40, antennas=1, tx_power=20.0, standard: WiFiStandard = WiFiStandard.WIFI_802_11a, data_rate: WiFiDataRate = WiFiDataRate.OFDM_RATE_6Mbps): super().__init__(network, nodes) #: The channel to use. self.channel = channel #: The frequency to use. #: #: This could collide with other WiFi channels. self.frequency = frequency #: The width of the channel in MHz. self.channel_width = channel_width #: The number of antennas to use. self.antennas = antennas #: The sending power in dBm. self.tx_power = tx_power #: The WiFi standard to use. self.standard = standard #: The data rate to use. self.data_rate = data_rate logger.debug("Setting up physical layer of WiFi.") self.wifi_phy_helper = wifi.YansWifiPhyHelper.Default() self.wifi_phy_helper.Set("ChannelWidth", core.UintegerValue(self.channel_width)) if self.frequency: self.wifi_phy_helper.Set("Frequency", core.UintegerValue(self.frequency)) else: self.wifi_phy_helper.Set("ChannelNumber", core.UintegerValue(self.channel)) self.wifi_phy_helper.Set("Antennas", core.UintegerValue(self.antennas)) self.wifi_phy_helper.Set("MaxSupportedTxSpatialStreams", core.UintegerValue(self.antennas)) self.wifi_phy_helper.Set("MaxSupportedRxSpatialStreams", core.UintegerValue(self.antennas)) self.wifi_phy_helper.Set("TxPowerStart", core.DoubleValue(self.tx_power)) self.wifi_phy_helper.Set("TxPowerEnd", core.DoubleValue(self.tx_power)) # Enable monitoring of radio headers. self.wifi_phy_helper.SetPcapDataLinkType( wifi.WifiPhyHelper.DLT_IEEE802_11_RADIO) wifi_channel_helper = wifi.YansWifiChannelHelper() wifi_channel_helper.SetPropagationDelay( "ns3::ConstantSpeedPropagationDelayModel") wifi_channel_helper.AddPropagationLoss( "ns3::LogDistancePropagationLossModel") # wifi_channel_helper.AddPropagationLoss("ns3::RangePropagationLossModel") self.wifi_phy_helper.SetChannel(wifi_channel_helper.Create()) #: Helper for creating the WiFi channel self.wifi = wifi.WifiHelper() self.wifi.SetRemoteStationManager( "ns3::ConstantRateWifiManager", "DataMode", core.StringValue(self.data_rate.value), "ControlMode", core.StringValue(self.data_rate.value)) self.wifi.SetStandard(self.standard.value) wifi_mac_helper = wifi.WifiMacHelper() # Adhoc network between multiple nodes (no access point). wifi_mac_helper.SetType("ns3::AdhocWifiMac") # Install on all connected nodes. logger.debug( "Installing the WiFi channel to %d nodes. Mode is %s (data) / %s (control).", len(nodes), self.standard, self.data_rate) #: All ns-3 devices on this channel. self.devices_container = self.wifi.Install(self.wifi_phy_helper, wifi_mac_helper, self.ns3_nodes_container) logger.info('Setting IP addresses on nodes.') stack_helper = internet.InternetStackHelper() for i, node in enumerate(nodes): ns3_device = self.devices_container.Get(i) address = None if node.wants_ip_stack(): if node.ns3_node.GetObject(internet.Ipv4.GetTypeId()) is None: logger.info('Installing IP stack on %s', node.name) stack_helper.Install(node.ns3_node) device_container = ns_net.NetDeviceContainer(ns3_device) ip_address = self.network.address_helper.Assign( device_container).GetAddress(0) netmask = network.network.prefixlen address = ipaddress.ip_interface(f'{ip_address}/{netmask}') interface = Interface(node=node, ns3_device=ns3_device, address=address) ns3_device.GetMac().SetAddress( ns_net.Mac48Address(interface.mac_address)) node.add_interface(interface) self.interfaces.append(interface)
def main(): # core.LogComponentEnable("UdpEchoClientApplication", core.LOG_LEVEL_INFO) wifihelper = wifi.WifiHelper.Default() wifihelper.SetStandard(wifi.WIFI_PHY_STANDARD_80211a) wifiphy = wifi.YansWifiPhyHelper.Default() wifichannel = wifi.YansWifiChannelHelper.Default() wifiphy.SetChannel(wifichannel.Create()) wifimac = wifi.WifiMacHelper() wifimac.SetType("ns3::AdhocWifiMac") wifihelper.SetRemoteStationManager("ns3::ConstantRateWifiManager", "DataMode", core.StringValue("OfdmRate54Mbps")) p2pmac = p2p.PointToPointHelper() p2pmac.SetChannelAttribute("Delay", core.TimeValue(core.NanoSeconds(6560))) p2pmac.SetDeviceAttribute("DataRate", core.StringValue("2Mbps")) stas = network.NodeContainer() stas.Create(3) p2ps = network.NodeContainer() p2ps.Create(1) mob = mobility.MobilityHelper() mob.Install(stas) stack = internet.InternetStackHelper() stack.Install(stas) stack.Install(p2ps) dev = wifihelper.Install(wifiphy, wifimac, stas) p2ps.Add(stas.Get(0)) dev2 = p2pmac.Install(p2ps) ip = internet.Ipv4AddressHelper() ip.SetBase(network.Ipv4Address('192.168.0.0'), network.Ipv4Mask('255.255.255.0')) ip.Assign(dev) ip.SetBase(network.Ipv4Address('192.168.1.0'), network.Ipv4Mask('255.255.255.0')) ip.Assign(dev2) client = p2ps.Get(0) client.AddApplication( aaa( network.Socket.CreateSocket(client, internet.UdpSocketFactory.GetTypeId()), 0)) for i in range(3): client = stas.Get(i) client.AddApplication( aaa( network.Socket.CreateSocket( client, internet.UdpSocketFactory.GetTypeId()), i)) internet.Ipv4GlobalRoutingHelper.PopulateRoutingTables() core.Simulator.Stop(core.Seconds(10.0)) wifiphy.EnablePcapAll('adhoc', True) stack.EnablePcapIpv4All('ipv4') core.Simulator.Run() core.Simulator.Destroy() sys.exit(0)