Anda di halaman 1dari 38

Index

S. No. Topic Date Teacher’s Sign

Write a program to demonstrate


1. communication between one client and one 6/9/2017
server.

Write a program to demonstrate


2. communication between one server and two 13/9/2017
client.

3. Introduction to OPNET Simulator 20/9/2017

Simulate Shared LAN and Switch LAN using


4. 27/9/2017
OPNET.

Simulate RIP with and without failure using


5. 18/10/2017
OPNET simulator.

6. Introduction to network simulator (ns-2). 25/10/2017

7. Installation and working of ns-2. 1/11/2017

Simulate three nodes point-to-point networks


with a duplex link between them. Set the
8. 8/11/2017
queue size and vary the bandwidth and find
the number of packets dropped.
1. Write a program to demonstrate communication
between one client and one server.
Server Program: Server.java
import java.io.*;
import java.net.*;
public class Server{
ServerSocket ss;
Socket s;
DataInputStream dis;
DataOutputStream dos;
public Server(){
try
{
System.out.println("Server Started");
ss=new ServerSocket(10);
s=ss.accept();
System.out.println(s);
System.out.println("Cliect Connected");
dis=new DataInputStream(s.getInputStream());
dos=new DataOutputStream(s.getOutputStream());
ServerChat();
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void main(String[] str){
new Server();
}
public void ServerChat() throws IOException{
String str, s1;
do{
str = dis.readUTF();
System.out.println("Client Message: "+str);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
s1=br.readLine();
dos.writeUTF(s1);
dos.flush();
}
while(!s1.equals("bye"));
}
}

Client Program: Client.java


import java.io.*;
import java.net.*;
public class Client{
Socket s;
DataInputStream dis;
DataOutputStream dout;
public Client(){
try
{
s=new Socket("localhost",10);
System.out.println(s);
dis=new DataInputStream(s.getInputStream());
dout=new DataOutputStream(s.getOutputStream());
ClientChat();
}
catch(Exception e)
{
System.out.println(e);
}
}
public static void main(String[] str){
new Client();
}
public void ClientChat() throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s1;
do{
s1=br.readLine();
dout.writeUTF(s1);
dout.flush();
System.out.println("Server Message: "+dis.readUTF());
}
while(!s1.equals("stop"));
}
}

Compiling programs:

Starting Server Application:

Starting Client Application:


Communication between Client and Server:
2. Write a program to demonstrate communication
between one server and two clients.
Server Program: NetworkServer.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class NetworkServer {
public static void main(String args[]){
Socket s=null;
ServerSocket ss2=null;
System.out.println("Server Listening......");
try{
ss2 = new ServerSocket(4445);
}
catch(IOException e){
e.printStackTrace();
System.out.println("Server error");
}
while(true){
try{
s= ss2.accept();
System.out.println("connection Established");
ServerThread st=new ServerThread(s);
st.start();
}
catch(Exception e){
e.printStackTrace();
System.out.println("Connection Error");
}
}
}
}
class ServerThread extends Thread{
String line=null;
BufferedReader is = null;
PrintWriter os=null;
Socket s=null;
public ServerThread(Socket s){
this.s=s;
}
public void run() {
try{
is= new BufferedReader(new InputStreamReader(s.getInputStream()));
os=new PrintWriter(s.getOutputStream());
}catch(IOException e){
System.out.println("IO error in server thread");
}
try {
line=is.readLine();
while(line.compareTo("QUIT")!=0){
os.println(line);
os.flush();
System.out.println("Response to Client : "+line);
line=is.readLine();
}
} catch (IOException e) {
line=this.getName(); //reused String line for getting thread name
System.out.println("IO Error/ Client "+line+" terminated abruptly");
}
catch(NullPointerException e){
line=this.getName(); //reused String line for getting thread name
System.out.println("Client "+line+" Closed");
}
finally{
try{
System.out.println("Connection Closing..");
if (is!=null){
is.close();
System.out.println(" Socket Input Stream Closed");
}
if(os!=null){
os.close();
System.out.println("Socket Out Closed");
}
if (s!=null){
s.close();
System.out.println("Socket Closed");
}
}
catch(IOException ie){
System.out.println("Socket Close Error");
}
}//end finally
}
}

Client Program: NetworkClient.java


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
public class NetworkClient {
public static void main(String args[]) throws IOException{
InetAddress address=InetAddress.getLocalHost();
Socket s1=null;
String line=null;
BufferedReader br=null;
BufferedReader is=null;
PrintWriter os=null;
try {
s1=new Socket(address, 4445); // You can use static final constant
PORT_NUM
br= new BufferedReader(new InputStreamReader(System.in));
is=new BufferedReader(new InputStreamReader(s1.getInputStream()));
os= new PrintWriter(s1.getOutputStream());
}
catch (IOException e){
e.printStackTrace();
System.err.print("IO Exception");
}
System.out.println("Client Address : "+address);
System.out.println("Enter Data to echo Server ( Enter QUIT to end):");
String response=null;
try{
line=br.readLine();
while(line.compareTo("QUIT")!=0){
os.println(line);
os.flush();
response=is.readLine();
System.out.println("Server Response : "+response);
line=br.readLine();
}
}
catch(IOException e){
e.printStackTrace();
System.out.println("Socket read Error");
}
finally{
is.close();os.close();br.close();s1.close();
System.out.println("Connection Closed");
}
}
}

Compiling Programs:

Starting Server Application:

Starting Client Thread-0:


Communication between Server and Client Thread-0:

Starting Client Thread-1:

Communication between Server and Client Thread-1:


Terminating the Client Threads:
3. Introduction to OPNET Simulator.
Network simulation is an important methodology in network research field and OPNET Modeler
is a very useful tool for network modeling and simulation. OPNET Modeler is generally used by
researchers, protocol designers, university teachers and students in the field of electronic
engineering, computer science, management information systems, and related disciplines. The
friendly design of its graphical user interface (GUI) makes it nice and easy to start with.

However, the complexity of OPNET Modeler and lack of useful support material make it
difficult for many users to fully make use of its benefits. The Modeler’s library offers more than
400 out-of-the-box protocols and vendor device models including IPv6, TCP/UDP, UMTS,
VoIP/Video/FTP/HTTP/Email, WiMAX, LTE, WLAN (a/b/g/n) and so on, to support accurate
event-driven simulation scenarios.

Wireless Design in OPNET


OPNET Modeler presents its capabilities in the form of distinct environments called editors.
Each editor allows users to set of related functions within a window that is contained in the
overall graphical environment. The main editors in OPNET are the following:

The project editor, which reflects the network domain, constitutes network topology and
configures nodes and links. The results of interest are chosen in the project domain and can be
viewed after running the simulation.

The node editor generates models of nodes by identifying internal structures and capabilities
of specific device of architecture.

The process editor develops models of decision-making processes representing protocols,


algorithms, resource managers, operating systems, and so on. The above-mentioned three editors
are the main components of the OPNET Modeler. Figure 1 shows the interaction between the
three editors' domains. There are other editors like link editor, path editor and other more shipped
with a software package. Besides the three main editors, simulation sequence editor is used to
design and run sequences of simulations, each potentially configured with different inputs and/or
outputs. Also, demand editor is used to create and edit traffic demand objects which represent IP
layer traffic.
OPNET Essential Skills
As a Guidance from OPNET modeler documentation and based on our experience with the
software, we provide this section as a quick start for new users. When creating a new network
model, a new project and scenario must be created first. A project is a group of related scenarios
that each explores different aspects of the network design. Projects can contain multiple
scenarios. Once project is created, the Startup Wizard is seen to set up a new scenario.

Creating a Project
 From the File menu, choose New.
 Select Project and click OK.
 Name the project <Project_Name> scenario <Scenario_Name>.
 Click OK.
 Click Next in the Startup Wizard.

Creating Scenario
In the scenario Wizard dialog, the following can be identified:

 Initial Topology
 Network Scale
 Specify Size
 Model Family
 Review Check

Creating Network Topologies


There are three ways to create network topologies as follow:

 Importing the topology.


 Placing each individual node from the object palette into the workspace.
 Creating a new network topology is by using the Rapid Configuration feature.

Creating Network Topologies Rapid Configuration Feature


Rapid Configuration allows selecting a network topology, the types of nodes within the network,
and the links connecting the nodes. To create the first floor network using Rapid Configuration:
From the Topology menu, choose the Rapid Configuration menu item. Select Star from the list of
available configurations, and then click OK.

Adding Components
Assuming that the general network topology has been constructed, it might be needed to add a a
new components, say a server. The second method of creating network objects can be used which
is dragging them from the object palette into the workspace.

 If it is not already open, open the object palette by clicking on the Object Palette action
button.
 Find the object in the palette and drag it into the workspace.
 If additional copies of this model is needed, right-click to turn off node creation.
 To link components, a link is drawn, connecting the two objects, then Right-click to turn
off link creation.

Editing Attributes
 The properties of objects can be changed such as hubs, switches, work station, eNodes,
UEs, etc. by editing the attributes.
 Right click on the object is desired to be edited.
 Choose Edit attributes.
Statistics
 There are two types of statistics:
o Statistics that are collected from individual nodes in a network (object statistics).
o Statistics that are collected for the entire network as a whole (global statistics).
 Global statistics are used to gather information about the network as a whole. They are
averaged values of the object statistics. For example, the delay for the entire network can
be found by collecting the global Delay statistic.
 User has to specify the statistics to be collected before simulation from DES Menu.

Run the Simulation


After you have specified the network, traffic, statistics to be collected and saved the project, you
are ready to run your simulation.

To run a simulation:

 For first time, you need to configure the simulation, duration, random seed and so on.
 From the DES Menu, choose Configure\run Discreet Event Simulation.
 Instead, you can press “Ctrl+R” in the Keyboard
 Type can specify the duration of simulation in the “Duration” box.
 Type can specify the random seed in the “Seed” box.
 Type can specify the Values per statistic (e.t., the resolution of the simulations, how often
it is collected) in the “Values per statistic” box.
 Once the simulation is configured, you want to run with the current configurations,
choose “Run Discreet Event Simulation” from DES Menu.
 Instead, you can press “shift+ Ctrl+R” in the keyboard.
 While the simulation is running, a window appears showing the simulation’s progress
(progress bar).
 Warning: do not try to interact with the simulator while simulation is running, it might
halt the simulation and cause loss of data since you have only one license.
 Only one simulation can run at the time per license.

View Results
 The results can be viewed after the simulation is finished
 To view existing results, go to DES Menu> Result> View Results
 Statistics (results) can be exported to spreadsheet files (excel files) and be organized
further for better presentation (MATLAB can be used) since OPNET modeler does not
offer a very flexible presentations of the results.

Debugging
 A good debugging tool is the Simulation Log. You can check for warnings and errors.
 Click on DES Menu> Result> Open Simulation Log.
 Live Debagging can be made for advanced user using the OPNET Simulation Debugger
(ODB) and should be set before running the simulation by checking the box in the
simulation configuration screen.
4. Simulate Shared LAN and Switch LAN using
OPNET.
Create a New Project
To create a new project for the Ethernet network:

1. Start OPNET IT Modeler Choose New from the File menu.


2. Select Project → Click OK → Name the project → SwitchedLAN, and the scenario
OnlyHub → Click OK.
3. In the Startup Wizard: Initial Topology dialog box, make sure that Create Empty Scenario
is selected → Click Next → Choose Office from the Network Scale list → Click Next three
times → Click OK.
4. Close the Object Palette dialog box.

Create the Network


To create our switched LAN:

1. To create the network configuration, select Topology → Rapid Configuration. From the
drop-down menu choose Star and click OK.
2. Click the Select Models button in the Rapid Configuration dialog box. From the Model List
drop-down menu choose ethernet and click OK.
3. In the Rapid Configuration dialog box, set the following five values Center Node Model =
ethernet16_hub, Periphery Node Model = ethernet_station, Link Model = 10BaseT,
Number=16, Y=50, and Radius = 42 → and click OK.

The prefix ethernet16_ indicates that the device supports up to 16 Ethernet connections.

The 10BaseT link represents an Ethernet connection operating at 10 Mbps.

1. Right-click on node_16, which is the hub Edit Attributes Change the name attribute to
Hub1 and click OK.
2. Now that you have created the network, it should look like the following one.
Make sure to save your project.

Here you will configure the traffic generated by the stations.

1. Right-click on any of the 16 stations (node_0 to node_15) → Select Similar Nodes. Now all
stations in the network are selected.
2. Right-click on any of the 16 stations → Edit Attributes.
A. Check the Apply Changes to Selected Objects check box. This is important to avoid
reconfiguring each node individually.
3. Expand the hierarchies of the Traffic Generation Parameters attribute and the Packet
Generation Arguments attribute → Set the following four values:

4. Click OK to close the attribute editing window(s). Save your project.

Choose Statistics
To choose the statistics to be collected during the simulation:
1. Right-click anywhere in the project workspace and select Choose Individual Statistics from
the pop-up menu.
2. In the Choose Results dialog box, choose the following four statistics:

The Ethernet Delay represents the end to end delay of all packets received by all the stations.

Traffic Received (in packets/sec) by the traffic sinks across all nodes.

Traffic Sent (in packets/sec) by the traffic sources across all nodes.

Collision Count is the total number of collisions encountered by the hub during packet
transmissions.

3. Click OK.

Configure the Simulation


Here we need to configure the duration of the simulation:

1. Click on the Configure/Run Simulation button:


2. Set the duration to be 2.0 minutes.
3. Click OK

Duplicate the Scenario


The network we just created utilizes only one hub to connect the 16 stations. We need to create
another network that utilizes a switch and see how this will affect the performance of the
network. To do that we will create a duplicate of the current network:
1. Select Duplicate Scenario from the Scenarios menu and give it the name HubAndSwitch →
Click OK.
2. Open the Object Palette by clicking on. Make sure that Ethernet is selected in the pull-
down menu on the object palette.
3. We need to place a hub and a switch in the new scenario. (They are circled in the following
figure.)
4. To add the Hub, click its icon in the object palette → Move your mouse to the workspace →
Click to drop the hub at a location you select. Right-click to indicate you are done deploying
hub objects.
5. Similarly, add the Switch.
6. Close the Object Palette.
7. Right-click on the new hub → Edit Attributes → Change the name attribute to Hub2 and
click OK.
8. Right-click on the switch → Edit Attributes → Change the name attribute to Switch and
click OK.
9. Reconfigure the network of the HubAndSwitch scenario so that it looks like the following
one.
10. To remove a link, select it and choose Cut from the Edit menu (or simply hit the Delete key).
You can select multiple links and delete all of them at once.
11. To add a new link, use the 10BaseT link available in the Object Palette.

12. Save your project.

Run the Simulation


To run the simulation for both scenarios simultaneously:

1. Select Manage Scenarios from the Scenarios menu.


2. Change the values under the Results column to <collect> (or <recollect>)for both scenarios.
Compare to the following figure.
3. Click OK to run the two simulations. Depending on the speed of your processor, this may
take several minutes to complete.
4. After the two simulation runs complete, one for each scenario, click Close.
5. Save your project.

View the Results


To view and analyze the results:

1. Select Compare Results from the Results menu.


2. Change the drop-down menu in the lower-right part of the Compare Results dialog box from
As Is to time_average, as shown. time_average is the average value over time of the values
generated during the collection window. This average is performed assuming a "sample-and-
hold" behavior of the data set (i.e., each value is weighted by the amount of time separating it
from the following update and the sum of all the weighted values is divided by the width of
the collection window). For example, suppose you have a 1-second bucket in which 10 values
have been generated. The first 7 values were generated between 0 and 0.3 seconds, the 8th
value at 0.4 seconds, the 9th value at 0.6 seconds, and the 10th at 0.99 seconds. Because the
last 3 values have higher durations, they are weighted more heavily in calculating the time
average.

