• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Ns2 lab final
 

Ns2 lab final

on

  • 4,361 views

 

Statistics

Views

Total Views
4,361
Views on SlideShare
4,361
Embed Views
0

Actions

Likes
1
Downloads
381
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Ns2 lab final Ns2 lab final Document Transcript

    • Lab -10 Understanding Network Simulator 2Introduction :Network Simulator (Version 2), widely known as NS2, is simply an event-driven simulation tool thathas proved useful in studying the dynamic nature of communication networks. Simulation of wiredas well as wireless network functions and protocols (e.g., routing algorithms, TCP, UDP) can bedone using NS2. In general, NS2 provides users with a way of specifying such network protocolsand simulating their corresponding behaviours .Basic Architecture :Figure shows the basic architecture of NS2. NS2 provides users with an executable command “ns”which takes one input argument, the name of a Tcl simulation scripting file . In most cases, asimulation trace file is created and is used to plot graph and/or to create animation.NS2 consists of two key languages: C++ and Object-oriented Tool Command Language (OTcl).While the C++ defines the internal mechanism (i.e., a backend) of the simulation, the OTcl sets upsimulation by assembling and configuring the objects as well as scheduling discrete events (i.e., afrontend). The C++ and the OTcl are linked together using TclCL. Mapped to a C++ object, variablesin the OTcl domains are sometimes referred to as handles. Conceptually, a handle is just a string(e.g., “_o10”) in the OTcl domain and does not contain any functionality. Instead, the functionality(e.g., receiving a packet) is defined in the mapped C++ object (e.g., of class Connector). In the OTcldomain, a handle acts as a frontend which interacts with users and other OTcl objects. It maydefine its own procedures and variables to facilitate the interaction. Note that the memberprocedures and variables in the OTcl domain are called instance procedures (instprocs) andinstance variables (instvars), respectively. NS2 provides a largenumber of built-in C++ classes. It is advisable to use these C++ classes to set up a simulation via aTcl simulation script. However, advance users may find these objects insufficient. They need todevelop their own C++ classes and use a OTcl configuration interface to put together objectsinstantiated from these class.
    • Directory StructureSuppose that NS2 is installed in Directory nsallinone-2.35. Figure shows the directory structureunder directory nsallinone-2.35. Here, the directory nsallinone-2.35is on the Level 1. On the Level2, the directory tclcl-1.20 contains classes in TclCL (e.g., Tcl, TclObject, TclClass). All NS2 simulationmodules are in the directory ns-2.35 on the Level 2. Hereafter, we will refer to directories ns-2.35and tclcl-1.20 as ˜ns/ and ˜tclcl/, respectively.On Level 3, the modules in the interpreted hierarchy are under the directory tcl. Among thesemodules, the frequently used ones (e.g., ns-lib.tcl, ns-node.tcl, ns-link.tcl) are stored under thedirectory lib on Level 4. Simulation modules in the compiled hierarchy are classified in directorieson Level 3. For example, directory tools contain various helper classes such as random variablegenerators. Directory common contains basic modules related to packet forwarding such as thesimulator, the scheduler, connector, packet. Directories queue, tcp, and trace contain modules forqueue, TCP (Transmission Control Protocol), and tracing, respectively.
    • Running NS2 Simulation :A Simulation ExampleNote : this example is taken from this linkhttp://nile.wpi.edu/NS/ 1.) Copy this file to myfirstTcl.tcl#Create a simulator objectset ns [new Simulator]#Define different colors for data flows (for NAM)$ns color 1 Blue$ns color 2 Red#Open the NAM trace fileset nf [open out.nam w]$ns namtrace-all $nf#Define a finish procedureproc finish {} { global ns nf $ns flush-trace #Close the NAM trace file close $nf #Execute NAM on the trace file exec nam out.nam & exit 0}#Create four nodesset n0 [$ns node]set n1 [$ns node]set n2 [$ns node]set n3 [$ns node]#Create links between the nodes$ns duplex-link $n0 $n2 2Mb 10ms DropTail$ns duplex-link $n1 $n2 2Mb 10ms DropTail$ns duplex-link $n2 $n3 1.7Mb 20ms DropTail#Set Queue Size of link (n2-n3) to 10$ns queue-limit $n2 $n3 10#Give node position (for NAM)$ns duplex-link-op $n0 $n2 orient right-down$ns duplex-link-op $n1 $n2 orient right-up
    • $ns duplex-link-op $n2 $n3 orient right#Monitor the queue for link (n2-n3). (for NAM)$ns duplex-link-op $n2 $n3 queuePos 0.5#Setup a TCP connectionset tcp [new Agent/TCP]$tcp set class_ 2$ns attach-agent $n0 $tcpset sink [new Agent/TCPSink]$ns attach-agent $n3 $sink$ns connect $tcp $sink$tcp set fid_ 1#Setup a FTP over TCP connectionset ftp [new Application/FTP]$ftp attach-agent $tcp$ftp set type_ FTP#Setup a UDP connectionset udp [new Agent/UDP]$ns attach-agent $n1 $udpset null [new Agent/Null]$ns attach-agent $n3 $null$ns connect $udp $null$udp set fid_ 2#Setup a CBR over UDP connectionset cbr [new Application/Traffic/CBR]$cbr attach-agent $udp$cbr set type_ CBR$cbr set packet_size_ 1000$cbr set rate_ 1mb$cbr set random_ false#Schedule events for the CBR and FTP agents$ns at 0.1 "$cbr start"$ns at 1.0 "$ftp start"$ns at 4.0 "$ftp stop"$ns at 4.5 "$cbr stop"#Detach tcp and sink agents (not really necessary)$ns at 4.5 "$ns detach-agent $n0 $tcp ; $ns detach-agent $n3 $sink"#Call the finish procedure after 5 seconds of simulation time$ns at 5.0 "finish"#Print CBR packet size and interval
    • puts "CBR packet size = [$cbr set packet_size_]"puts "CBR interval = [$cbr set interval_]"#Run the simulation$ns run 2.) Run the above simulation by typing #ns myfirstTcl.tcl 3.) Nam Emulator will appear .set ns [new Simulator]: generates an NS simulator object instance, and assigns it tovariable ns (italics is used for variables and values in this section). What this line does is thefollowing: o Initialize the packet format (ignore this for now) o Create a scheduler (default is calendar scheduler) o Select the default address format (ignore this for now) The "Simulator" object has member functions that do the following:
    • o Create compound objects such as nodes and links (described later)o Connect network component objects created (ex. attach-agent)o Set network component parameters (mostly for compound objects)o Create connections between agents (ex. make connection between a "tcp" and "sink")o Specify NAM display optionso Etc.• $ns color fid color: is to set color of the packets for a flow specified by the flow id (fid).This member function of "Simulator" object is for the NAM display, and has no effect onthe actual simulation.• $ns namtrace-all file-descriptor: This member function tells the simulator to recordsimulation traces in NAM input format. It also gives the file name that the trace will bewritten to later by the command $ns flush-trace. Similarly, the member function trace-all is for recording the simulation trace in a general format.• proc finish {}: is called after this simulation is over by the command $ns at 5.0 "finish".In this function, post-simulation processes are specified.• set n0 [$ns node]: The member function node creates a node. A node in NS iscompound object made of address and port classifiers. Users can create a node byseparately creating an address and a port classifier objects and connecting themtogether. However, this member function of Simulator object makes the job easier. Tosee how a node is created, look at the files: " ns-2.35/tcl/lib/ns-lib.tcl" and "ns-2.35/tcl/lib/ns-node.tcl".• $ns duplex-link node1 node2 bandwidth delay queue-type: creates two simplex linksof specified bandwidth and delay, and connects the two specified nodes. In NS, theoutput queue of a node is implemented as a part of a link, therefore users shouldspecify the queue-type when creating links. In the above simulation script, DropTailqueue is used. If the reader wants to use a RED queue, simply replace the word DropTailwith RED. Like a node, a link is a compound object, and users can create its sub-objectsand connect them and the nodes. Link source codes can be found in "ns-2.35/tcl/lib/ns-lib.tcl" and "ns-2.35/tcl/lib/ns-link.tcl" files. One thing to note is that you can inserterror modules in a link component to simulate a lossy link (actually users can make andinsert any network objects). Refer to the NS documentation to find out how to do this.• $ns queue-limit node1 node2 number: This line sets the queue limit of the twosimplex links that connect node1 and node2 to the number specified. Please take a lookat "ns-2.35/tcl/lib/ns- lib.tcl" and "ns-2.35/tcl/lib/ns-link.tcl", or NS documentation formore information.• $ns duplex-link-op node1 node2 ...: The next couple of lines are used for the NAMdisplay. To see the effects of these lines, users can comment these lines out and try thesimulation. Now that the basic network setup is done, the next thing to do is to setuptraffic agents such as TCP and UDP, traffic sources such as FTP and CBR, and attach themto nodes and agents respectively.
    • • set tcp [new Agent/TCP]: This line shows how to create a TCP agent. But in general,users can create any agent or traffic sources in this way. Agents and traffic sources are infact basic objects (not compound objects), mostly implemented in C++ and linked toOTcl. Therefore, there are no specific Simulator object member functions that createthese object instances. To create agents or traffic sources, a user should know the classnames of these objects (Agent/TCP, Agnet/TCPSink, Application/FTP and so on). Thisinformation can be found in the NS documentation. But one shortcut is to look at the"ns-2.35/tcl/lib/ns-default.tcl" file. This file contains the default configurable parametervalue settings for available network objects. Therefore, it works as a good indicator ofwhat kind of network objects are available in NS and what are the configurableparameters.• $ns attach-agent node agent: The attach-agent member function attaches an agentobject created to a node object. Actually, what this function does is call the attachmember function of specified node, which attaches the given agent to itself. Therefore,a user can do the same thing by, for example, $n0 attach $tcp. Similarly, each agentobject has a member function attach- agent that attaches a traffic source object toitself.• $ns connect agent1 agent2: After two agents that will communicate with each otherare created, the next thing is to establish a logical network connection between them.This line establishes a network connection by setting the destination address to eachothers network and port address pair. Assuming that all the network configuration isdone, the next thing to do is write a simulation scenario (i.e. simulation scheduling).The Simulator object has many scheduling member functions. However, the one that ismostly used is the following:• $ns at time "string": This member function of a Simulator object makes the scheduler(scheduler_ is the variable that points the scheduler object created by [new Scheduler]command at the beginning of the script) to schedule the execution of the specifiedstring at given simulation time. For example, $ns at 0.1 "$cbr start" will make thescheduler call a start member function of the CBR traffic source object, which starts theCBR to transmit data. In NS, usually a traffic source does not transmit actual data, but itnotifies the underlying agent that it has some amount of data to transmit, and theagent, just knowing how much of the data to transfer, creates packets and sends them.After all network configuration, scheduling and post-simulation p procedurespecifications are done, theonly thing left is to run the simulation. This is done by $nsrun.
    • 1). Post-simulationTrace File analysis :Running the above script generates a NAM trace file that is going to be used as an input to NAMand a trace file called "out.tr" that will be used for our simulation analysis. Below is the traceformat and example trace data from "out.tr".Each trace line starts with an event (+, -, d, r) descriptor followed by the simulation time (inseconds) of that event, and from and to node, which identify the link on which the event occurred. The next information in the line before flags (appeared as "------" since no flag is set) is packet typeand size (in Bytes). Currently, NS implements only the Explicit Congestion Notification (ECN) bit,and the remaining bits are not used. The next field is flow id (fid) of IPv6 that a user can set foreach flow at the input OTcl script. Even though fid field may not used in a simulation, users can usethis field for analysis purposes. The fid field is also used when specifying stream color for the NAMdisplay. Thenext two fields are source and destination address in forms of "node.port". The next field showsthe network layer protocols packet sequence number. Note that even though UDPimplementations do not use sequence number, NS keeps track of UDP packet sequence number foranalysis purposes. The last field shows the unique id of the packet.Let’s Take an Example+ 0.1 1 2 cbr 1000 ------- 2 1.0 3.1 0 0- 0.1 1 2 cbr 1000 ------- 2 1.0 3.1 0 0+ 0.108 1 2 cbr 1000 ------- 2 1.0 3.1 1 1- 0.108 1 2 cbr 1000 ------- 2 1.0 3.1 1 1r 0.114 1 2 cbr 1000 ------- 2 1.0 3.1 0 0+ 0.114 2 3 cbr 1000 ------- 2 1.0 3.1 0 0- 0.114 2 3 cbr 1000 ------- 2 1.0 3.1 0 0+ 0.116 1 2 cbr 1000 ------- 2 1.0 3.1 2 2above is the trace file .**********************************************************************BEGIN{//Begin will be initialized once in a Codei=0;}{
    • action=$1;cl1=$2;Cl2=$3;cl3=$4;cl4=$5;if(action=="+"){c1[i]=cl1;c2[i]=cl2;c3[i]=cl3;c4[i]=cl4i++;}}END{for(j=0;j<=i;j++){printf("%f %x %d %sn", c1[j], c2[j], c3[j], c4[j]);}}To run this#awk –f “example.awk” out.tr Note : here out.tr is the file generated from myfirstTcl.tclawk (also written as Awk and AWK) is a utility that enables a programmer to write tiny buteffective programs in the form of statements that define text patterns that are to be searched forin each line of a document and the action that is to be taken when a match is found within a line.awk breaks each line into fields, which are groups of characters with spaces acting as separators sothat a word, for example, would be a field. A string is encased in backslashes and actions to beperformed are encased in curly brackets. The lines are numbered in order of their appearance,with "0" referring to the entire line. "$" is the symbol for field.
    • Plotting :Note : Please follow these link for more infromation .http://www.duke.edu/~hpgavin/gnuplot.html for gnuplothttp://www.isi.edu/nsnam/xgraph/ for xgraphhttp://en.wikipedia.org/wiki/Gnuplotthere is not much difference between xgraph and gnuplot .xgraph comes with ns2 and for gnuplotwe have to install .gnuplot is a command-line program that can generate two- and three-dimensional plots of functions,data, and data fits. It is frequently used for publication-quality graphics as well as education. Theprogram runs on all major computers and operating systems (GNU/Linux, Unix, MicrosoftWindows, Mac OS X, and others). It is a program with a fairly long history, dating back to 1986.Despite its name, this software is not distributed under the GNU General Public License (GPL),opting for its own more restrictive open source license instead.#gnuplotgnuplot> plot “name_of_file” with optionsfor ex.gnuplot> plot “link” with lineWork to Do :1 . Copy this Code in a file FirstCode.tcl*****************************************************************#Create a simulator objectset ns [new Simulator]#Define different colors for data flows (for NAM)$ns color 1 Blue$ns color 2 Red#Open the NAM trace fileset nf [open out.nam w]$ns namtrace-all $nf#Open the Trace fileset tf [open out.tr w]$ns trace-all $tf#Define a finish procedureproc finish {} { global ns nf tf $ns flush-trace #Close the NAM trace file close $nf #Close the Trace file
    • close $tf #Execute NAM on the trace file exec nam out.nam &exit 0}#Create four nodesset n0 [$ns node]set n1 [$ns node]set n2 [$ns node]set n3 [$ns node]#Create links between the nodes$ns duplex-link $n0 $n2 2Mb 10ms DropTail$ns duplex-link $n1 $n2 2Mb 10ms DropTail$ns duplex-link $n2 $n3 1.7Mb 20ms DropTail#Set Queue Size of link (n2-n3) to 10$ns queue-limit $n2 $n3 10#Give node position (for NAM)$ns duplex-link-op $n0 $n2 orient right-down$ns duplex-link-op $n1 $n2 orient right-up$ns duplex-link-op $n2 $n3 orient right#Monitor the queue for link (n2-n3). (for NAM)$ns duplex-link-op $n2 $n3 queuePos 0.5#Setup a TCP connectionset tcp [new Agent/TCP]$tcp set class_ 2$ns attach-agent $n0 $tcpset sink [new Agent/TCPSink]$ns attach-agent $n3 $sink$ns connect $tcp $sink$tcp set fid_ 1#Setup a FTP over TCP connectionset ftp [new Application/FTP]$ftp attach-agent $tcp$ftp set type_ FTP
    • #Setup a UDP connectionset udp [new Agent/UDP]$ns attach-agent $n1 $udpset null [new Agent/Null]$ns attach-agent $n3 $null$ns connect $udp $null$udp set fid_ 2#Setup a CBR over UDP connectionset cbr [new Application/Traffic/CBR]$cbr attach-agent $udp$cbr set type_ CBR$cbr set packet_size_ 1000$cbr set rate_ 1mb$cbr set random_ false#Schedule events for the CBR and FTP agents$ns at 0.1 "$cbr start"$ns at 1.0 "$ftp start"$ns at 100.0 "$ftp stop"$ns at 100 "$cbr stop"#Detach tcp and sink agents (not really necessary)$ns at 99.5 "$ns detach-agent $n0 $tcp ; $ns detach-agent $n3 $sink"#Call the finish procedure after 5 seconds of simulation time$ns at 100.5 "finish"#Print CBR packet size and intervalputs "CBR packet size = [$cbr set packet_size_]"puts "CBR interval = [$cbr set interval_]"#Run the simulation$ns run********************************************************************************************2. Run#ns FirstCode.tcl3. Copy and Paste in link_tcp.awkBelow file finds the throughput of the given TCP connection only please remember we havecreated two connections one is TCP and one is UDP.******************************************************************************************************************** BEGIN {
    • packet_size= 1500 total_throughput = 0 final = 0 time_ini = 1.0 count = 0 } { ackn = $5 event = $1 time = $2 node = 0 flowid= $8 from_node = $3 to_node= $4 #from node should be 2 #print(event) #print(time) #print(flowid) #print(from_node) if(event == "r" && flowid == "1" && from_node == "0" && time_ini >= time && ackn == "tcp" ) { #remember always immediately after if there will be start of the “{“ .not in next line total_throughput = total_throughput + packet_size ++count } if(event == "r" && flowid == "1" && from_node == "0" && time_ini <= time && ackn == "tcp") { #print(count) count = 0 final = total_throughput + final #print(total_throughput) total_throughput = (total_throughput *8)/1000 printf("%ft%fn" , time_ini , total_throughput ) > "Throughput" total_throughput = 0 time_ini = time_ini + 1 } } END { print("*******************") final = (((final *8)/1000 ) / time) print("Total Throughput for TCP : " , final) for (i = 1.00 ; i <= time_ini ; i++) printf("%ft%fn" , i , final ) > "Throughput_AVG"}
    • ************************************************************************************* 4. Run above code awk -f "throughput.awk" out.tr 5. two files have been generated Throughput and Throughput_AVG 6. plot the Graph by this below command #gnuplot gnuplot> plot "Throughput_AVG" with line , "Throughput" with lineAssignment :Find the Throughput for UDP connection .just like TCPconnection .Plot the throughput graph . upload this plot and awk file incourse website today only. 1. Run the given FirstCode.tcl 2. You will get the out.tr and out.nam 3. You can also run out.nam by typing #nam out.nam 4. Then make some changes in link_tcl.awk Like if(event == "r" && flowid == "1" && from_node == "0" && to_node == "3" && time_ini >= time && ackn == "tcp" ) change from _node == “1” to_node == “3” flowid == “2”
    • ackn == “cbr” 5. Then follow all steps from the step 4.Note : You does not have to re-run the tcl file just make somechanges in awk file and follow from the step 4 .References : 6. Ns2 By examples : http://nile.wpi.edu/NS/ 7. Teerawat Issariyakul and Ekram Hossain, “Introduction to Network Simulator NS2”, Second Edition, Springer 2012. 8. http://csis.bits-pilani.ac.in/faculty/murali/resources/tutorials/ns2.htm 9. http://www.duke.edu/~hpgavin/gnuplot.html (Gnuplot) 10. http://www.isi.edu/nsnam/xgraph/ xgraphPrepared By :Arun Kumar Gupta201111049(M)8000597109arun_k_gupta@daiict.ac.inarungupta143@gmail.com