\documentclass{article}
 \usepackage{graphicx}
\usepackage{verbatim}
\usepackage{fullpage}


%\documentclass[12pt]{article}

\renewcommand{\baselinestretch}{1}
\pagestyle{empty}
\setlength{\textwidth}{16.5cm}
\setlength{\textheight}{22.5cm}
\setlength{\oddsidemargin}{0cm}

\setlength{\evensidemargin}{0cm}
\setlength{\topmargin}{-1cm}
\setlength{\footskip}{-1cm}

\newcounter{qcounter}
\setcounter{qcounter}{1}


%\newenvironment{question}{\QuadSpace\par\noindent{\bf Question}}{\HalfSpace}
\newenvironment{question}
{
     \begin{minipage}[s]{6.2in}
     \noindent{\bf Question \arabic{qcounter}:}
     \addtocounter{qcounter}{1}
}
{
     \end{minipage}
}

\newcommand\rr{{\it Route Reflector} }
\newenvironment{answer}
{
     \par\noindent
     \noindent{\bf Answer:}
}


\begin{comment}
\newenvironment{question}
{
     \HalfSpace\par\noindent
     \begin{minipage}[s]{6.2in}
     \noindent{\bf Question \arabic{qcounter}:} 
     \addtocounter{qcounter}{1}
}
{
     \end{minipage}\HalfSpace
}
\end{comment}


\newenvironment{code}
{\par\noindent}{}


 %  \newsavebox{\fmbox}
  % \newenvironment{fmpage}
   %  {\begin{lrbox}{\fmbox}\begin{minipage}{Question}}
    % {\end{minipage}\end{lrbox}\fbox{\usebox{\fmbox}}}






%\noindent
%\framebox[6.5in]{
%\begin{minipage}[s]{6.2in}
%\vspace{0.05in}
%{\bf Question 1:} Write a short piece of Tcl code to create a topology with 7 nodes
%connected in the form of a circle with 1Mbps/10ms duplex links with DropTail queues.
%\vspace{0.05in}
%\end{minipage}
%}\vspace{0.2in}



%\newcommand{\QuadSpace}{\vspace{0.25\baselineskip}}
%\newcommand{\HalfSpace}{\vspace{0.5\baselineskip}}
\begin{document}

\begin{center}
{\large{15-744: Computer Networking}}\\ \vspace{0.1in}
{\Large {Homework 2 - Network Simulator + TCP}} \\\vspace{0.1in}
{\bf Date Assigned : Oct 15, 2004} \\
{\bf Date Due : Oct 29, 2004 (in class)}
\end{center}



\section{Gearing Up ...}

ns is a network simulator that will be useful in homeworks, the class
project and in networks research in general.  