3. Select the Traffic Sent (packets/sec) statistic and click Show. The resulting graph should
resemble the one below. As you can see, the traffic sent in both scenarios is almost identical.
4. Select the Traffic Received (packets/sec) statistic and click Show. The resulting graph
should resemble the one below. As you see, the traffic received with the second scenario,
HubAndSwitch, is higher than that of the OnlyHub scenario.

5. Select the Delay (sec) statistic and click Show. The resulting graph should resemble the one
below. (Note: Result may vary slightly due to different node placement.)
6. Select the Collision Count statistic for Hub1 and click Show.
7. On the resulting graph right-click anywhere on the graph area → Choose Add Statistic →
Expand the hierarchies as shown below Select the → Collision Count Statistic for Hub2 →
Change As Is to time_average → Click Add.
8. The resulting graph should resemble the one below.
5. Simulate RIP with and without failure using OPNET
Simulator.
No_Failure Scenario creation
1. Start OPNET IT Guru → Choose File → New from the file menu → Select Project and Click
OK
2. Enter the name of the project to be RIP_Test, and the scenario to be NO_Failure and Click
OK
3. In the Startup wizard:
Initial Topology Dialog box_ Create Empty Scenario is selected_ Click Next
Network Scale List _ Select Campus_ Click Next three times_ Click OK

Creating and Configuring the Network


1. Add two 100BaseT_LAN objects and one ethernet4_slip8_gtwy router to the project
workspace.
2. Connect the two LAN objects with the router using 100BaseT links.
3. You can do so by right-clicking on the object and selecting “Set Name”→ close the Object
Palette Dialog box → Save your Project.

The network should appear as below:

4. Right-click Router1_Edit Attributes _ Expand the “IP Routing Routers” hierarchy and set the
value of “Routing Table Export” to Once at the end of the simulation.

5. Make three more copies and make sure that your network look like this

 Use PPP_DS3 links to interconnect the router


Choosing the Statistics
1. Right-click on the project workspace and select “Choose Individual Statistics” then
 Global Statistics _RIP _Traffic Sent (bits/sec)
 Global Statistics _RIP _Traffic Received (bits/sec)
 Nodes Statistics _ Route Table _ Total Number ofUpdate
2. Click OK and then save your project.

Configuring the Simulation


1. Click on the run simulation icon _Configure Simulation window should appear _ Set the
duration of the simulation to be 10 minutes.
2. Click on the Global Attributes tab and change the following attributes as shown below:
i. IP Dynamic Routing Protocol = RIP
ii. IP Interface Addressing Mode = Auto Addressed / Export
iii. RIP Sim Efficiency = Disabled

