0% found this document useful (0 votes)
45 views8 pages

NS Lab Assignment - 6: Name: Darshan Singh

This document contains code for an NS-3 simulation that traces various TCP metrics like congestion window, slow start threshold, RTT, and RTO for different TCP variants over time. It sets up a simple network topology with sources, sinks and a gateway node. Various TCP parameters like buffer size, recovery algorithm, and error model are configured. Tracing callbacks are used to log metric values to output files as the simulation runs.

Uploaded by

Darshan Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views8 pages

NS Lab Assignment - 6: Name: Darshan Singh

This document contains code for an NS-3 simulation that traces various TCP metrics like congestion window, slow start threshold, RTT, and RTO for different TCP variants over time. It sets up a simple network topology with sources, sinks and a gateway node. Various TCP parameters like buffer size, recovery algorithm, and error model are configured. Tracing callbacks are used to log metric values to output files as the simulation runs.

Uploaded by

Darshan Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

NS Lab Assignment – 6

Name: Darshan Singh RollNo:119CS0169

CODE
#include
<iostream>#include
<fstream>#include<str
ing>

#include "ns3/coremodule.h"#include
"ns3/networkmodule.h"#include"ns3/in
ternet-module.h" #include"ns3/point-
to-point-
module.h"#include
"ns3/applicationsmodule.h"#include"ns3/error-model.h"
#include
"ns3/tcpheader.h"#incl
ude
"ns3/udpheader.h"#incl
ude
"ns3/enum.h"#include"ns3/event
-id.h"
#include "ns3/flow-monitor-
helper.h"#include "ns3/ipv4-global-
routinghelper.h"#include"ns3/traffic-control-module.h"
usingnamespacens3;

NS_LOG_COMPONENT_DEFINE("TcpVariantsComparison");staticbo

olfirstCwnd=true; static
bool firstSshThr =
true;static bool firstRtt =
true;staticboolfirstRto=true; static
Ptr<OutputStreamWrapper> cWndStream;static
Ptr<OutputStreamWrapper>
ssThreshStream;static
Ptr<OutputStreamWrapper> rttStream;static
Ptr<OutputStreamWrapper> rtoStream;static
Ptr<OutputStreamWrapper> nextTxStream;static
Ptr<OutputStreamWrapper> nextRxStream;static
Ptr<OutputStreamWrapper>
inFlightStream;staticuint32_tcWndValue;
staticuint32_tssThreshValue;

staticvoid
CwndTracer(uint32_toldval,uint32_tnewval)
{
if(firstCwnd
)
{
*cWndStream->GetStream () << "0.0 " << oldval <<
std::endl;firstCwnd=false;
}
*cWndStream->GetStream () << Simulator::Now ().GetSeconds () << " " << newval <<
std::endl;cWndValue=newval;

if(!firstSshThr)
{
*ssThreshStream->GetStream () << Simulator::Now ().GetSeconds () << " " << ssThreshValue
<<std::endl;
}
}

staticvoid
SsThreshTracer(uint32_toldval,uint32_tnewval)
{
if(firstSshTh
r)
{
*ssThreshStream->GetStream () << "0.0 " << oldval <<
std::endl;firstSshThr=false;
}
*ssThreshStream->GetStream () << Simulator::Now ().GetSeconds () << " " << newval
<< std::endl;ssThreshValue=newval; if(!firstCwnd)
{
*cWndStream->GetStream()<<Simulator::Now().GetSeconds()<<""<<cWndValue<<std::endl;
}
}

staticvoid
RttTracer(Timeoldval,Timenewval)
{
if(firstRtt
)
{
*rttStream->GetStream () << "0.0 " << oldval.GetSeconds () <<
std::endl;firstRtt=false;
}
*rttStream->GetStream () << Simulator::Now ().GetSeconds () << " " << newval.GetSeconds ()
<<std::endl;
}