The purpose of this assignment is to teach you the basics of using ns
and to make you familiar with the {\em ns manual}
(http://www.isi.edu/nsnam/ns/ns-documentation.html).  You will also
learn how to develop new components for ns.


Here's what you need to do/know, before you start this assignment:
\begin{enumerate}
\item Download and Install ns \\
Download ns-allinone from the ns-2 homepage. This version
of ns contains all the components you need, including the Tcl interpreter.
We recommend using this ``build-it-all-at-once'' approach not only because
it is less hassle-free than to build ns from its constituent pieces;
but also because you might get different results or problems if you use 
a different version of ns or the Tcl interpreter.

Visit http://www.isi.edu/nsnam/ns/ns-build.html\#allinone for
instructions to install ns. Make sure you have enough disk space on
your machine: to build ns you will need around 250 Mb.  

\par A version of the ns-all-in-one package has been posted to the
course webpage, with install scripts modified, that should easily
compile on any facilitized cs machine.
\item Starting ns \\
After installation, you can start ns with the command `ns
$<$tclscript$>$' (assuming that you are in the directory with the ns
executable, or that your path points to that directory), where
`$<$tclscript$>$' is the name of a Tcl script file which defines the
simulation scenario (i.e. the topology and the events). This will be
more clear as you go along. You could also just start ns without any
arguments (ns will return a \% prompt on most systems) and enter the
Tcl commands in the Tcl shell but that is definitely less comfortable.

\item Understanding Otcl\\
To do this homework you need a basic understanding of Otcl.\\
http://www.isi.edu/nsnam/otcl/doc/tutorial.html gives a short introduction
to Otcl for C++ programmers, which you might want to read if you are not
familiar with Otcl.

\item Please hand in answers to the questions in boxes. In addition,
please hand in the following files as a printout together with the rest
of the assignment and send an electronic version by e-mail to
vyass@cs.cmu.edu :

5a.tcl, 5b.tcl, 6.tcl, ping.tcl.
%tcp-sj.c, and tcp-sj.h.

\end{enumerate}

\section{A brief overview of ns}

ns is an event-driven object-oriented simulator, written in C++, with an Otcl
interpreter as a front-end. This means that most of your simulation
scripts will be written in Tcl. If you want to develop new components for
ns you might have to use both Tcl and C++. 

ns uses two languages because any network simulator, in general, has
two different kinds of things it needs to do. On the one hand, detailed
simulations of protocols requires a systems programming language which
can efficiently manipulate bytes, packet headers, and implement
algorithms that run over large data sets. For these tasks run-time
speed is important and turn-around time (run simulation, find bug, fix
bug, recompile, re-run) is less important. On the other hand, a large
part of network research involves slightly varying parameters or
configurations, or quickly exploring a number of scenarios. In these
cases, iteration time (change the model and re-run) is more important. Since
configuration runs once (at the beginning of the simulation), run-time
of this part of the task is less important.

ns meets both of these needs with two languages, C++ and Otcl. C++ is
fast to run but slower to change, making it suitable for detailed
protocol implementation. Otcl runs much slower but can be changed very
quickly (and interactively), making it ideal for simulation
configuration. ns (via tclcl) provides glue to make objects and variables
{\bf appear on both languages}.

In the first part of this assignment, you will learn how to write simulation
scripts for ns. In the second part of the assignment, you will write new
components for ns to extend the functionality of ns.


\section{A simple example}

Figure~\ref{fig:simple} shows a simple example of an ns script.
Even without knowing ns you might be able to guess what the
script is doing: it creates two nodes and connects them with a link.
Then, 1 second after simulation begin it starts a constant-bit-rate
source on one of the nodes. The source stops after 4.5 seconds
and after 5 seconds the entire simulation is stopped.

In the next couple of sections we will examine the individual components
of a typical ns script like the one in Figure~\ref{fig:simple}.



\begin{figure}[htb]
\centering
\begin{minipage}{4in}
{\small
{\tt set ns [new Simulator]}

\noindent
{\tt set nf [open out.nam w]}\\
{\tt \$ns namtrace-all \$nf}\\

{\tt proc finish \{\} \{}\\
{\tt global ns nf}\\
{\tt \$ns flush-trace}\\
{\tt close \$nf}\\
{\tt exec nam out.nam \&}\\
{\tt exit 0}\\
{\tt }\}\\


{\tt set n0 [\$ns node]}\\
{\tt set n1 [\$ns node]}\\
{\tt \$ns duplex-link \$n0 \$n1 1Mb 10ms DropTail}\\


{\tt set udp0 [new Agent/UDP]}\\
{\tt \$ns attach-agent \$n0 \$udp0}\\
{\tt set null0 [new Agent/Null]}\\
{\tt \$ns attach-agent \$n1 \$null0}\\

{\tt set cbr0 [new Application/Traffic/CBR]}\\
{\tt \$cbr0 set packetSize\_ 500}\\
{\tt \$cbr0 set interval\_ 0.005}\\
{\tt \$cbr0 attach-agent \$udp0}\\

{\tt \$ns connect \$udp0 \$null0}\\


{\tt \$ns at 1.0 "\$cbr0 start"}\\
{\tt \$ns at 4.5 "\$cbr0 stop"}\\

{\tt \$ns at 5.0 "finish"}\\

{\tt \$ns run}\\
}
\end{minipage}
\caption{A simple sample script \label{fig:simple}}
\end{figure}

\section{How to start: A template for ns scripts}

In this section you are going to write a template that you can use 
for all  your simulation scripts.

A simulation in ns is described by a Tcl {\tt {class Simulator}}.
A simulation script, therefore, generally begins by creating an instance of
this class. This is done with the command \\

{\tt set ns [new Simulator]} \\

\noindent  

After creating the simulator object a simulation script usually calls various 
methods to create nodes and topologies. We will see in Section~\ref{s:topology}
how exactly this is done. Next we have to define what exactly we want to happen
in the simulation.
Since the ns simulator is an event-driven simulator this
is done by {\em scheduling events}:
when creating a simulator object a scheduler is created which runs by selecting
the next earliest event, executing  it to completion, and returning to execute
the next event.
An event can for example be the sending of data from one node to another node
or the failure of a link.
The command to schedule an event is \\

{\tt \$ns at <time in sec> <event>}\\


After scheduling all the events being scheduled 
we are ready to start the simulator:\\

{\tt \$ns run}\\


Although we have seen the basics of running a simulation we don't have
a way yet to get any output from the simulation. Fortunately, ns
provides a number of ways of collecting output or trace data on a
simulation as we will see in Section~\ref{s:tracing}.

The following code for example first opens the file `out.nam' for writing and gives it 
the file handle `f'.
It then tells the simulator to trace each individual packet on any link in
the topology and write the data into the file. \\


\noindent
{\tt set nf [open out.nam w]}\\
{\tt \$ns namtrace-all \$nf}\\

The trace data is collected in
a format that can later be used by the {\em nam} facility to visualize the
simulation in  an animation.

The only remaining step is to make sure that all the trace data is flushed into
the file at the end of the simulation and that the file is closed. 
Furthermore, we have to call the nam tool on the created trace file
to produce the animation. We do this by writing
a `finish' procedure that we call at the end of the simulation and that
performs all these tasks. 


\begin{verbatim}
proc finish {} {
        global ns nf
        $ns flush-trace
        close $nf
        exec nam out.nam &
        exit 0
}
\end{verbatim}


\noindent
The following line calls this procedure at the end of the simulation:\\

{\tt \$ns at 5.0 ``finish''}\\

\section{Creating a network topology \label{s:topology}}

Next let's look at how to create topologies in ns.

\subsection{Nodes and Links}

To create a node we can simply use the simulator method {\tt node}.
The following two lines create two nodes and assign them to the handles
`n0' and `n1'.\\

\noindent
{\tt set n0[\$ns node]}\\
{\tt set n1[\$ns node]}\\



\noindent
We can then either use the  simulator method {\tt simplex-link} or 
the method {\tt duplex-link} to connect the nodes with a link:\\

\noindent
{\tt \$ns simplex-link \$n0 \$n1 1Mb 10ms DropTail}\\
{\tt \$ns duplex-link \$n0 \$n1 1Mb 10ms DropTail}\\

\noindent
The first line creates a unidirectional link between n0 and n1 with
bandwidth 1Mbps, a propagation delay of 10ms and a DropTail queue.
The second line creates a bidirectional link with the same parameters.  

In addition to the DropTail queue, ns also supports many other queueing policies
like for example FairQueueing(FQ), Random Early Detection (RED), and Class-based queueing (CBQ). \\


%\noindent
%\framebox[6.5in]{
%\begin{question}What other queueing policies in addition to DropTail does ns support? Look up the ns documentation
%for an answer.
%\end{question}}\\[0.5cm]

\noindent
\framebox[6.5in]{

\begin{question}
What is the default maximum buffer size of the queue in a link?  Which
command can you use to limit the maximum buffer size of the queue in
the link between nodes n1 and n2 to 5 packets? (Hint: the variable to
look for is called limit\_)
\end{question}

}\\

\subsection{Creating larger topologies}

When creating larger topologies that have a regular structure it is
often more comfortable to use a Tcl loop instead of creating the nodes
one by one.  The following code creates seven nodes and stores them in
the array {\it n()}.

\begin{verbatim}
for {set i 0} {$i < 7} {incr i} {
    set n($i) [$ns node]
}
\end{verbatim}

\noindent
Note that arrays like other Tcl variables don't have to be declared first.\\

%\noindent
%\framebox[6.5in]{\begin{question}
%Write a short piece of Tcl code to create a topology with 7 nodes
%connected in the form of a circle with 1Mbps/10ms duplex links with DropTail queues.
%\end{question}
%}

The following questions asks you to write a procedure for creating
dumb-bell topologies like in Figure~\ref{f:dumbbell}.
The dumb-bell topology is used to study the effect of a bottle-neck link
shared by many sources. You will need it later in this homework
and also in the next assignment with ns.\\

\begin{figure}[htb]
\centering
\includegraphics[width=4in]{dumbbell}
\caption{{\em The dumb-bell topology}}
\label{f:dumbbell}
\end{figure}



\noindent
\framebox[6.5in]{

\begin{question}
Write a Tcl procedure that takes as an argument an integer $n$ and
creates a dumb-bell topology with $n$ nodes on either side.  Make the
link between R1 and R2 a 5Mbps/10ms duplex links with a DropTail
queue. Make all the other links 100Mbps/10ms duplex links with
DropTail queues.

\end{question}

}\\[0.1in]

Instead of creating your own topologies by hand you can also use one
of the {\em topology generators} that {\em ns-allinone} comes with.
One of them is for example {\em itm} which is based on Georgia-Tech's
Internetwork Topology Models (GT-ITM).  {\em itm}.\\

%\noindent
%\framebox[6.5in]{
%\begin{question}
%Write scripts for {\em itm} to generate a graph with the following specifications:
%\begin{itemize}
%%\item A pure random graph on 50 nodes.  The probability of an edge
%%must be 0.2. The output file must be named: r50.gb. Obtain the
%%corresponding Tcl code for topology creation from the output of {\em itm}.
%\item 10 random transit-stub graphs of 50 nodes each. Each graph must have
%five stub domains per transit node, with no extra transit-stub
%or stub-stub edges.  There should  be two transit domains.  The
%transit domains must have (on average) four nodes, and an edge between each
%pair of nodes with probability 0.75.  Each stub domain most have (on
%average) ten nodes, and edge probability 0.5.  The graphs should be
%named ts50-[0-9].gb.
%
%\end{itemize}
%\end{question}
%}

\section{Creating network traffic \label{s:traffic}}

By now you have some scripts that create topologies but there
is not traffic yet! 
Traffic generation in ns is based on objects of two classes, the {\tt class Agent}
and the {\tt class Application}.

Agents represent endpoints where network-layer packets are constructed or
consumed. Every node in the network that needs to send or receive traffic has to have
an agent attached to it. 
These agents can be thought of as the implementation of the
transport protocol.

On top of an agent runs an application.
The application determines the kind 
of traffic source that is simulated (e.g. ftp or telnet). 
Therefore applications can be thought of as representing the 
application layer in an ns-simulation.

\subsection{Creating Agents}

Corresponding to the two transport protocols used in the Internet there
are also two types of agents in ns: UDP agents and TCP agents.

The following code shows an example for setting up a 
UDP agent on the nodes n0 and n1 from above.\\

\noindent
{\tt set udp0 [new Agent/UDP]}\\
{\tt \$ns attach-agent \$n0 \$udp0}\\

\noindent
{\tt set null0 [new Agent/Null]}\\
{\tt \$ns attach-agent \$n1 \$null0}\\

\noindent
{\tt ns connect udp0 null0}\\

This code first creates a UDP agent and attaches it to n0
using the {\tt attach-agent} procedure.
It then creates a Null agent which will act as a traffic sink
and attach it to n1.
Finally, the two agents are connected using the simulator method {\tt connect}.
In the next section the UDP agent will be used by an
application to send data. \\

\noindent
\framebox[6.5in]{
\begin{question} 
Read the ns manual to find out how to write similar code
to set up a {\em TCP} connection. Then use your procedure
from Question 3 to create a dumb-bell topology with
5 $S_i$-$D_i$ pairs.
Set up a TCP connection for each of the $S_i$-$D_i$
pairs.
For all connections use an object of type {\tt Agent/TCP}.
\end{question}
}

\vspace{0.2in}

\noindent
\framebox[6.5in]{
\begin{question}
The code you wrote in the previous question creates a TCP agent that
implements TCP Tahoe. Find out what other flavors of TCP are 
supported in ns.
\end{question}
}

\vspace{0.2in}


%\noindent
%\framebox[6.5in]{
%\begin{question}
%What features does a two-way TCP agent (i.e. an agent of the type 
%{\tt Agent/TCP/FullTcp}) support that a one-way TCP agent does not support?
%\end{question}
%}

\subsection{Creating Applications}

In the previous section we have set up the agents implementing the transport 
layer. 
We will now create applications that we attach
to the transport agents and that will actually generate traffic.
In ns there are two basic types of applications: {\em simulated applications} and
{\em traffic generators}. \\

%\subsubsection{Traffic generators}
{\em Traffic generators} generate On/Off traffic: during On-periods, packets
are generated at a constant burst rate and during Off-periods no
packets are generated. 
ns provides three different classes of traffic generators
which differ in how the lengths of the On and Off-periods are modeled:

\begin{enumerate}
\item A  traffic generator of the type {\tt Application/Traffic/Exponential} takes 
the length of the On and Off periods from an Exponential distribution.
\item A {\tt Application/Traffic/Pareto} source generates the lengths
of these periods from  a Pareto distribution.
\item Finally, the class 
{\tt Application/Traffic/CBR} has zero off periods and generates packets
at a constant bit rate.  
\end{enumerate}

The following code generates one traffic generator of each class.\\

\noindent
{\tt set exp [new Application/Traffic/Exponential]}\\
{\tt set par [new Application/Traffic/Pareto]}\\
{\tt set cbr0 [new Application/Traffic/CBR]}\\

See the ns-manual for how to configure these traffic generators.

All traffic generators run on top of a UDP agent.
Therefore, we have to attach a traffic generator to a
UDP agent before we can use it to send data.
The following example illustrates the use of the CBR traffic generator
that we created above.\\

\noindent
{\tt \$cbr0 set packetSize\_ 500}\\
{\tt \$cbr0 set interval\_ 0.005}\\
{\tt \$cbr0 attach-agent \$udp0}\\

\noindent
{\tt \$ns at 1.0 ``\$cbr start''}\\

%\subsubsection{Simulated Applications}
The {\em simulated applications} currently implemented in ns are
{\tt Application/FTP} and {\tt Application/Telnet}.
These try to simulate the corresponding  applications in the real world:
FTP and Telnet.
Like the  real  applications  the ns  applications
can run only on TCP. They therefore have to be attached to a TCP agent.\\

\noindent
\framebox[6.5in]{
\begin{question}
Create and attach an FTP application to each of the $S_i$ nodes
from Question 3 and connect each to the corresponding $D_i$ nodes.
Start the FTP sources at 4 sec and stop them at 8 sec.
Now change the code so that instead of explicitly stopping 
the FTP sources after 8 sec they stop after sending 10 packets.
Save the resulting scripts in files called 5a.tcl and 5b.tcl,
respectively.
\end{question}
}

\vspace{0.2in}

\noindent
\framebox[6.5in]{
\begin{question}
Instead of deterministically starting a source it is sometimes useful
to have a source start firing randomly. Change the code from the previous 
question so that the FTP sources start firing at random instants of time.
Stop the sources after 100 sec.
Save the script in a file called 6.tcl.
\end{question}
}

% \subsubsection{As an Aside: Trace Driven traffic generation}


\section{Tracing and Monitoring \label{s:tracing}}

So far, when we wanted to see what is happening in a simulation we have used 
nam to visualize the events. However, often we want more detailed
{\em trace data} on a simulation which then allows us to compute 
numbers like packet loss rates or  per-connection throughput.

The easiest way to do this is to 
use the simulator method {\tt trace-all} which
traces all the links in the topology:\\

\noindent
{\tt set f[open out.tr w]}\\
{\tt \$ns trace-all \$f}\\

When you  use {\tt trace-all} you also have to remember to change the 
{\tt finish} procedure to flush the 
trace and close the file (as we did previously for the nam tracing).

Sometimes we are only interested in the events at one particular queue 
and want to avoid the overhead that comes with tracing every single link
in the topology.
For this case ns provides us with the {\tt trace-queue} method.
In addition, Section 22 of the ns-manual describes many other ways of
collecting trace data.\\[0.1in]

\noindent
\framebox[6.5in]{
\begin{question}
Create a trace file for the simulation in the previous question.
Start the tracing 20 sec after simulation begin and report the loss
rate on each of the flows, and the number of packets sent, received
and dropped on each flow.
\end{question}
}\\[0.1 in]

Instead of tracing {\em events} it is often useful to trace C++ or Tcl {\em instance
variables}. Below is an example of setting up variable tracing in ns.\\


%%%%%{ \flushleft \vspace{-0.3in}

\noindent
{\tt \# \$tcp tracing its own variable cwnd\_ }\\
{\tt \$tcp trace cwnd\_ } \\

\noindent
{\tt \# the variable ssthresh\_ of \$tcp is traced by a generic \$tracer }\\
{\tt set tracer [new Trace/Var]} \\
{\tt {\$tcp trace ssthresh\_ \$tracer}} \\[0.4cm]
%}

\noindent
\framebox[6.5in]{
\begin{question}
Trace the {\tt cwnd\_} variable of an arbitrary flow in 6.tcl and
obtain a plot of the evolution of the congestion window with time.
\end{question}
}

\section{Routing and Network Dynamics \label{s:dynamic}}

ns implements three different routing strategies: static routing, session routing
and DV routing. 
Read the ns manual to understand the differences between the different
routing strategies.\\
You can specify which routing strategy you want to use through the
{\tt rtproto{}} method in the {\tt class Simulator}.
The following commands illustrate the use of the {\tt rtproto}
method.\\

\noindent
{\tt \$ns rttproto Static}\\
{\tt \$ns rttproto Session}\\
{\tt \$ns rttproto DV}\\


For making the simulation topology dynamic.
ns provides a  simulator method called {\tt rtmodel-at}
which allows you to take links down or bring them up again
at a specified time.\\

\noindent
{\tt \$ns rtmodel-at 1.0 down \$n(1) \$n(2)}\\
{\tt \$ns rtmodel-at 2.0 up \$n(1) \$n(2)}\\


Instead of scheduling manually when a link should go down or come up
again you can also use a {\em model} for network dynamics which is to be applied
to the nodes and links in the topology.
The following line gives an example for using an exponential (On/Off)
model for the failure of the link between nodes n(1) and n(2).\\

\noindent
 {\tt \$ns rtmodel Exponential 0.8 1.0 1.0 down \$n(1) \$n(2)}\\


Read Section 26 in the ns-manual for more details on failure models.\\

\noindent
\framebox[6.5in]{
\begin{question}
Create 3 nodes n1, n2, and n3. Connect n1 with n2, n1 with n3, and n3 with
n2.
Then create a CBR agent and attach
it to node 1. Connect this CBR agent to a sink on node 2. Have the CBR agent
start sending at 0.5s and have it stop at 4.5s. Do not specify a routing protocol.
At time 2.5 let the link between node 1 and 2 go down for a second.
What do you observe?
\end{question}
}


\vspace{0.2in}

\noindent
\framebox[6.5in]{
\begin{question}
What happens after the link fails and why? (Hint: what is the default
routing strategy?).
How can you modify the code to {\it route around} the  this `problem'.
\end{question}
}

%\vspace{0.2in
%}
%\noindent
%\framebox[6.5in]{
%\begin{question}
%Consult the ns manual to find out how to set link weights and how to
%use multipath routing.
%Then change the above code so that both path n1-n2-n ..and n1-n
%are used for the traffic from n0 to n2..
%\end{question}
%}




\section{Developing new components for ns}

ns supports a class hierarchy in
C++ (also called the compiled hierarchy in this document), and a
similar class hierarchy within the OTcl interpreter (also called the
interpreted hierarchy in this document).

The two hierarchies are closely related to each other; from the user's
perspective, there is a one-to-one correspondence between a class in
the interpreted hierarchy and one in the compiled hierarchy. 


The most important classes are the following.
\begin{itemize}

\item {\tt class TclObject:} \hspace{0.1in}
This class is the root of the hierarchy. 
Users create new 
Tcl Objects through the OTcl interpreter; these objects are instantiated within
the interpreter, and are closely mirrored by a corresponding object in
the compiled (C++) hierarchy. 
The class TclObject provides two methods that are very important for the
linkage between the compiled and the interpreted hierarchy: bind() and command().
bind() links variables between Otcl and C++ and command() links Otcl methods
to the corresponding C++ implementations.
Consider for example the following ns code:\\

\noindent
{\tt set tcp [new Agent/TCP]}\\
{\tt \$tcp set maxseq\_ 200}\\
{\tt \$tcp advance 10}\\

The linkage between maxseq\_ and the corresponding
C++ counterpart is achieved by the constructor of
the class TcpAgent calling bind() \\

{\tt bind("maxseq\_", \&maxseq\_); } \\

and the Tcl command advance is implemented in the
C++ class TcpAgent 
(which is derived from TclObject) using the command() method: 

\begin{verbatim}
int TcpAgent::command(int argc, const char*const* argv)
{
        if (argc == 3) {
                if (strcmp(argv[1], "advance") == 0) {
                  .....
                }
        }
}

\end{verbatim}

\item {\tt class TclClass:}\hspace{0.1in}
This class is used for creating and initializing TclObjects.
Its constructor constructs the interpreted class hierarchy to
mirror the compiled class hierarchy. Its method
create() instantiates new TclObjects. 
The following shows the corresponding code for the class
TcpClass.

\begin{verbatim}
static class TcpClass : public TclClass {
public:
        TcpClass() : TclClass("Agent/TCP") {}
        TclObject* create(int , const char*const*) {
                return (new TcpAgent());
        }
} class_tcp;

\end{verbatim}

\item {\tt class Tcl:}\hspace{0.1in}
The class Tcl provides C++ methods to access and communicate
with the Tcl interpreter.
In particular, it provides a method eval() that allows the C++
programmer to execute interpreter commands and it provides
the function result() to pass results from and to the interpreter.

\end{itemize}
\vspace{0.4cm}
\noindent
\framebox[6.5in]{
\begin{question}
Having two languages raises the question of which language should be
used when implementing a new component.
What is the advantage of doing it purely in Otcl space?
What is the advantage of doing it in C++ space?
\end{question}}\vspace{0.15in}

In the following you will learn how to implement new ns components
purely in Otcl. In a later homework you will also implement
new components as split-objects in C++.

\subsection{Making changes to ns in otcl space}

The following are the steps to implement a new component purely in
otcl.

\begin{enumerate}
\item Create a directory mysrc in the directory
ns-allinone-2.27/ns-2.27/tcl.
\item Write the tcl implementation of the new component into the
file $<$new\_stuff$>$.tcl in the mysrc directory you just created.
\item You now have to recompile ns. Before you do so you want to make
sure that the new $<$new\_stuff$>$.tcl is sourced when the recompiled
ns is started.  The way to do this is to add the following line in
~ns-2.27/tcl/lib/ns-lib.tcl


source tcl/mysrc/new\_stuff.tcl

 
to automatically get new\_stuff.tcl at startup. Then run ./install to
recompile ns.
\end{enumerate}

The goal of this section is to create a Tcl {\tt Class Sender} and
a {\tt Class Receiver} that implement a protocol similar to the ping protocol:

The sender sends in periodic intervals of 1 sec a packet to the receiver and expects for each
packet it sends an ack from the receiver.
On receipt of an ack it prints the number of the ack, the address of
the receiver and the time when the ack was received. 

When receiving a packet from the sender the receiver prints the sequence 
number of the packet, the time when the packet was received and
the address of the sender. It then sends back an ack to the sender.

Both the sender and the receiver will be derived from the Tcl superclass
{\tt Agent/Message}:

\noindent
{\tt Class Sender -superclass Agent/Message}\\
{\tt Class Receiver -superclass Agent/Message}\\

In the next question you will be asked to implement methods for these
classes so that the new agents can be used as shown in the following example:\\


\noindent
{\tt set sdr [new Sender]}\\
{\tt \$sdr set seq\_ 100}\\

\noindent
{\tt set rcvr [new Receiver]}\\

\noindent
{\tt \$ns attach-agent \$n(3) \$sdr}\\
{\tt \$ns attach-agent \$n(5) \$rcvr}\\

\noindent
{\tt \$ns connect \$sdr \$rcvr}\\
{\tt \$ns connect \$rcvr \$sdr}\\

\noindent
{\tt \$ns at 1 "\$sdr send-next"}\\


Depending on the particular implementation of the agents and the topology in
the simulation the output 
of this script should be something similar to the following:\\

\noindent
{\tt
Receiver gets seq 100 from 3 at time 1.1837500000000001\\
Sender gets ack 100 from 5 at time 1.3675000000000002\\
Receiver gets seq 101 from 3 at time 2.1837499999999994\\
Sender gets ack 101 from 5 at time 2.3674999999999988\\
Receiver gets seq 102 from 3 at time 3.184605553196151\\
Sender gets ack 102 from 5 at time 3.3683555531961504\\
...
}\\

\noindent
\framebox[6.5in]{
\begin{question}
Implement the following three methods so that the new Tcl classes 
{\tt Sender} and {\tt Receiver} can be used as specified above.\\

\noindent
{\tt Sender instproc send-next args \{ ....\}}\\
{\tt Sender instproc recv msg \{....\}} \\
{\tt Receiver instproc recv msg \{....\}}\\

Do the entire implementation in a file called ping.tcl.
Create a Sender and a Receiver and attach them to two nodes
that are directly connected by a
1Mbps/10ms duplex link with a DropTail queue. Set the seq\_ variable
to 100.
Start the sender 1 sec after simulation begin and
stop it 5 sec after simulation begin. What is
the output you get?
\end{question}
}\\[0.1in]

Some hints for the implementation:

Use instance variables {\tt seq\_} and {\tt agent\_addr\_}.
{\tt agent\_addr\_} is inherited from the superclass 
{\tt Agent/Message} and you don't have to worry about
it's initialization.
Also, use {\tt Agent/Message}'s instance method $\,\,$
{\tt send ``msg text''} to pass the  messages (containing the sequence
number etc.) from the sender to the receiver and vice versa. 

The above description might sound more complicated than it actually is: 
all three methods you are asked to implement should be only 4 or 5 lines of code.

\comment{
\subsection{Making changes to ns in C++ space}

In this section you will implement a new TCP protocol called
Tcp-jump-start or short JSTcp. 
Recall that Tcp implements congestion control by 
using a sliding window protocol. The size of the
window limits the amount of outstanding (i.e.
not acknowledged) data.
The window size is initially set to 1 packet and is gradually
increased if there are no losses, i.e. no congestion. 
You will now implement a more aggressive version of TCP
called JSTcp 
that starts with a wide-open transmission window at the beginning. 
Unlike the ping agents in the previous question
TCP-jump-start will be implemented as a split object in C++.

The following are the steps to create a new component as a split object.

\begin{enumerate}
\item Decide the position in the class hierarchy. 
\item Write new code in $<$new\_stuff$>$.\{cc,h\} files.
\item Change Makefile correspondingly.
\item {\tt make depend} and recompile.
\end{enumerate}

\noindent
\framebox[6.5in]{
\begin{question}
Create and fill in the following two classes to implement JSTcp:\\

{\tt class JSTCPAgent : public TcpAgent \{ ... \}}\\
{\tt static JSTcpClass : public TclClass \{ ...\}}\\

Use two files called tcp-js.h and tcp-js.c for your implementation.
\end{question}}\\[0.1in]

Some hints for the implementation: \\

The ns variable that keeps track of the congestion
window is cwnd\_.
Create a member variable {\tt int MAXWIN\_} and
use this to initialize the congestion window as follows:

Look at the code for TCP-Tahoe
in ns-allinone-2.27/ns-2.27/tcp.\{h,cc\} to 
see which method it uses to initialize the cwnd\_
variable. 
Then implement this method for the new 
JSTcp class such that it sets cwnd\_ to {\tt MAXWIN}.
Use the {\tt bind()} method in TclClass to make sure 
that {\tt  MAXWIN\_} can be set through the ns 
interpreter from Tcl scripts.\\

In addition to the methods mentioned in the previous 
paragraph, you will have to implement two methods
for the class {\tt JSTcpClass}, the constructor and
the method {\tt create}.\\

Make sure that you understand the role of the classes
{\tt class TcpObject} (which all other objects including 
TcpAgent are derived
from) and {\tt class TclClass}.
If necessary look into Chaper 3 of the ns-manual.\\

\noindent
\framebox[6.5in]{
\begin{question}
Repeat the experiment from Question 6 with the new JSTcp and
plot the evolution of the congestion window over time.
\end{question}}
}

\end{document}