{If the RIP Sim Efficiency is enabled, then RIP will stop after the “RIP Stop Time”. But, we
need RIP to keep updating the routing table in case there is any change in the network.}

Click Ok and then save the project.

In the network we just created, the routers will build their routing tables and then they will
notneed to update them further because we did not simulate any node or link failures.

Failure Scenario creation


In this scenario, we will simulate failures so that we can now compare the behavior of the
routersin both the cases.

1. Scenarios _Duplicate Scenario _ name it Failure_Click OK


2. Add a Failure Recovery object to the workspace, select utilities from the drop down menu
and name it Failure as shown below:

3. Right-click on the Failure object and select “Edit Attributes”


4. Expand the Link Failure/Recovery Specification hierarchy and set rows to 1. Set the
attributes of the added row as shown below:

Click Ok and then save the project_ Run Simulation for the duration of 10 minutes as before.

Now Let us compare the Result


A) Right click on the project workspace → Compare Results → Campus Network → Router1 →
Route Table → Total number of updates → Click Show → right-click and change “Draw
Style” to Bar
B) Capture the figure using PrntScrn.
C) Likewise, obtain figures for the total number of updates at all the other routers.
Result Analysis
In No failure scenario, it shows that routing table we created will build their routing table with no
update tables as there is no link failure therefore, the routing table is smooth as show in the above
part of the fig.

In Failure scenario, we created a link failure where more traffic is sent and set time is 200
seconds to fail the simulation (200 second equal to3minutes and 20 seconds). In result the RIP in
effected nodes send out an update of their routing table to place that failure.

For further data traffic and update, we find the IP address of the routers for OPNET interface.

Obtain the IP addresses of the interface


Before checking the contents of the routing tables, we need to determine the IP address
information for all interfaces in the current network. Recall that these IP addresses are assigned
automatically during simulation, and we set the global attribute IP Interface Addressing Mode to
export this information to a file.

1. Select the File menu. Choose Model Files → Refresh Model Directories.
2. From the File menu, choose Open.
3. Instead of “Project”, select “Generic Data File” from the pull-down menu.
4. Select the RIP_Test-No_Failure-ip_addresses (Note that the other file created from the
Failure scenario should also contain the same information). Click OK.
5. The following is a part of the gdf file. It shows the IP addresses assigned to all interfaces in
the network.
6. Introduction to network simulator (ns-2).
The network simulator is discrete event packet level simulator. The network simulator covers a
very large number of application of different kind of protocols of different network types
consisting of different network elements and traffic models. Network simulator is a package of
tools that simulates behavior of networks such as creating network topologies, log events that
happen under any load, analyze the events and understand the network. Well the main aim of our
first experiment is to learn how to use network simulator and to get acquainted with the simulated
objects and understand the operations of network simulation and we also need to analyze the
behavior of the simulation object using network simulation.

Platform required to run network simulator


 Unix and Unix like systems
 Linux (Use Fedora or Ubuntu versions)
 Free BSD
 SunOS/Solaris
 Windows 95/98/NT/2000/XP

Backend Environment of Network Simulator


Network Simulator is mainly based on two languages. They are C++ and OTcl. OTcl is the
object oriented version of Tool Command language. The network simulator is a bank of different
network and protocol objects. C++ helps in the following way:

 It helps to increase the efficiency of simulation.


 It is used to provide details of the protocols and their operation.
 It is used to reduce packet and event processing time.
 OTcl helps in the following way:
 With the help of OTcl we can describe different network topologies
 It helps us to specify the protocols and their applications
 It allows fast development
 Tcl is compatible with many platforms and it is flexible for integration
 Tcl is very easy to use and it is available in free

Basics of Tcl Programming (w.r.t. ns2)

Before we get into the program we should consider the following things:

 Initialization and termination aspects of network simulator.


 Defining the network nodes, links, queues and topology as well.
 Defining the agents and their applications
 Network Animator(NAM)
 Tracing
Initialization
To start a new simulator we write

set ns [new Simulator]

From the above command we get that a variable ns is being initialized by using the set command.
Here the code [new Simulator] is an instantiation of the class Simulator which uses the reserved
word 'new'. So we can call all the methods present inside the class simulator by using the variable
ns.

Creating the output files


1 #To create the trace files we write
2
3 set tracefile1 [open out.tr w]
4 $ns trace-all $tracefile1
5
6 #To create the nam files we write
7
8 set namfile1 [open out.nam w]
9 $ns namtrace-all $namfile