staticvoid
RtoTracer(Timeoldval,Timenewval)
{
if(firstRto
)
{
*rtoStream->GetStream () << "0.0 " << oldval.GetSeconds () <<
std::endl;firstRto=false;
}
*rtoStream->GetStream () << Simulator::Now ().GetSeconds () << " " << newval.GetSeconds ()
<<std::endl;
}

staticvoid
NextTxTracer(SequenceNumber32old,SequenceNumber32nextTx)
{
NS_UNUSED(old);
*nextTxStream->GetStream()<<Simulator::Now().GetSeconds()<<""<<nextTx<<std::endl;
}

staticvoid
InFlightTracer(uint32_told,uint32_tinFlight)
{
NS_UNUSED(old);
*inFlightStream->GetStream()<<Simulator::Now().GetSeconds()<<""<<inFlight<<std::endl;
}

staticvoid
NextRxTracer(SequenceNumber32old,SequenceNumber32nextRx)
{
NS_UNUSED(old);
*nextRxStream->GetStream()<<Simulator::Now().GetSeconds()<<""<<nextRx<<std::endl;
}

staticvoid
TraceCwnd(std::stringcwnd_tr_file_name)
{
AsciiTraceHelperascii;
cWndStream=ascii.CreateFileStream( c w n d _ t r _ f i l e _ n a m e . c _ s t r ( ) ) ; Config::C
onnectWithoutContext ("/NodeList/1/$ns3::TcpL4Protocol/SocketList/0/CongestionWindow",
MakeCallback(&CwndTracer));
}

staticvoid
TraceSsThresh(std::stringssthresh_tr_file_name)
{
AsciiTraceHelperascii;
ssThreshStream = ascii.CreateFileStream (ssthresh_tr_file_name.c_str
());Config::ConnectWithoutContext
("/NodeList/1/$ns3::TcpL4Protocol/SocketList/0/SlowStartThreshold",
MakeCallback(&SsThreshTracer));
}

staticvoid
TraceRtt(std::stringrtt_tr_file_name)
{
AsciiTraceHelperascii;
rttStream=ascii.CreateFileStream(rtt_tr_file_name.c_str());
Config::ConnectWithoutContext("/NodeList/1/$ns3::TcpL4Protocol/SocketList/0/RTT",
MakeCallback(&RttTracer));
}

staticvoid
TraceRto(std::stringrto_tr_file_name)
{
AsciiTraceHelperascii;
rtoStream=ascii.CreateFileStream(rto_tr_file_name.c_str());
Config::ConnectWithoutContext("/NodeList/1/$ns3::TcpL4Protocol/SocketList/0/RTO",
MakeCallback(&RtoTracer));
}

staticvoid
TraceNextTx(std::string&next_tx_seq_file_name)
{
AsciiTraceHelperascii; nextTxStream = ascii.CreateFileStream
(next_tx_seq_file_name.c_str
());Config::ConnectWithoutContext ("/NodeList/1/$ns3::TcpL4Protocol/SocketList/0/NextTxSequence",
MakeCallback(&NextTxTracer));
}

staticvoid
TraceInFlight(std::string&in_flight_file_name)
{
AsciiTraceHelperascii;
inFlightStream = ascii.CreateFileStream (in_flight_file_name.c_str
());Config::ConnectWithoutContext ("/NodeList/1/$ns3::TcpL4Protocol/SocketList/0/BytesInFlight",
MakeCallback(&InFlightTracer));
}

