Topologías
Para esto se creo un script en python que genera código en python también que forman algúna topología común como estrella, anillo o árbol. Este es el código con algunas mejoras del que se realizo en laboratorio:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import sys | |
import random | |
def inicia_archivo(): | |
f = open("nuevo.py", "w") | |
f.write("import ns3\n") | |
f.write("def main(argv):\n") | |
f.write(" cmd = ns3.CommandLine()\n") | |
f.write(" cmd.Parse (argv)\n") | |
return f | |
def termina_archivo(f): | |
f.write("if __name__ == '__main__':\n") | |
f.write(" import sys\n") | |
f.write(" main(sys.argv)\n") | |
return f | |
def anillo(f, nodos): | |
#escribe los nodos | |
f.write("\n") | |
f.write(" #nodes\n") | |
for i in range(nodos): | |
f.write(" nodo_%s=ns3.NodeContainer()\n" %i) | |
f.write(" nodo_%s.Create(1)\n" %i) | |
#links | |
f.write("\n") | |
f.write(" #links\n") | |
for i in range(nodos): | |
f.write(" hub_%s = ns3.CsmaHelper()\n" %i) | |
f.write(" hub_%s.SetChannelAttribute(\"DataRate\", ns3.DataRateValue(ns3.DataRate(100000000)))\n" %i) | |
f.write(" hub_%s.SetChannelAttribute(\"Delay\", ns3.TimeValue(ns3.MilliSeconds(10000)))\n" %i) | |
#links | |
f.write("\n") | |
f.write(" #links\n") | |
for i in range(nodos-1): | |
if i != nodos-1: | |
f.write(" all_hub_%s = ns3.NodeContainer()\n" %i) | |
f.write(" all_hub_%s.Add (term_%s)\n" %(i,i)) | |
f.write(" all_hub_%s.Add (term_%s)\n" %(i,i+1)) | |
f.write(" ndc_hub_%s=hub_%s.Install(all_hub_%s)\n" %(i,i,i)) | |
else: | |
f.write(" all_hub_%s = ns3.NodeContainer()\n" %i) | |
f.write(" all_hub_%s.Add (term_%s)\n" %(i,i)) | |
f.write(" all_hub_%s.Add (term_%s)\n" %(i,0)) | |
f.write(" ndc_hub_%s=hub_%s.Install(all_hub_%s)\n" %(i,i,i)) | |
#ip stack | |
f.write("\n") | |
f.write(" #ip stack\n") | |
f.write(" internetStackH = ns3.InternetStackHelper()\n") | |
for i in range(nodos): | |
f.write(" internetStackH.Install(nodo_%s)\n" %i) | |
#ip | |
f.write("\n") | |
f.write(" #ip\n") | |
for i in range(nodos-1): | |
f.write(" ipv4.SetBase(ns3.Ipv4Address(\"10.0.%s.0\"), ns3.Ipv4Mask(\"255.255.255.0\"))\n"%i) | |
f.write(" iface_ndc_hub_%s = ipv4.Assign (ndc_hub_%s)\n" %(i,i)) | |
#generate route | |
f.write("\n") | |
f.write(" #generate route\n") | |
f.write(" ns3.Ipv4GlobalRoutingHelper.PopulateRoutingTables()\n") | |
#simulation | |
#aqui debe cada quien escribir la simulcion | |
f.write(" stopTime = 1\n") | |
f.write(" ns3.Simulator.Stop (ns3.Seconds(stopTime))\n") | |
#inicia la simulacion | |
f.write("\n") | |
f.write(" #inicial simulacion\n") | |
f.write(" ns3.Simulator.Run()\n") | |
f.write(" ns3.Simulator.Destroy()\n") | |
return f | |
def estrella(f, nodos): | |
#escribe los nodos | |
f.write("\n") | |
f.write(" #nodes\n") | |
for i in range(nodos): | |
f.write(" nodo_%s=ns3.NodeContainer()\n" %i) | |
f.write(" nodo_%s.Create(1)\n" %i) | |
#links | |
f.write("\n") | |
f.write(" #links\n") | |
for i in range(nodos-1): | |
f.write(" hub_%s = ns3.CsmaHelper()\n" %i) | |
f.write(" hub_%s.SetChannelAttribute(\"DataRate\", ns3.DataRateValue(ns3.DataRate(100000000)))\n" %i) | |
f.write(" hub_%s.SetChannelAttribute(\"Delay\", ns3.TimeValue(ns3.MilliSeconds(10000)))\n" %i) | |
#links | |
f.write("\n") | |
f.write(" #links\n") | |
for i in range(nodos-1): | |
if i != nodos-1: | |
f.write(" all_hub_%s = ns3.NodeContainer()\n" %i) | |
f.write(" all_hub_%s.Add (nodo_%s)\n" %(i,0)) | |
f.write(" all_hub_%s.Add (nodo_%s)\n" %(i,i+1)) | |
f.write(" ndc_hub_%s=hub_%s.Install(all_hub_%s)\n" %(i,i,i)) | |
else: | |
f.write(" all_hub_%s = ns3.NodeContainer()\n" %i) | |
f.write(" all_hub_%s.Add (nodo_%s)\n" %(i,0)) | |
f.write(" all_hub_%s.Add (nodo_%s)\n" %(i,i+1)) | |
f.write(" ndc_hub_%s=hub_%s.Install(all_hub_%s)\n" %(i,i,i)) | |
#ip stack | |
f.write("\n") | |
f.write(" #ip stack\n") | |
f.write(" internetStackH = ns3.InternetStackHelper()\n") | |
for i in range(nodos): | |
f.write(" internetStackH.Install(nodo_%s)\n" %i) | |
#ip | |
f.write("\n") | |
f.write(" #ip\n") | |
for i in range(nodos-1): | |
f.write(" ipv4.SetBase(ns3.Ipv4Address(\"10.0.%s.0\"), ns3.Ipv4Mask(\"255.255.255.0\"))\n"%i) | |
f.write(" iface_ndc_hub_%s = ipv4.Assign (ndc_hub_%s)\n" %(i,i)) | |
#generate route | |
f.write("\n") | |
f.write(" #generate route\n") | |
f.write(" ns3.Ipv4GlobalRoutingHelper.PopulateRoutingTables()\n") | |
#simulation | |
#aqui debe cada quien escribir la simulcion | |
f.write(" stopTime = 1\n") | |
f.write(" ns3.Simulator.Stop (ns3.Seconds(stopTime))\n") | |
#inicia la simulacion | |
f.write("\n") | |
f.write(" #inicial simulacion\n") | |
f.write(" ns3.Simulator.Run()\n") | |
f.write(" ns3.Simulator.Destroy()\n") | |
return f | |
def aleatoria(f, nodos): | |
#escribe los nodos | |
f.write("\n") | |
f.write(" #nodes\n") | |
for i in range(nodos): | |
f.write(" nodo_%s=ns3.NodeContainer()\n" %i) | |
f.write(" nodo_%s.Create(1)\n" %i) | |
#links | |
f.write("\n") | |
f.write(" #links\n") | |
for i in range(nodos-1): | |
f.write(" hub_%s = ns3.CsmaHelper()\n" %i) | |
f.write(" hub_%s.SetChannelAttribute(\"DataRate\", ns3.DataRateValue(ns3.DataRate(100000000)))\n" %i) | |
f.write(" hub_%s.SetChannelAttribute(\"Delay\", ns3.TimeValue(ns3.MilliSeconds(10000)))\n" %i) | |
#links | |
f.write("\n") | |
f.write(" #links\n") | |
for i in range(nodos-1): | |
if i != nodos-1: | |
f.write(" all_hub_%s = ns3.NodeContainer()\n" %i) | |
f.write(" all_hub_%s.Add (nodo_%s)\n" %(i,0)) | |
f.write(" all_hub_%s.Add (nodo_%s)\n" %(i,random.randint(0, nodos-1))) | |
f.write(" ndc_hub_%s=hub_%s.Install(all_hub_%s)\n" %(i,i,i)) | |
else: | |
f.write(" all_hub_%s = ns3.NodeContainer()\n" %i) | |
f.write(" all_hub_%s.Add (nodo_%s)\n" %(i,0)) | |
f.write(" all_hub_%s.Add (nodo_%s)\n" %(i,random.randint(0, nodos-1))) | |
f.write(" ndc_hub_%s=hub_%s.Install(all_hub_%s)\n" %(i,i,i)) | |
#ip stack | |
f.write("\n") | |
f.write(" #ip stack\n") | |
f.write(" internetStackH = ns3.InternetStackHelper()\n") | |
for i in range(nodos): | |
f.write(" internetStackH.Install(nodo_%s)\n" %i) | |
#ip | |
f.write("\n") | |
f.write(" #ip\n") | |
for i in range(nodos-1): | |
f.write(" ipv4.SetBase(ns3.Ipv4Address(\"10.0.%s.0\"), ns3.Ipv4Mask(\"255.255.255.0\"))\n"%i) | |
f.write(" iface_ndc_hub_%s = ipv4.Assign (ndc_hub_%s)\n" %(i,i)) | |
#generate route | |
f.write("\n") | |
f.write(" #generate route\n") | |
f.write(" ns3.Ipv4GlobalRoutingHelper.PopulateRoutingTables()\n") | |
#simulation | |
#aqui debe cada quien escribir la simulcion | |
f.write(" stopTime = 1\n") | |
f.write(" ns3.Simulator.Stop (ns3.Seconds(stopTime))\n") | |
#inicia la simulacion | |
f.write("\n") | |
f.write(" #inicial simulacion\n") | |
f.write(" ns3.Simulator.Run()\n") | |
f.write(" ns3.Simulator.Destroy()\n") | |
return f | |
def main(): | |
"""funcion principal | |
""" | |
try: | |
tipo = sys.argv[1] | |
nodos = sys.argv[2] | |
except: | |
print "Falta datos" | |
return | |
print tipo | |
print nodos | |
f = inicia_archivo() | |
if tipo == "anillo": | |
f = anillo(f,int(nodos)) | |
elif tipo == "estrella": | |
f = estrella(f, int(nodos)) | |
elif tipo == "aleatoria": | |
f = aleatoria(f, int(nodos)) | |
else: | |
pass | |
termina_archivo(f) | |
if __name__ == "__main__": | |
main() |
Tráfico
Esto se realizo con un archivo de texto que tenía algunos datos relevantes, los pasos a seguir son:
- Se implementa una subclase de la clase Application.
- Instanciar una o varios sockets dentro de esa aplicación.
- Iniciar la programación de eventos cuando se llama StartApplication.
- Parar la programación de eventos cuando StopApplication es llamada.
- Se crean paquetes y se envían en cada evento.
El código y su archivo de entrada.
El archivo de entrada contiene varios renglones y cada uno contiene la información de un envío en el siguiente orden:
nodo_inicio, nodo_final, tiempo_inicio, tiempo_termino, ip, data_rate
Código:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ns.applications | |
import ns.bridge | |
import ns.core | |
import ns.csma | |
import ns.internet | |
import ns.network | |
import ns.mobility | |
import ns.visualizer | |
import ns.flow_monitor | |
def main(argv): | |
cmd = ns.core.CommandLine() | |
cmd.NumNodesSide = True | |
cmd.AddValue("NumNodesSide", "Grid side number of nodes (total number of nodes will be this number squared)") | |
cmd.Results = "1" | |
cmd.AddValue("Results", "Write XML results to file") | |
cmd.Plot = True | |
cmd.AddValue("Plot", "Plot the results using the matplotlib python module") | |
cmd.Parse(argv) | |
print "Crea nodos" | |
terminals = ns.network.NodeContainer() | |
terminals.Create(5) | |
csmaSwitch = ns.network.NodeContainer() | |
csmaSwitch.Create(1) | |
csmaSwitch2 = ns.network.NodeContainer() | |
csmaSwitch2.Create(1) | |
print "Construye la topologia" | |
csma = ns.csma.CsmaHelper() | |
csma.SetChannelAttribute("DataRate", ns.network.DataRateValue(ns.network.DataRate(5000000))) | |
csma.SetChannelAttribute("Delay", ns.core.TimeValue(ns.core.MilliSeconds(2))) | |
# Crea los links de cada terminal al switch | |
terminalDevices = ns.network.NetDeviceContainer() | |
switchDevices = ns.network.NetDeviceContainer() | |
switchDevices2 = ns.network.NetDeviceContainer() | |
#se unen los cuatro nodos al primer switch | |
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)) | |
#se une un nodo al segundo switch | |
link = csma.Install(ns.network.NodeContainer(ns.network.NodeContainer(terminals.Get(2)), csmaSwitch2)) | |
terminalDevices.Add(link.Get(0)) | |
switchDevices2.Add(link.Get(1)) | |
link = csma.Install(ns.network.NodeContainer(ns.network.NodeContainer(terminals.Get(4)), csmaSwitch2)) | |
terminalDevices.Add(link.Get(0)) | |
switchDevices2.Add(link.Get(1)) | |
#se crean los puentes para enviar los paquetes | |
switchNode = csmaSwitch.Get(0) | |
bridgeDevice = ns.bridge.BridgeNetDevice() | |
switchNode.AddDevice(bridgeDevice) | |
switchNode2 = csmaSwitch2.Get(0) | |
bridgeDevice2 = ns.bridge.BridgeNetDevice() | |
switchNode2.AddDevice(bridgeDevice2) | |
for portIter in range(switchDevices.GetN()): | |
bridgeDevice.AddBridgePort(switchDevices.Get(portIter)) | |
for portIter in range(switchDevices2.GetN()): | |
bridgeDevice2.AddBridgePort(switchDevices2.Get(portIter)) | |
# se agrega el internet a las terminales | |
internet = ns.internet.InternetStackHelper() | |
internet.Install(terminals) | |
# Se agregan las direcciones iP | |
print "Se asignan direcciones IP" | |
ipv4 = ns.internet.Ipv4AddressHelper() | |
ipv4.SetBase(ns.network.Ipv4Address("10.1.1.0"), ns.network.Ipv4Mask("255.255.255.0")) | |
ipv4.Assign(terminalDevices) | |
#para dibujar los nodos | |
mobility = ns.mobility.ConstantPositionMobilityModel() | |
mobility.SetPosition(ns.core.Vector(95, 5, 0)) | |
terminals.Get(0).AggregateObject(mobility) | |
mobility = ns.mobility.ConstantPositionMobilityModel() | |
mobility.SetPosition(ns.core.Vector(120,35, 0)) | |
terminals.Get(1).AggregateObject(mobility) | |
mobility = ns.mobility.ConstantPositionMobilityModel() | |
mobility.SetPosition(ns.core.Vector(60,35, 0)) | |
terminals.Get(2).AggregateObject(mobility) | |
mobility = ns.mobility.ConstantPositionMobilityModel() | |
mobility.SetPosition(ns.core.Vector(100,65, 0)) | |
terminals.Get(3).AggregateObject(mobility) | |
mobility = ns.mobility.ConstantPositionMobilityModel() | |
mobility.SetPosition(ns.core.Vector(10,35, 0)) | |
terminals.Get(4).AggregateObject(mobility) | |
mobility1 = ns.mobility.ConstantPositionMobilityModel() | |
mobility1.SetPosition(ns.core.Vector(90,45, 0)) | |
csmaSwitch.Get(0).AggregateObject(mobility1) | |
mobility2 = ns.mobility.ConstantPositionMobilityModel() | |
mobility2.SetPosition(ns.core.Vector(40,40, 0)) | |
csmaSwitch2.Get(0).AggregateObject(mobility2) | |
# se crea una aplicacion para enviar paquetes UDP del nodo cero al nodo 1. | |
print "Create Applications." | |
port = 9 | |
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))) | |
# empieza la aplicacion | |
app.Start(ns.core.Seconds(1.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)) | |
#se lee el trafico del archivo de entrada simulando CBR como video o voz | |
traffic = [line.strip() for line in open("entrada.txt")] | |
for i in traffic: | |
caracteristicas = i.split(',') | |
nodo_inicial = int(caracteristicas[0]) | |
nodo_destino = int(caracteristicas[1]) | |
tiempo_inicio = float(caracteristicas[2]) | |
tiempo_final = float(caracteristicas[3]) | |
ip = ''+str(caracteristicas[4])+'' | |
data_rate = ''+(str(caracteristicas[5])+'kb/s').strip() | |
onoff.SetConstantRate(ns.network.DataRate(data_rate)) | |
onoff.SetAttribute("Remote", | |
ns.network.AddressValue(ns.network.InetSocketAddress(ns.network.Ipv4Address(ip), port))) | |
app = onoff.Install(ns.network.NodeContainer(terminals.Get(nodo_inicial))) | |
app.Start(ns.core.Seconds(tiempo_inicio)) | |
app = sink.Install(ns.network.NodeContainer(terminals.Get(nodo_destino))) | |
csma.EnablePcapAll("csma-bridge", False) | |
app.Stop(ns.core.Seconds(tiempo_final)) | |
flowmon_helper = ns.flow_monitor.FlowMonitorHelper() | |
monitor = flowmon_helper.InstallAll() | |
monitor = flowmon_helper.GetMonitor() | |
monitor.SetAttribute("DelayBinWidth", ns.core.DoubleValue(0.1)) | |
monitor.SetAttribute("JitterBinWidth", ns.core.DoubleValue(0.1)) | |
monitor.SetAttribute("PacketSizeBinWidth", ns.core.DoubleValue(20)) | |
print "Empieza la simulacion" | |
ns.core.Simulator.Run() | |
ns.core.Simulator.Destroy() | |
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) | |
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() | |
print "Finaliza" | |
if __name__ == '__main__': | |
import sys | |
main(sys.argv) |
Lo siguiente es comparar por lo menos dos diferentes esquemas de control de congestión (inventados por nosotros mismos, sin googlear ni por ideas ni código)
Las librerías que hay que importar para crear y modificar las tablas de ruteo son:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "ns3/global-router-interface.h" | |
#include "ns3/ipv4-static-routing.h" | |
#include "ns3/ipv4-global-routing.h" | |
#include "ns3/ipv4-list-routing.h" | |
#include "ns3/ipv4-routing-table-entry.h" | |
#include "ns3/ipv4-static-routing-helper.h" | |
#include "ns3/ipv4-list-routing-helper.h" | |
#include "ns3/ipv4-global-routing-helper.h" |
Este código base es lo más importante para los dos algoritmos de congestion que cree:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// se cran los nodos ruter y se inicializan las tablas de ruteo. | |
// tablas de ruteo nodo a y b | |
Ipv4GlobalRoutingHelper::PopulateRoutingTables (); | |
// se modifica la tabla... | |
Ptr<GlobalRouter> globalRouterB = nB->GetObject<GlobalRouter> (); | |
globalRouterB->InjectRoute ("10.1.1.4", "255.255.255.252"); | |
// se agrega el siguiente nodo | |
globalRouterB->InjectRoute ("192.168.1.1", "255.255.255.255"); | |
Ipv4GlobalRoutingHelper::RecomputeRoutingTables (); | |
//Además, nB necesita una ruta estática para que sepa qué hacer con las cosas | |
Ipv4StaticRoutingHelper ipv4RoutingHelper; | |
Ptr<Ipv4StaticRouting> staticRoutingB = ipv4RoutingHelper.GetStaticRouting (ipv4B); | |
staticRoutingB->AddHostRouteTo (Ipv4Address ("192.168.1.1"), Ipv4Address ("10.1.1.6"),2); |
El primer algoritmo que hice de congestión es muy simple, solamente toma un nodo al azar y es al que se le da preferencia de transferir o enviar datos y así hasta que todos los nodos han completado alguna acción.
El segundo algoritmo lo que hace es tomar el primero que esta en la lista que quiere enviar o recibir algún paquete y darle prioridad a el y una vez que lo hiso se saca de la lista y se va por el siguiente y así hasta terminar.
Código
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int | |
main (int argc, char *argv[]) | |
{ | |
Config::SetDefault ("ns3::Ipv4GlobalRouting::RespondToInterfaceEvents", BooleanValue (true)); | |
CommandLine cmd; | |
cmd.Parse (argc, argv); | |
NS_LOG_INFO ("Create nodes."); | |
NodeContainer c; | |
c.Create (7); | |
NodeContainer n0n2 = NodeContainer (c.Get (0), c.Get (2)); | |
NodeContainer n1n2 = NodeContainer (c.Get (1), c.Get (2)); | |
NodeContainer n5n6 = NodeContainer (c.Get (5), c.Get (6)); | |
NodeContainer n1n6 = NodeContainer (c.Get (1), c.Get (6)); | |
NodeContainer n2345 = NodeContainer (c.Get (2), c.Get (3), c.Get (4), c.Get (5)); | |
InternetStackHelper internet; | |
internet.Install (c); | |
// We create the channels first without any IP addressing information | |
NS_LOG_INFO ("Create channels."); | |
PointToPointHelper p2p; | |
p2p.SetDeviceAttribute ("DataRate", StringValue ("5Mbps")); | |
p2p.SetChannelAttribute ("Delay", StringValue ("2ms")); | |
NetDeviceContainer d0d2 = p2p.Install (n0n2); | |
NetDeviceContainer d1d6 = p2p.Install (n1n6); | |
NetDeviceContainer d1d2 = p2p.Install (n1n2); | |
p2p.SetDeviceAttribute ("DataRate", StringValue ("1500kbps")); | |
p2p.SetChannelAttribute ("Delay", StringValue ("10ms")); | |
NetDeviceContainer d5d6 = p2p.Install (n5n6); | |
//se crean los canales | |
CsmaHelper csma; | |
csma.SetChannelAttribute ("DataRate", StringValue ("5Mbps")); | |
csma.SetChannelAttribute ("Delay", StringValue ("2ms")); | |
NetDeviceContainer d2345 = csma.Install (n2345); | |
// Later, we add IP addresses. | |
NS_LOG_INFO ("Assign IP Addresses."); | |
Ipv4AddressHelper ipv4; | |
ipv4.SetBase ("10.1.1.0", "255.255.255.0"); | |
ipv4.Assign (d0d2); | |
ipv4.SetBase ("10.1.2.0", "255.255.255.0"); | |
ipv4.Assign (d1d2); | |
ipv4.SetBase ("10.1.3.0", "255.255.255.0"); | |
Ipv4InterfaceContainer i5i6 = ipv4.Assign (d5d6); | |
ipv4.SetBase ("10.250.1.0", "255.255.255.0"); | |
ipv4.Assign (d2345); | |
ipv4.SetBase ("172.16.1.0", "255.255.255.0"); | |
Ipv4InterfaceContainer i1i6 = ipv4.Assign (d1d6); | |
// tabla de ruteo | |
Ipv4GlobalRoutingHelper::PopulateRoutingTables (); | |
Ptr<GlobalRouter> globalRouterB = nB->GetObject<GlobalRouter> (); | |
globalRouterB->InjectRoute ("10.1.1.4", "255.255.255.252"); | |
globalRouterB->InjectRoute ("192.168.1.1", "255.255.255.255"); | |
// se crea una aplicacion para enviar datagramas | |
NS_LOG_INFO ("Create Applications."); | |
uint16_t port = 9; | |
OnOffHelper onoff ("ns3::UdpSocketFactory", | |
InetSocketAddress (i5i6.GetAddress (1), port)); | |
onoff.SetConstantRate (DataRate ("2kbps")); | |
onoff.SetAttribute ("PacketSize", UintegerValue (50)); | |
ApplicationContainer apps = onoff.Install (c.Get (1)); | |
apps.Start (Seconds (1.0)); | |
apps.Stop (Seconds (10.0)); | |
// se crea una aplicacion para enviar datagramas | |
OnOffHelper onoff2 ("ns3::UdpSocketFactory", | |
InetSocketAddress (i1i6.GetAddress (1), port)); | |
onoff2.SetAttribute ("OnTime", StringValue ("ns3::ConstantRandomVariable[Constant=1]")); | |
onoff2.SetAttribute ("OffTime", StringValue ("ns3::ConstantRandomVariable[Constant=0]")); | |
onoff2.SetAttribute ("DataRate", StringValue ("2kbps")); | |
onoff2.SetAttribute ("PacketSize", UintegerValue (50)); | |
ApplicationContainer apps2 = onoff2.Install (c.Get (1)); | |
apps2.Start (Seconds (11.0)); | |
apps2.Stop (Seconds (16.0)); | |
// recibir paquetes | |
PacketSinkHelper sink ("ns3::UdpSocketFactory", | |
Address (InetSocketAddress (Ipv4Address::GetAny (), port))); | |
apps = sink.Install (c.Get (6)); | |
apps.Start (Seconds (1.0)); | |
apps.Stop (Seconds (10.0)); | |
PacketSinkHelper sink2 ("ns3::UdpSocketFactory", | |
Address (InetSocketAddress (Ipv4Address::GetAny (), port))); | |
apps2 = sink2.Install (c.Get (6)); | |
apps2.Start (Seconds (11.0)); | |
apps2.Stop (Seconds (16.0)); | |
AsciiTraceHelper ascii; | |
Ptr<OutputStreamWrapper> stream = ascii.CreateFileStream ("dynamic-global-routing.tr"); | |
p2p.EnableAsciiAll (stream); | |
csma.EnableAsciiAll (stream); | |
internet.EnableAsciiIpv4All (stream); | |
p2p.EnablePcapAll ("dynamic-global-routing"); | |
csma.EnablePcapAll ("dynamic-global-routing", false); | |
Ptr<Node> n1 = c.Get (1); | |
Ptr<Ipv4> ipv41 = n1->GetObject<Ipv4> (); | |
// se da prioridad a los primeros | |
uint32_t ipv4ifIndex1 = 2; | |
Simulator::Schedule (Seconds (2),&Ipv4::SetDown,ipv41, ipv4ifIndex1); | |
Simulator::Schedule (Seconds (4),&Ipv4::SetUp,ipv41, ipv4ifIndex1); | |
Ptr<Node> n6 = c.Get (6); | |
Ptr<Ipv4> ipv46 = n6->GetObject<Ipv4> (); | |
// se da prioridad a los primeros | |
uint32_t ipv4ifIndex6 = 2; | |
Simulator::Schedule (Seconds (6),&Ipv4::SetDown,ipv46, ipv4ifIndex6); | |
Simulator::Schedule (Seconds (8),&Ipv4::SetUp,ipv46, ipv4ifIndex6); | |
Simulator::Schedule (Seconds (12),&Ipv4::SetDown,ipv41, ipv4ifIndex1); | |
Simulator::Schedule (Seconds (14),&Ipv4::SetUp,ipv41, ipv4ifIndex1); | |
// tablas de ruteo | |
Ipv4GlobalRoutingHelper g; | |
Ptr<OutputStreamWrapper> routingStream = Create<OutputStreamWrapper> ("dynamic-global-routing.routes", std::ios::out); | |
g.PrintRoutingTableAllAt (Seconds (12), routingStream); | |
NS_LOG_INFO ("Run Simulation."); | |
//Nos crea un archivo animation.xml con la informacion de la simulacion | |
AnimationInterface anim("animation.xml"); | |
//Se coloca el intervalo de tiempo de movimiento de la animacion | |
anim.SetMobilityPollInterval( Seconds( 1 ) ); | |
//Se habilita la animacion de intercambio de datos | |
anim.EnablePacketMetadata(true); | |
Simulator::Run (); | |
Simulator::Destroy (); | |
NS_LOG_INFO ("Done."); | |
} |
Vídeo Algoritmo 1:
Vídeo algoritmo 2:
Referencias
Ejemplos del paquete de ns3/src/routing
Injection
Me hubiera gustado algo de estadísticas comparativas, pero al parecer estabas muy ocupada con tu cumpleaños (¿y tu anillo nuevo de compromiso?); 8 pts.
ResponderEliminar