In the above, we create an output trace file out.tr and a nam visualization file out.nam. But in the
Tcl script they are not called by their names declared, while they are called by the pointers
initialized for them such as tracefile1 and namfile1 respectively. The line which starts with '#' are
commented. The next line opens the file 'out.tr' which is used for writing is declared 'w'. The next
line uses a simulator method trace-all by which we will trace all the events in a particular format.

The termination program is done by using a 'finish' procedure


01 # Defining the 'finish' procedure'
02
03 proc finish {} {
04 global ns tracefile1 namfile1
05 $ns flush-trace
06 close $tracefile
07 close $namfile
08 exec nam out.nam &
09 exit 0
10 }

In the above the word 'proc' is used to declare a procedure called 'finish’. The word 'global' is
used to tell what variables are being used outside the procedure.

'flush-trace' is a simulator method that dumps the traces on the respective files. The command
'close' is used to close the trace files and the command 'exec' is used to execute the nam
visualization. The command 'exit' closes the application and returns 0 as zero (0) is default for
clean exit.

In ns we end the program by calling the 'finish' procedure


1 #end the program
2 $ns at 125.0 "finish"

Thus the entire operation ends at 125 seconds.To begin the simulation we will use the command
1 #start the the simulation process
2 $ns run

Defining nodes, links, queues and topology


Way to create a node:
1 set n0 [ns node]

In the above we created a node that is pointed by a variable n0.While referring the node in the
script we use $n0. Similarly we create another node n2.Now we will set a link between the two
nodes.
1 $ns duplex-link $n0 $n2 10Mb 10ms DropTail

So we are creating a bi-directional link between n0 and n2 with a capacity of 10Mb/sec and a
propagation delay of 10ms.

In NS an output queue of a node is implemented as a part of a link whose input is that node to
handle the overflow at the queue. But if the buffer capacity of the output queue is exceeded then
the last packet arrived is dropped and here we will use a 'DropTail' option. Many other options
such as RED(Random Early Discard) mechanism, FQ(Fair Queuing), DRR(Deficit Round
Robin), SFQ(Stochastic Fair Queuing) are available.

So now we will define the buffer capacity of the queue related to the above link
1 #Set queue size of the link
2 $ns queue-limit $n0 $n2 20

So, if we summarize the above three things we get


01 #create nodes
02
03 set n0 [$ns node]
04 set n1 [$ns node]
05 set n2 [$ns node]
06 set n3 [$ns node]
07 set n4 [$ns node]
08 set n5 [$ns node]
09
10 #create links between the nodes
11
12 $ns duplex-link $n0 $n2 10Mb 10ms DropTail
13 $ns duplex-link $n1 $n2 10Mb 10ms DropTail
14 $ns simplex-link $n2 $n3 0.3Mb 100ms DropTail
15 $ns simplex-link $n3 $n2 0.3Mb 100ms DropTail
16 $ns duplex-link $n0 $n2 0.5Mb 40ms DropTail
17 $ns duplex-link $n0 $n2 0.5Mb 40ms DropTail
18
19 #set queue-size of the link (n2-n3) to 20
20 $ns queue-limit $n2 $n3 20

Agents and applications


TCP

TCP is a dynamic reliable congestion protocol which is used to provide reliable transport of
packets from one host to another host by sending acknowledgements on proper transfer or loss of
packets.Thus TCP requires bi-directional links in order for acknowledgements to return to the
source.

Now we will show how to set up tcp connection between two nodes
1 #setting a tcp connection
2
3 set tcp [new Agent/TCP]
4 $ns attach-agent $n0 $tcp
5 set sink [new Agent/TCPSink]
6 $ns attach-agent $n4 $sink
7 $ns connect $tcp $sink
8 $tcp set fid_1
9 $tcp set packetSize_552

The command 'set tcp [new Agent/TCP]' gives a pointer called 'tcp' which indicates the tcp agent
which is an object of ns. Then the command '$ns attach-agent $n0 $tcp' defines the source node
of tcp connection. Next the command 'set sink [new Agent/TCPSink]' defines the destination of
tcp by a pointer called sink. The next command '$ns attach-agent $n4 $sink' defines the
destination node as n4.Next, the command '$ns connect $tcp $sink' makes the TCP connection
between the source and the destination i.e. n0 and n4.When we have several flows such as TCP,
UDP etc. in a network. So, to identify these flows we mark these flows by using the command
'$tcp set fid_1'. In the last line we set the packet size of tcp as 552 while the default packet size of
tcp is 1000.

FTP over TCP

File Transfer Protocol (FTP) is a standard mechanism provided by the Internet for transferring
files from one host to another. Well this is the most common task expected from a networking or
a inter networking. FTP differs from other client server applications in that it establishes between
the client and the server. One connection is used for data transfer and other one is used for
providing control information. FTP uses the services of the TCP. It needs two connections. The
well Known port 21 is used for control connections and the other port 20 is used for data
transfer.