staticvoid
TraceNextRx(std::string&next_rx_seq_file_name)
{
AsciiTraceHelperascii;
nextRxStream=ascii.CreateFileStream(next_rx_seq_file_name.c_str());
Config::ConnectWithoutContext("/NodeList/2/$ns3::TcpL4Protocol/SocketList/1/RxBuffer/
NextRxSequence",MakeCallback(&NextRxTracer));
}

intmain(intargc,char*argv[])
{ std::string transport_prot =
"TcpHighSpeed";doubleerror_p=0.
0; std::string bandwidth =
"2Mbps";std::stringdelay="0.01ms";std::str
ing access_bandwidth =
"10Mbps";std::stringaccess_delay="45ms";
booltracing=true;
std::string prefix_file_name =
"TcpVariantsComparison";uint64_tdata_mbytes=0;
uint32_t mtu_bytes =
400;uint16_t num_flows = 1;double
duration =
100.0;uint32_trun=0;
bool flow_monitor =
false;boolpcap=true;
boolsack=true;
std::string queue_disc_type =
"ns3::PfifoFastQueueDisc";std::stringrecovery="ns3::TcpClassicR
ecovery";

CommandLinecmd;
cmd.AddValue ("transport_prot", "Transport protocol to use: TcpNewReno,
""TcpHybla,TcpHighSpeed,TcpHtcp,TcpVegas,TcpScalable,TcpVeno,"
"TcpBic, TcpYeah, TcpIllinois, TcpWestwood, TcpWestwoodPlus, TcpLedbat,
""TcpLp",transport_prot);
cmd.AddValue ("error_p", "Packet error rate",
error_p);cmd.AddValue ("bandwidth", "Bottleneck bandwidth",
bandwidth);cmd.AddValue("delay","Bottleneckdelay",delay);
cmd.AddValue ("access_bandwidth", "Access link bandwidth",
access_bandwidth);cmd.AddValue
("access_delay","Accesslinkdelay",access_delay);cmd.AddValue("tracing","Flagtoenable
/disabletracing",tracing);
cmd.AddValue ("prefix_name", "Prefix of output trace file",
prefix_file_name);cmd.AddValue ("data", "Number of Megabytes of data to transmit",
data_mbytes);cmd.AddValue ("mtu", "Size of IP packets to send in bytes",
mtu_bytes);cmd.AddValue("num_flows","Numberofflows",num_flows);
cmd.AddValue ("duration", "Time to allow flows to run in seconds",
duration);cmd.AddValue ("run", "Run index (for setting repeatable seeds)", run);cmd.AddValue
("flow_monitor", "Enable flow monitor",
flow_monitor);cmd.AddValue("pcap_tracing","EnableordisablePCAPtracing",pcap);
cmd.AddValue ("queue_disc_type", "Queue disc type for gateway (e.g.
ns3::CoDelQueueDisc)",queue_disc_type);
cmd.AddValue("sack","EnableordisableSACKoption",sack);
cmd.AddValue("recovery","Recoveryalgorithmtypetouse(e.g.,ns3::TcpPrrRecovery",recovery);

cmd.Parse(argc,argv); transport_prot = std::string ("ns3::") +

transport_prot;SeedManager::SetSeed(1);
SeedManager::SetRun(run);

//Usermayfinditconvenienttoenablelogging
//LogComponentEnable("TcpVariantsComparison",LOG_LEVEL_ALL);
//LogComponentEnable("BulkSendApplication",LOG_LEVEL_INFO);
//LogComponentEnable("PfifoFastQueueDisc",LOG_LEVEL_ALL);

//CalculatetheADUsize
Header*temp_header=newIpv4Header(); uint32_t
ip_header = temp_header->GetSerializedSize
();NS_LOG_LOGIC ("IP Header size is: " << ip_header);deletetemp_header;
temp_header=newTcpHeader();
uint32_t tcp_header = temp_header->GetSerializedSize
();NS_LOG_LOGIC ("TCP Header size is: " <<
tcp_header);deletetemp_header; uint32_t tcp_adu_size =
mtu_bytes - 20 - (ip_header +
tcp_header);NS_LOG_LOGIC("TCPADUsizeis:"<<tcp_adu_size);

// Set the simulation start and stop


timedoublestart_time=0.1;
doublestop_time=start_time+duration;

//4MBofTCPbuffer
Config::SetDefault("ns3::TcpSocket::RcvBufSize",UintegerValue(1<<21));
Config::SetDefault ("ns3::TcpSocket::SndBufSize", UintegerValue (1 <<
21));Config::SetDefault("ns3::TcpSocketBase::Sack",BooleanValue(sack));

Config::SetDefault ("ns3::TcpL4Protocol::RecoveryType",
TypeIdValue(TypeId::LookupByName(recovery)));
//SelectTCPvariant
if(transport_prot.compare("ns3::TcpWestwoodPlus")==0)
{
// TcpWestwoodPlus is not an actual TypeId name; we need TcpWestwood
hereConfig::SetDefault("ns3::TcpL4Protocol::SocketType",TypeIdValue(TcpWestwood::GetTypeId
()));
//thedefaultprotocoltypeinns3::TcpWestwoodisWESTWOOD
Config::SetDefault("ns3::TcpWestwood::ProtocolType",EnumValue(TcpWestwood::WESTWOODPLUS));
}
else
{
TypeIdtcpTid;
NS_ABORT_MSG_UNLESS (TypeId::LookupByNameFailSafe (transport_prot, &tcpTid), "TypeId "
<<transport_prot<<"notfound");
Config::SetDefault ("ns3::TcpL4Protocol::SocketType", TypeIdValue
(TypeId::LookupByName(transport_prot)));
}

// Create gateways, sources, and


sinksNodeContainergateways;gateways.Create(
1);
NodeContainer sources;sources.Create
(num_flows);NodeContainer
sinks;sinks.Create(num_flows);

//Configuretheerrormodel
// Here we use RateErrorModel with packet error
ratePtr<UniformRandomVariable> uv = CreateObject<UniformRandomVariable>
();uv->SetStream(50);
RateErrorModel
error_model;error_model.SetRandomVariab
le(uv);
error_model.SetUnit(RateErrorModel::ERROR_UNIT_PACKET);error_model.Set
Rate(error_p);

PointToPointHelperUnReLink;
UnReLink.SetDeviceAttribute ("DataRate", StringValue
(bandwidth));UnReLink.SetChannelAttribute ("Delay", StringValue
(delay));UnReLink.SetDeviceAttribute("ReceiveErrorModel",PointerValue(&error_model));
InternetStackHelper
stack;stack.InstallAll();

TrafficControlHelpertchPfifo;
tchPfifo.SetRootQueueDisc("ns3::PfifoFastQueueDisc");

TrafficControlHelper
tchCoDel;tchCoDel.SetRootQueueDisc("ns3::CoDelQueueDisc");

Ipv4AddressHelperaddress;
address.SetBase("10.0.0.0","255.255.255.0");

//Configurethesourcesandsinksnetdevices
// and the channels between the sources/sinks and the
gatewaysPointToPointHelperLocalLink;
LocalLink.SetDeviceAttribute ("DataRate", StringValue
(access_bandwidth));LocalLink.SetChannelAttribute("Delay",StringValue(access_delay));

Ipv4InterfaceContainersink_interfaces;

DataRate access_b
(access_bandwidth);DataRatebottle_b(ban
dwi dth); Time access_d
(access_delay);Timebottle_d(delay
);

uint32_t size = static_cast<uint32_t>((std::min (access_b, bottle_b).GetBitRate () / 8)


*((access_d+bottle_d)*2).GetSeconds());

Config::SetDefault ("ns3::PfifoFastQueueDisc::MaxSize",
QueueSizeValue (QueueSize (QueueSizeUnit::PACKETS, size /
mtu_bytes)));Config::SetDefault("ns3::CoDelQueueDisc::MaxSize",
QueueSizeValue(QueueSize(QueueSizeUnit::BYTES,size)));

for(uint32_ti=0;i<num_flows;i++)
{
NetDeviceContainerdevices;
devices = LocalLink.Install (sources.Get (i), gateways.Get
(0));tchPfifo.Install(devices);
address.NewNetwork();
Ipv4InterfaceContainerinterfaces=address.Assign(devices);

devices = UnReLink.Install (gateways.Get (0), sinks.Get


(i));if(queue_disc_type.compare("ns3::PfifoFastQueueDisc")==0)
{
tchPfifo.Install(devices
);
}
elseif(queue_disc_type.compare("ns3::CoDelQueueDisc")=
=0)
{
tchCoDel.Install(devices
);
}
else
{ NS_FATAL_ERROR ("Queue not recognized. Allowed values are
ns3::CoDelQueueDisc
orns3::PfifoFastQueueDisc");
} address.NewNetwork();
interfaces = address.Assign
(devices);sink_interfaces.Add(interfaces.Get(1)
); }

NS_LOG_INFO ("Initialize Global


Routing.");Ipv4GlobalRoutingHelper::PopulateRoutingTables
();

uint16_tport=50000;
Address sinkLocalAddress (InetSocketAddress (Ipv4Address::GetAny (),
port));PacketSinkHelpersinkHelper("ns3::TcpSocketFactory",sinkLocalAddress);

for(uint16_ti=0;i<sources.GetN();i++)
{
AddressValue remoteAddress (InetSocketAddress (sink_interfaces.GetAddress (i, 0),
port));Config::SetDefault ("ns3::TcpSocket::SegmentSize", UintegerValue
(tcp_adu_size));BulkSendHelperftp("ns3::TcpSocketFactory",Addres
s()); ftp.SetAttribute("Remote",remoteAddress); ftp.SetAttribute
("SendSize", UintegerValue
(tcp_adu_size));ftp.SetAttribute("MaxBytes",UintegerValue(data_mbytes*10000
0 0));
ApplicationContainer sourceApp = ftp.Install (sources.Get
(i));sourceApp.Start(Seconds(start_time*i));
sourceApp.Stop(Seconds(stop_time-3));

sinkHelper.SetAttribute ("Protocol", TypeIdValue (TcpSocketFactory::GetTypeId


()));ApplicationContainersinkApp=sinkHelper.Install(sinks.Get(i));
sinkApp.Start (Seconds (start_time *
i));sinkApp.Stop(Seconds(stop_time));
}

// Set up tracing if
enabledif(tracing)
{ std::ofstream
ascii;Ptr<OutputStreamWrapper>ascii_wr
ap;
ascii.open((prefix_file_name+"-ascii").c_str());
ascii_wrap=newOutputStreamWrapper((prefix_file_name+"-ascii").c_str(),
std::ios::out);
stack.EnableAsciiIpv4All(ascii_wrap);

Simulator::Schedule (Seconds (0.00001), &TraceCwnd, prefix_file_name + "-


cwnd.data");Simulator::Schedule (Seconds (0.00001), &TraceSsThresh, prefix_file_name +
"ssth.data");Simulator::Schedule (Seconds (0.00001), &TraceRtt, prefix_file_name +
"rtt.data");Simulator::Schedule (Seconds (0.00001), &TraceRto, prefix_file_name +
"rto.data");Simulator::Schedule (Seconds (0.00001), &TraceNextTx, prefix_file_name + "-
nexttx.data");Simulator::Schedule (Seconds (0.00001), &TraceInFlight, prefix_file_name +
"inflight.data");Simulator::Schedule(Seconds(0.1),&TraceNextRx,prefix_file_name+"-next-
rx.data"); }

if(pcap)
{
UnReLink.EnablePcapAll (prefix_file_name,
true);LocalLink.EnablePcapAll(prefix_file_name,true
); }

// Flow monitorFlowMonitorHelper
flowHelper;if(flow_monitor)
{
flowHelper.InstallAll()
;
}

Simulator::Stop (Seconds
(stop_time));Simulator::Run();

if(flow_monitor)
{
flowHelper.SerializeToXmlFile(prefix_file_name+".flowmonitor",true,tr
ue); }

Simulator::Destroy
();return0;
}

Output

You might also like