Well here we will learn in how to run a FTP connection over a TCP
1 #Initiating FTP over TCP
2
3 set ftp [new Application/FTP]
4 $ftp attach-agent $tcp
In above, the command 'set ftp [new Application/FTP]' gives a pointer called 'ftp' which indicates
the FTP application. Next, we attach the ftp application with tcp agent as FTP uses the services
of TCP.

UDP

The User datagram Protocol is one of the main protocols of the Internet protocol suite. UDP
helps the host to send messages in the form of datagrams to another host which is present in an
Internet protocol network without any kind of requirement for channel transmission setup. UDP
provides a unreliable service and the datagrams may arrive out of order, appear duplicated, or go
missing without notice. UDP assumes that error checking and correction is either not necessary
or performed in the application, avoiding the overhead of such processing at the network
interface level. Time-sensitive applications often use UDP because dropping packets is preferable
to waiting for delayed packets, which may not be an option in a real-time system.

Now we will learn how to create a UDP connection in network simulator.


1 # setup a UDP connection
2 set udp [new Agent/UDP]
3 $ns attach-agent $n1 $udp
4 $set null [new Agent/Null]
5 $ns attach-agent $n5 $null
6 $ns connect $udp $null
7 $udp set fid_2

Similarly,the command 'set udp [new Agent/UDP]' gives a pointer called 'udp' which indicates
the udp agent which is a object of ns. Then the command '$ns attach-agent $n1 $udp' defines the
source node of udp connection. Next the command 'set null [new Agent/Null]' defines the
destination of udp by a pointer called null. The next command '$ns attach-agent $n5 $null'
defines the destination node as n5.Next, the command '$ns connect $udp $null' makes the UDP
connection between the source and the destination .i.e. n1 and n5.When we have several flows
such as TCP, UDP etc. in a network. So, to identify these flows we mark these flows by using the
command '$udp set fid_2

Constant Bit Rate(CBR)

Constant Bit Rate (CBR) is a term used in telecommunications, relating to the quality of service.
When referring to codecs, constant bit rate encoding means that the rate at which a codec's output
data should be consumed is constant. CBR is useful for streaming multimedia content on limited
capacity channels since it is the maximum bit rate that matters, not the average, so CBR would be
used to take advantage of all of the capacity. CBR would not be the optimal choice for storage as
it would not allocate enough data for complex sections (resulting in degraded quality) while
wasting data on simple sections.

CBR over UDP Connection


1 #setup cbr over udp
2
3 set cbr [new Application/Traffic/CBR]
4 $cbr attach-agent $udp
5 $cbr set packetSize_1000
6 $cbr set rate_0.01Mb
7 $cbr set random _false

In the above we define a CBR connection over a UDP one. Well we have already defined the
UDP source and UDP agent as same as TCP. Instead of defining the rate we define the time
interval between the transmission of packets in the command '$cbr set rate_0.01Mb'. Next, with
the help of the command '$cbr set random _false' we can set random noise in cbr traffic. We can
keep the noise by setting it to 'false' or we can set the noise on by the command '$cbr set random
_1'. We can set by packet size by using the command '$cbr set packetSize_(packetsize).We can
set the packet size up to sum value in bytes.

Scheduling Events

In ns the tcl script defines how to schedule the events or in other words at what time which event
will occur and stop. This can be done using the command
$ns at .

So here in our program we will schedule the ftp and cbr.


1 # scheduling the events
2
3 $ns at 0.1 "cbr start"
4 $ns at 1.0 "ftp start"
5 $ns at 124.0 "ftp stop"
6 $ns at 124.5 "cbr stop"

Network Animator (NAM)


When we will run the above program in ns then we can visualize the network in the NAM. But
instead of giving random positions to the nodes, we can give suitable initial positions to the
nodes and can form a suitable topology. So, in our program we can give positions to the nodes in
NAM in the following way
1 #Give position to the nodes in NAM
2
3 $ns duplex-link-op $n0 $n2 orient-right-down
4 $ns duplex-link-op $n1 $n2 orient-right-up
5 $ns simplex-link-op $n2 $n3 orient-right
6 $ns simplex-link-op $n3 $n2 orient-left
7 $ns duplex-link-op $n3 $n4 orient-right-up
8 $ns duplex-link-op $n3 $n5 orient-right-down

We can also define the color of cbr and tcp packets for identification in NAM. For this we use the
following command
1 #Marking the flows
2 $ns color1 Blue
3 $ns color2 Red
To view the network animator we need to type the command: nam

Tracing
Tracing Objects

NS simulation can produce visualization trace as well as ASCII file corresponding to the events
that are registered at the network. While tracing ns inserts four objects: EnqT, DeqT, RecvT &
DrpT. EnqT registers information regarding the arrival of packet and is queued at the input queue
of the link. When overflow of a packet occurs, then the information of the dropped packet is
registered in DrpT. DeqT holds the information about the packet that is dequeued instantly.
RecvT hold the information about the packet that has been received instantly.

Structure of Trace files

1. The first field is event. It gives you four possible symbols '+' '-' 'r' 'd'. These four symbols
correspond respectively to enqueued, dequeued, received and dropped.
2. The second field gives the time at which the event occurs
3. The third field gives you the input node of the link at which the event occurs
4. The fourth field gives you the output node at which the event occurs
5. The fifth field shows the information about the packet type .i.e. whether the packet is UDP or
TCP
6. The sixth field gives the packet size
7. The seventh field give information about some flags
8. The eight field is the flow id(fid) for IPv6 that a user can set for each flow in a tcl script.It is
also used for specifying the color of flow in NAM display
9. The ninth field is the source address
10. The tenth field is the destination address
11. The eleventh field is the network layer protocol's packet sequence number
12. The last field shows the unique id of packet

Following are trace of two events:


r 1.84471 2 1 cbr 210 ------- 1 3.0 1.0 195 600
r 1.84566 2 0 ack 40 ------- 2 3.2 0.1 82 602

The trace file can be viewed with the cat command:


cat out.tr
7. Installation and working of ns-2.
Download and Extract ns2
Download the all in one package for ns2

The package downloaded will be named "ns-allinone-2.35.tar.gz". Copy it to the home folder.
Then in a terminal use the following two commands to extract the contents of the package.:

All the files will be extracted into a folder called "ns-allinone-2.35".

Building the dependencies


Ns2 requires a few packages to be pre-installed. It also requires the latest GCC- version to work
correctly. So install all of them by using the following command:

Once the installation is over, we have to make a change in the "ls.h" file. Use the following steps
to make the changes:

Navigate to the folder "linkstate", use the following command. Here it is assumed that the ns
folder extracted is in the home folder of your system.
cd ~/ns-allinone-2.35/ns-2.35/linkstate

Now open the file named "ls.h"

Scroll to the 137th line. In that change the word "error" to "this->error".

The image below shows the line 137 (highlighted in the image below) before making the changes
to the ls.h file.
The image below shows the line 137 (highlighted in the image below) after making the changes to
the ls.h file.

Save that file and close it.

Installation
Now we are ready to install ns2. To do so we first require root privileges and then we can run the
install script. Use the following commands:

Now, navigate to ns-2.35 directory and add ns2 to your /usr/bin:


Now, navigate to nam-1.15 folder to add NAM binary into your /usr/bin:

Running ns2
Once the system has restarted, open a terminal and start ns2 by using the following command:
ns

If the installation is correct then the terminal looks like the image below :
8. Simulate three nodes point-to-point networks with a
duplex link between them. Set the queue size and vary
the bandwidth and find number of packets dropped.
TCL Script: three_nodes.tcl
set ns [new Simulator]
# open a nam trace file in write mode
set nf [open out1.nam w]
# nf nam filename
$ns namtrace-all $nf
# tf trace filename
set tf [open out.tr w]
$ns trace-all $tf

# creates 3 nodes
set n0 [$ns node]
set n2 [$ns node]
set n3 [$ns node]

# establishing links
$ns duplex-link $n0 $n2 200Mb 10ms DropTail
$ns duplex-link $n2 $n3 1Mb 1000ms DropTail
$ns queue-limit $n0 $n2 10

# attaching transport layer protocols


set udp0 [new Agent/UDP]
$ns attach-agent $n0 $udp0
# attaching application layer protocols
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0

# creating sink(destination) node


set null0 [new Agent/Null]
$ns attach-agent $n3 $null0
$ns connect $udp0 $null0

proc finish { } {
global ns nf tf
# clears trace file contents
$ns flush-trace
close $nf
close $tf
exec nam out1.nam &
exit 0
}

$ns at 0.1 "$cbr0 start"


$ns at 1.0 "finish"
$ns run
AWK Script: packet_dropped.awk
#immediately after BEGIN should open braces ‘{‘

BEGIN{ c=0;}
{
if($1=="d")
{ c++;
printf("%s\t%s\n",$5,$11);
}
}
END{ printf("The number of packets dropped = %d\n",c); }

Run the simulation program:

Here “ns” indicates network simulator. We get the topology shown in the snapshot.

Now press the play button in the simulation window and the simulation will begins.

Finding number of packet dropped:


After simulation is completed run awk file to see the output.
To see the trace file contents: out.tr