Monday, September 26, 2016

Program No 7

Write a TCL script to simulate the following scenario with ns2 simulator. Consider six nodes, (as shown in the figure below) moving within a flat topology of 700m x 700m. The initial positions of nodes   are   0   (150,300)   ,1   (300,500),2   (500,500),3 (300,100),4(500,100)   and   5(650,300)   respectively.A   TCP connection is initiated between node 0 (source) and node 5 (destination) through node 3 and node 4 i.e the route is 0­3­4­5. At time t = 3 seconds the FTP application runs over it. After time t=4.0 sec, node 3 (300,100) moves towards node 1 (300,500) with a speed of 5.0m/sec and after some time the path break, then the data transmit with a new path via node 1 and node 2 i.e the new route 0­1­2­5. The simulation lasts for 60 secs. In the above said case both the route has equal cost. Use DSR as the routing protocol and the IEEE 802.11 MAC protocol. Now, Analyze the trace file and determine when the use of second route commence, and Plot the number of packets received by each node over the entire time duration of the simulation

TCL Script:

set ns [new Simulator]

set namfile [open namfile.nam w]
$ns namtrace-all-wireless $namfile 700 700

set wireless_tracefile [open dsr-6-nodes.tr w]
$ns trace-all $wireless_tracefile

$ns use-newtrace
set topography [new Topography]
$topography load_flatgrid 700 700

set god_ [create-god 6]

#globally node settings
$ns node-config -adhocRouting DSR \
-llType LL \
-macType Mac/802_11 \
-ifqType CMUPriQueue \
-ifqLen 50 \
-antType Antenna/OmniAntenna \
-propType Propagation/TwoRayGround \
-phyType Phy/WirelessPhy \
-channel [new Channel/WirelessChannel] \
-topoInstance $topography \
-agentTrace ON \
-routerTrace OFF \

-macTrace ON

# Create wireless nodes

set node(0) [$ns node]
$node(0) set X_ 150
$node(0) set Y_ 300
$node(0) set Z_ 0.0
$node(0) color "black"
$ns initial_node_pos
$node(0) 30.000000

set node(1) [$ns node]
$node(1) set X_ 300
$node(1) set Y_ 500
$node(1) set Z_ 0.0
$node(1) color "black"
$ns initial_node_pos
$node(1) 30.000000

set node(2) [$ns node]
$node(2) set X_ 500
$node(2) set Y_ 500
$node(2) set Z_ 0.0
$node(2) color "black"
$ns initial_node_pos
$node(2) 30.000000

set node(3) [$ns node]
$node(3) set X_ 300
$node(3) set Y_ 100
$node(3) set Z_ 0.0
$node(3) color "black"
$ns initial_node_pos
$node(3) 30.000000

set node(4) [$ns node]
$node(4) set X_ 500
$node(4) set Y_ 100
$node(4) set Z_ 0.0
$node(4) color "black"
$ns initial_node_pos
$node(4) 30.000000

set node(5) [$ns node]
$node(5) set X_ 650
$node(5) set Y_ 300
$node(5) set Z_ 0.0
$node(5) color "black"
$ns initial_node_pos
$node(5) 30.000000

$ns at 4.0 "$node(3) setdest 300.0 500.0 5.0"

$ns at 4.0 "$god_ set-dist 0 5 3"

set tcp [new Agent/TCP]
$ns attach-agent $node(0) $tcp

set sink [new Agent/TCPSink]
$ns attach-agent $node(5) $sink

$ns connect $tcp $sink

set ftp [new Application/FTP]
$ftp attach-agent $tcp

$ns at 3.0 "$ftp start"

for {set i 0} {$i < 6 } {incr i} {
$ns at 60.000000 "$node($i) reset";
}

proc finish {} 
{
global ns
$ns flush-trace
exit 0
}

$ns at 60.000000 "finish"
$ns run

Program No 6

Bandwidth sharing between TCP and UDP Consider the dumbbell topology from our previous exercise: Node # 0 is a TCP source, and the corresponding sink is at node # 6. Node # 1 is a UDP source (CBR traffic) with a null agent attached to node # 7. These two traffic flows through the common link 2­3. The aim of this exercise is to examine how TCP and UDP share the bandwidth between themselves when the rate of CBR traffic is changed. Set the TCP packet size to 1460 B. The UDP and CBR packet sizes are 1500 B. All the links in the network have same bandwidths (say, 4 Mb), delay and queue types.  Part 1:    Set the initial rate of CBR traffic to 0.5ms. Run the simulation, and plot the "Bytes Received" by node #s 6 and 7 (sinks for TCP and UDP traffic)     Now, increment the rate up to 4ms, the rate of CBR, in steps of 0.5ms. Run the simulation and plot the graphs again.    How does the graphs change after each run? In particular, what's the nature of the graphs when the rate of CBR traffic is 50% of the bit rate?

TCL Script:

set ns [new Simulator]
set namfile [open ex_06.nam w]
$ns namtrace-all $namfile

set tracefile [open ex_06.tr w]
$ns trace-all $tracefile    
Agent/TCP set packetSize_ 1460

set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
set n6 [$ns node]
set n7 [$ns node]

$n1 color blue
$n1 shape box
$n0 color red

$ns duplex-link $n0 $n2 4Mb 10ms DropTail

$ns duplex-link-op $n0 $n2 orient right-down
$ns duplex-link $n1 $n2 4Mb 10ms DropTail
$ns duplex-link-op $n1 $n2 orient right-up
$ns duplex-link $n2 $n3 4Mb 10ms DropTail
$ns duplex-link-op $n2 $n3 orient right
$ns duplex-link $n3 $n4 4Mb 10ms DropTail
$ns duplex-link-op $n3 $n4 orient right-up
$ns duplex-link $n3 $n5 4Mb 10ms DropTail
$ns duplex-link-op $n3 $n5 orient right-down
$ns duplex-link $n4 $n6 4Mb 10ms DropTail
$ns duplex-link-op $n4 $n6 orient right
$ns duplex-link $n5 $n7 4Mb 10ms DropTail
$ns duplex-link-op $n5 $n7 orient right

set tcp [new Agent/TCP]
$ns attach-agent $n0 $tcp

set sink [new Agent/TCPSink]
$ns attach-agent $n6 $sink  

$ns connect $tcp $sink

set ftp [new Application/FTP]
$ftp attach-agent $tcp

set udp [new Agent/UDP]
$ns attach-agent $n1 $udp

set null [new Agent/Null]
$ns attach-agent $n7 $null

$ns connect $udp $null

$udp set class_ 1
$ns color 1 Blue

$tcp set class_ 2
$ns color 2 Red

set cbr [new Application/Traffic/CBR]
$cbr set packetSize_ 1500
$cbr set interval_ 0.005
$cbr attach-agent $udp

$ns at 0.0 "$cbr start"
$ns at 9.0 "$cbr stop"

$ns at 0.0 "$ftp start"
$ns at 9.0 "$ftp stop"

proc finish {}
{    
global ns namfile tracefile
$ns flush-trace
close $namfile
close $tracefile

set awkCode {
BEGIN{}
{
if($1 == "r" && $4 == 6 && $6 >= 1460)
{
count_bytes = count_bytes + $6 - ($6 % 1460);
print $2,count_bytes >> "prgm6_tcp0.005.data";
}
else
if($1 == "r" && $4 == 7 && $6 >= 500)
{
count_bytes = count_bytes + $6 - ($6 % 500);
print $2,count_bytes >> "prgm6_udp0.005.data";
}
}
END{}
}
exec awk $awkCode ex_06.tr

exec nam ex_06.nam &
exec xgraph -bb -tk -x Time -y Bytes_Received_at_0.5 prgm6_tcp0.005.data -bg white &
exec xgraph -bb -tk -x Time -y Bytes_Received_at_0.5 prgm6_udp0.005.data -bg white &
exit 0
}
$ns at 100.0 "finish"
$ns run

Program No 5

Measuring Network Performances ­ Bottleneck in the network Consider a dumbbell topology with eight nodes as shown as in the following figure. Consider nodes# 2 and 3 to be two routers   connecting   two   different   networks.   When   the bandwidth of the link 2­3 is much lower than the sum of bandwidths of the other links in the network, it act as a bottleneck. Assume node # 0 running a FTP application (over TCP) and sending data to node # 6. Node # 1 is sending CBR data node # 7. Assume all the links except 2­3 has a bandwidth of 1 Mb, propagation delay of 10ms and queue type as DropTail. (All are duplex links).  Tasks:   The link 2­3 has a propagation delay of 10 ms. Vary it's bandwidth from 0.5 Mb to 2.5 Mb in steps of 0.25Mb.    Compute the throughput for node # 3 in each case    Plot the throughput vs. bandwidth data in the "Cu stom Plot" section below    Based on the above plots, suggest what should be the recommended bandwidth of the link 2­3. Now, plot the end­to­ end delay between nodes 0 and 6 for the above chosen values of link 2­3  bandwidth. Revisit your previous answer (i.e. optimum bandwidth of link 2­3) based on these graphs.

TCL Script:

set ns [new Simulator]
set namfile [open ex_05a.nam w]
$ns namtrace-all $namfile

set tracefile [open ex_05a.tr w]
$ns trace-all $tracefile    
Agent/TCP set packetSize_ 1460

set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
set n6 [$ns node]
set n7 [$ns node]

$n1 color blue
$n1 shape box
$n0 color red

$ns duplex-link $n0 $n2 1Mb 10ms DropTail
$ns duplex-link-op $n0 $n2 orient right-down
$ns duplex-link $n1 $n2 1Mb 10ms DropTail
$ns duplex-link-op $n1 $n2 orient right-up
$ns duplex-link $n2 $n3 0.5Mb 10ms DropTail
$ns duplex-link-op $n2 $n3 orient right
$ns duplex-link $n3 $n4 1Mb 10ms DropTail
$ns duplex-link-op $n3 $n4 orient right-up
$ns duplex-link $n3 $n5 1Mb 10ms DropTail
$ns duplex-link-op $n3 $n5 orient right-down
$ns duplex-link $n4 $n6 1Mb 10ms DropTail
$ns duplex-link-op $n4 $n6 orient right
$ns duplex-link $n5 $n7 1Mb 10ms DropTail
$ns duplex-link-op $n5 $n7 orient right

set tcp [new Agent/TCP]
$ns attach-agent $n0 $tcp

set sink [new Agent/TCPSink]
$ns attach-agent $n6 $sink
 
$ns connect $tcp $sink

set ftp [new Application/FTP]
$ftp attach-agent $tcp

set udp [new Agent/UDP]
$ns attach-agent $n1 $udp

set null [new Agent/Null]
$ns attach-agent $n7 $null

$ns connect $udp $null

$udp set class_ 1
$ns color 1 Blue
$tcp set class_ 2
$ns color 2 Red

set cbr [new Application/Traffic/CBR]
$cbr set packetSize_ 500
$cbr set interval_ 0.005
$cbr attach-agent $udp

$ns at 0.0 "$cbr start"
$ns at 9.0 "$cbr stop"
set filesize [expr 4*1024*1024]
$ns at 0.0 "$ftp send $filesize"

proc finish {}
{    
global ns namfile tracefile
$ns flush-trace
close $namfile
close $tracefile

exec nam ex_05a.nam &
exit 0
}

$ns at 100.0 "finish"
$ns run



Note:-  
In the underlined line put the bandwidth from 0.5Mb, 0.75Mb, 1.0Mb, 1.25Mb, 1.5Mb, 1.75Mb, 2.0Mb, 2.25Mb and 2.5Mb and execute the program.

Calculatin ThroughPut:

For every time you change the bandwidth execute the following code with this command in terminal:-  awk -f throughput.awk ex_05.tr

BEGIN

recvbytes = 0 starttime = $2 


if ( $1 == "r" && $4 == 3 && $6 >100) 

recvbytes += $6 endt = $2 


END

printf(" %f \n", ((recvbytes/(endt-starttime))* (8/(1024*1024)))) 
}

Calculatin Delay:

For every time you change the bandwidth execute the following code with this command in terminal:- awk -f delay.awk ex_05.tr

BEGIN

tdelay=0 count=0 pktid=-1 


if($1=="+" && $3==0 && $12>pktid) 

pktid=$12 sTime[pktid]=$2 

if($1=="r" && $4==6) 

pktid=$12 eTime[$12]=$2 count++ 

if($1=="d") 

eTime[$12]=-1 


END

for(i=0;i<pktid;i++)

delay[i]=eTime[i]-sTime[i] if(delay[i]>0) tdelay=tdelay+delay[i] 

print("%f\n",(tdelay/count)) 
}

Program No 4

Simulating link errors  Consider the following network diagram: Here node # 2 act as a router. Any traffic to or from the LAN passes through it. Consider node # 1 running a FTP server, and node # 5 is downloading a file of size 4 MB. However, the link between node # 2 and # 3 is fault. It drops packets with a fixed probability of 0.2. Implement a link error model to reflect this. It may be noted here that the file download time will be more than we had in exercise # 2 of experiment # 1. Try different values of the simulation time to ensure that the file has been entirely transferred. Is the plot of bytes received a linear curve or non­linear? Why? Presence of link errors cause one or more packets to be retransmitted. Verify this from the "Packet Retransmissions" plot.

TCL Script:

set ns [new Simulator]
set namfile [open lab4.nam w]
$ns namtrace-all
$namfile set tracefile [open lab4.tr w]
$ns trace-all $tracefile

set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
set n6 [$ns node]
$n1  color red
$n1 shape square

$ns duplex-link $n0 $n1 1Mb 10ms DropTail
$ns duplex-link-op $n0 $n1 orient right-down

$ns duplex-link $n0 $n2 1Mb 10ms DropTail
$ns duplex-link-op $n0 $n2 orient right

$ns duplex-link $n1 $n2 1Mb 10ms DropTail
$ns duplex-link-op $n1 $n2 orient right-up

$ns duplex-link $n2 $n3 1Mb 10ms DropTail
$ns duplex-link-op $n2 $n3 orient right

set lan [$ns newLan "$n3 $n4 $n5 $n6" 10Mb 10ms LL Queue/DropTail Mac/802_3 Channel]

set errmodel [new ErrorModel]
$errmodel set rate_ 0.2
$errmodel ranvar [new RandomVariable/Uniform]
$errmodel drop-target [new Agent/Null]
$ns lossmodel $errmodel $n2 $n3

set tcp [new Agent/TCP]
$ns attach-agent $n1 $tcp

set sink [new Agent/TCPSink]
$ns attach-agent $n5 $sink
$ns connect $tcp $sink

set ftp [new Application/FTP]
$ftp attach-agent $tcp
set filesize [expr 4*1024*1024]
$ns at 0.0 "$ftp send $filesize"

proc finish {}
{
global ns namfile tracefile
$ns flush-trace
close $namfile
close $tracefile

set awkCode
{
BEGIN{}
{
if($1 == "r" && $4 == 5 && $6 > 1000)
{
count_bytes = count_bytes + $6 - ($6 % 1000);
print $2,count_bytes >> "lab4.data";
}
else
if($1 == "d" && $5 == "tcp" && $6 > 1000)
{
count_packets++; print $2,count_packets >> "lab4_packets.data";
}
}
END{}
}
exec awk $awkCode lab4.tr
exec nam lab4.nam &
exec xgraph -bb -tk -x Time -x Bytes lab4.data -bg white &
exec xgraph -bb -tk -x Time -y packets lab4_packets.data -bg white &
exit 0

}
$ns at 100.0 "finish"
$ns run

ADDITIONAL TASK (3)

Suppose the above LAN is to be connected to the Internet. Add node # 7 into the network so that it act as the gateway. Connect node # 0 and # 7 with a 1 Mb wired link. Move the UDP source to node # 7.

TCL Script:

set ns [new Simulator]
set namfile [open ex_03at.nam w]
$ns namtrace-all $namfile

set tracefile [open ex_03at.tr w]
$ns trace-all $tracefile    

set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
set n6 [$ns node]
set n7 [$ns node]

set lan [$ns newLan "$n0 $n1 $n2 $n3 $n4 $n5 $n6" 100Mb 0.5ms LL Queue/DropTail Mac/802_3 Channel Phy/WiredPhy]

set udp [new Agent/UDP]
$ns attach-agent $n7 $udp

set null [new Agent/Null]
$ns attach-agent $n6 $null
 
$ns connect $udp $null

set cbr [new Application/Traffic/CBR]
$cbr set packetSize_ 500
$cbr set interval_ 0.005
$cbr attach-agent $udp

$ns at 0.0 "$cbr start"
$ns at 9.0 "$cbr stop"

proc finish {}
 {    
global ns namfile tracefile
$ns flush-trace
close $namfile
close $tracefile
exec nam ex_03at.nam &
exit 0
}

$ns duplex-link $n7 $n0 1Mb 10ms DropTail

$ns at 10.0 "finish"
$ns run

Program No 2/3::

Part - A            

Setting up a local area network with ns2  In this exercise you will be simulating a CSMA/CD based LAN with ns2. Consider the LAN with seven nodes to be an isolated one i.e. not connected to the Internet. Node # 0 in the LAN act as a UDP traffic source, and node # 6 is the destination node. Assume CBR traffic to be flowing between the nodes. The simulation lasts for 25 seconds. In Ethernet a packet is broadcasted in the shared medium, and only the destination node accepts the packet. Other nodes simply drop it.

TCL Script:

set ns [new Simulator]
set namfile [open ex_03.nam w]
$ns namtrace-all $namfile

set tracefile [open ex_03.tr w]
$ns trace-all $tracefile  

set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
set n6 [$ns node]

set lan [$ns newLan "$n0 $n1 $n2 $n3 $n4 $n5 $n6" 100Mb 0.5ms LL Queue/DropTail Mac/802_3 Channel Phy/WiredPhy]

set udp [new Agent/UDP]
$ns attach-agent $n0 $udp
 
set null [new Agent/Null]
$ns attach-agent $n6 $null

$ns connect $udp $null

set cbr [new Application/Traffic/CBR];
$cbr set packetSize_ 500
$cbr set interval_ 0.005
$cbr attach-agent $udp

$ns at 0.0 "$cbr start"
$ns at 9.0 "$cbr stop"

proc finish {}
{    
global ns namfile tracefile
$ns flush-trace close
$namfile close
$tracefile exec nam ex_03.nam &
exit 0
}
$ns at 0.25 "finish" $ns run

Sunday, September 25, 2016

Program No 2

Write a TCL script to simulate a file transfer with ns2  Consider a client and a server. The server is running a FTP application (over TCP). The client sends a request to download a file of size 10 MB from the server. Write a script to simulate this scenario. Let node #0 be the server and node #1 be the client. TCP packet size is 1500 B. Assume typical values for other parameters.  Note: This simulation require transfer of a fixed size file. Therefore, time required for the transfer would be constant for a given bandwidth of a link. To verify this, determine the time that would roughly be required for the transfer. Then look at the bottom of the trace file and verify whether there is any transmission beyond the time calculated. To verify that the client has downloaded the entire file, plot the "Bytes Received" curve for node#1. The y­axis is in Kbits. Convert it to MB and verify whether it approximates the specified file size. TCP headers would effectively increase the count of received bytes at node # 1.

TCL Script:

set ns [new Simulator]

set namfile [open ex_02.nam w]
$ns namtrace-all $namfile

set tracefile [open ex_02.tr w]
$ns trace-all $tracefile    

Agent/TCP set packetSize_ 1500

set n0 [$ns node]
set n1 [$ns node]

$ns duplex-link $n0 $n1 1Mb 10ms DropTail

set tcp [new Agent/TCP]
$ns attach-agent $n0 $tcp

set sink [new Agent/TCPSink]
$ns attach-agent $n1 $sink  

$ns connect $tcp $sink

set ftp [new Application/FTP]
$ftp attach-agent $tcp

set filesize [expr 10*1024*1024]
$ns at 0.0 "$ftp send $filesize"

proc finish {}
{            
global ns namfile tracefile        
$ns flush-trace      
close $namfile      
close $tracefile        
set awkCode
{  
BEGIN{}  
{
if ($1 == "r" && $4 == 1 && $6 > 1500)
{
count = count + $6 - ($6 % 1500);
print $2, count >> "ex_02.data";
}  
}  
 END{}
}        
exec awk $awkCode ex_02.tr        
exec nam ex_02.nam &        
exec xgraph -bb -tk -x Time -y Bytes ex_02.data -bg white &        
exit 0
 }

$ns at 100.0 "finish"
$ns run

Program No 9:

Simulate a network which will create congestion in the network. With the trace file created, identify the points at which congestion occurs by writing sed/awk scripts. Also write a mechanism to correct/control the congestion.

TCL Script:

set ns [new Simulator]
set namfile [open 9a.nam w]
$ns namtrace-all $namfile

set tracefile [open 9a.tr w]
$ns trace-all $tracefile    
Agent/TCP set packetSize_ 1460

set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
set n6 [$ns node]
set n7 [$ns node]

$n1 color blue
$n1 shape box
$n0 color red

$ns duplex-link $n0 $n3 2Mb 10ms DropTail
$ns duplex-link-op $n0 $n3 orient right-down
$ns duplex-link $n1 $n3 2Mb 10ms DropTail
$ns duplex-link-op $n1 $n3 orient right
$ns duplex-link $n2 $n3 2Mb 10ms DropTail
$ns duplex-link-op $n2 $n3 orient right-up
$ns duplex-link $n3 $n4 2Mb 10ms DropTail
$ns duplex-link-op $n3 $n4 orient right
$ns duplex-link $n4 $n5 2Mb 10ms DropTail
$ns duplex-link-op $n4 $n5 orient right-up
$ns duplex-link $n4 $n6 2Mb 10ms DropTail
$ns duplex-link-op $n4 $n6 orient right
$ns duplex-link $n4 $n7 2Mb 10ms DropTail
$ns duplex-link-op $n4 $n7 orient right-down

set tcp1 [new Agent/TCP/Newreno]
$ns attach-agent $n0 $tcp1

set sink1 [new Agent/TCPSink]
$ns attach-agent $n5 $sink1  
$ns connect $tcp1 $sink1

set udp1 [new Agent/UDP]
$ns attach-agent $n1 $udp1
set null1 [new Agent/Null]
$ns attach-agent $n6 $null1  
$ns connect $udp1 $null1

set udp2 [new Agent/UDP]
$ns attach-agent $n2 $udp2
set null2 [new Agent/Null]
$ns attach-agent $n7 $null2  
$ns connect $udp2 $null2

set ftp1 [new Application/FTP]
$ftp1 attach-agent $tcp1

set cbr1 [new Application/Traffic/CBR]
$cbr1 set packetSize_ 500
$cbr1 set interval_ 0.005
$cbr1 attach-agent $udp1

set cbr2 [new Application/Traffic/CBR]
$cbr2 set packetSize_ 500
$cbr2 set interval_ 0.005
$cbr2 attach-agent $udp2

$tcp1 set class_ 1
$ns color 1 Blue

$udp1 set class_
2 $ns color 2 Red

$udp2 set class_ 3
$ns color 3 Green

set filesize [expr 4*1024*1024]
$ns at 0.0 "$ftp1 send $filesize"

$ns at 0.0 "$cbr1 start"
$ns at 9.0 "$cbr1 stop"

$ns at 0.0 "$ftp1 start"
$ns at 9.0 "$ftp1 stop"

$ns at 0.0 "$cbr2 start"
$ns at 9.0 "$cbr2 stop"

proc finish {} {    
global ns namfile tracefile
$ns flush-trace close
$namfile close
$tracefile set awkCode
{
BEGIN{}
{
if($1 == "d" && $6 > 1000){
count_bytes = count_bytes + $6 - ($6 % 1000);
print $2,count_bytes >> "9a.data";
}
} END{}
} exec awk $awkCode 9a.tr
exec nam 9a.nam &
exec xgraph -bb -tk -x Time -x Bytes 9a.data -bg white &
exit 0 }

$ns at 100.0 "finish"
$ns run

Note:- Initially run the above program. That creats the congestion. Then, update the line as follows:
set tcp1 [new Agent/TCP/Newreno] and also for tcp2, tcp3. This provides the congestion control.

Program No 8

Simulate a wired network and demonstrate Distance Vector Routing algorithm

TCL Script:

set ns [new Simulator]
set namfile [open ex_08.nam w]
$ns namtrace-all $namfile

set tracefile [open ex_08.tr w]
$ns trace-all $tracefile    

set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]

$ns duplex-link $n0 $n1 10Mb 1ms DropTail
$ns duplex-link-op $n0 $n1 orient right
$ns duplex-link $n1 $n3 10Mb 1ms DropTail
$ns duplex-link-op $n1 $n3 orient right
$ns duplex-link $n1 $n2 10Mb 1ms DropTail
$ns duplex-link-op $n1 $n2 orient right-up
$ns duplex-link $n2 $n3 10Mb 1ms DropTail
$ns duplex-link-op $n2 $n3 orient right-down

set udp [new Agent/UDP]
$ns attach-agent $n0 $udp

set null [new Agent/Null]
$ns attach-agent $n3 $null

$ns connect $udp $null

set cbr [new Application/Traffic/CBR]
$cbr set packetsize_ 500
$cbr set interval_ 0.005
$cbr attach-agent $udp

$udp set class_ 1
$ns color 1 Red

$ns rtmodel-at 1.0 down $n1 $n3
$ns rtmodel-at 2.0 up $n1 $n3

$ns rtproto DV

$ns at 0.0 "$cbr start"
$ns at 5.0 "$cbr stop"

proc finish {}
 {    
global ns namfile tracefile
$ns flush-trace close
$namfile close
$tracefile exec nam ex_08.nam &
exit 0
}
$ns at 5.0 "finish"
$ns run

Program no 1.

Write a TCL script to simulate the network described below  Consider a small network with five nodes n0, n1, n2, n3, n4, forming a star topology. The node n4 is at the center. Node n0 is a TCP source, which transmits packets to node n3 (a TCP sink) through the node n4. Node n1 is another traffic source, and sends UDP packets to node n2 through n4. The duration of the simulation time is 10 seconds.

TCL Script:

set ns [new Simulator]
set namfile [open ex_01.nam w]
$ns namtrace-all $namfile

set tracefile [open ex_01.tr w]  
$ns trace-all $tracefile

set n0 [$ns node] 
set n1 [$ns node] 
set n2 [$ns node] 
set n3 [$ns node] 
set n4 [$ns node]

$ns duplex-link $n0 $n4 1Mb 10ms DropTail 
$ns duplex-link $n1 $n4 1Mb 10ms DropTail 
$ns duplex-link $n4 $n3 1Mb 10ms DropTail 
$ns duplex-link $n4 $n2 1Mb 10ms DropTail

set tcp [new Agent/TCP] 
$ns attach-agent $n0 $tcp 

set sink [new Agent/TCPSink] 
$ns attach-agent $n3 $sink  

$ns connect $tcp $sink

set ftp [new Application/FTP] 
$ftp attach-agent $tcp

set udp [new Agent/UDP] 
$ns attach-agent $n1 $udp

set null [new Agent/Null] 
$ns attach-agent $n2 $null

$ns connect $udp $null

$udp set class_ 1 
$ns color 1 Blue

$tcp set class_ 2 
$ns color 2 Red

set cbr [new Application/Traffic/CBR] 
$cbr set packetsize_ 500 
$cbr set interval_ 0.005 
$cbr attach-agent $udp

$ns at 0.0 "$cbr start" 
$ns at 0.0 "$ftp start" 
$ns at 9.0 "$cbr stop" 
$ns at 9.0 "$ftp stop"

proc finish {} {              
global ns namfile tracefile          
$ns flush-trace        
close $namfile        
close $tracefile        
exec nam ex_01.nam &        
exit 0 
}

$ns at 10.0 "finish" 
$ns run


Saturday, September 17, 2016

1. a. Constructor overloading and Method overloading

/*Write a JAVA Program to demonstrate Constructor overloading and Method overloading*/


// ArithmeticMain.java
import java.util.*;
import java.lang.Math;
import java.io.*;
class Arithmetic
  {
int a,b;
Scanner s1=new Scanner(System.in);
Arithmetic()
{
System.out.println("Enter any 2 integers");
a=s1.nextInt();
b=s1.nextInt();
}
void display()
{
System.out.println("\nAddition \t= "+(a+b));
System.out.println("Substraction \t= "+(a-b));
System.out.println("Multiplication \t= "+(a*b));
System.out.println("Division \t= "+(a/b));
}
Arithmetic (float a1, float b1)
{
System.out.println("\nAddition \t= "+(a1+b1));
System.out.println("Substraction \t= "+(a1-b1));
System.out.println("Multiplication \t= "+(a1*b1));
System.out.println("Division \t= "+(a1/b1));
}
void display(int x)
{
System.out.println("square of "+x+" is "+(x*x));
}
   }
class ArithmeticMain
  {
public static void main(String args[])
{
Scanner s1=new Scanner(System.in);
System.out.println("Arithmetic operation on integer\n ===================");
Arithmetic a=new Arithmetic();
a.display();
System.out.println("\n\nAirthmetic operation on float\n==================");
System.out.println("Enter any 2 float value");
float a1=s1.nextFloat();
float a2=s1.nextFloat();
Arithmetic arth1=new Arithmetic(a1,a2);
System.out.println("\nEnter no to find square\n========================");
int x=s1.nextInt();
a.display(x);
}
  }

1 b. Inner class and demonstrate its Access protection

         /* Write a JAVA Program to implement Inner class and demonstrate its      Access protection.*/
          

          //AccessMain.java
          import java.io.*;
          class  outer
          {
          int  outdata = 10;
          
          void  display()
          {
          inner  inobj = new  inner();
          System.out.println("Accessing from outer class");
          System.out.println("The value of outdata is " +outdata);
          System.out.println("The value of indata is "   +inobj.indata);
          }
           
         class  inner
         {
         int  indata = 20;
         void  inmethod()
         {
               System.out.println("Accessing from inner class");
               System.out.println("The sum of indata & outdata is " +(outdata + indata));
         }
         }
         }
                 
        class  AccessMain
       {
        public  static  void  main(String  args[])
        {
          outer  outobj  = new  outer();
          outobj.display();
          outer.inner  inobj1 = outobj.new  inner();
          inobj1.inmethod();
         }
        }

2. Program in Java for String handling which performs the following: i) Checks the capacity of StringBuffer objects. ii) Reverses the contents of a string given on console and converts the resultant string in upper case. iii) Reads a string from console and appends it to the resultant string of ii.

/*Write a program in Java for String handling which performs the following: i) Checks the capacity of StringBuffer objects. ii) Reverses the contents of a string given on console and converts the resultant       string in upper case. iii) Reads a string from console and appends it to the resultant string of ii.*/

// StringHandler.java

import java.io.*;
class StringHandler
  {
    public static void main(String s[]) throws IOException
      {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s1,s2,s3,s4,s5;
int i,l;
s2=" ";
System.out.println("\nEnter the string : \t\t\t");
System.out.println("\n=======================\t");
s1=br.readLine();
System.out.println("\nEntered string is : \t\t\t "+s1);
System.out.println("\nlength of the string is : \t\t "+s1.length());
StringBuffer sb=new StringBuffer(s1);
System.out.println("\nCapacity of string buffer : \t\t "+sb.capacity());
l=s1.length();
if(l==0)
 System.out.println("\nString is empty cannot be reversed");
else
 {
    for(i=l-1;i>=0;i--)
{
 s2=s2+s1.charAt(i);
}
    System.out.println("\nThe reversed string is : \t\t"+s2);
    s3=s2.toUpperCase();
        System.out.println("\nUpper case of reverse string is : \t"+s3);
      System.out.println("\nEnter a new string : \t");
    System.out.println("\n=======================\t");
    s4=br.readLine();
    System.out.println("\nThe entered new string is : \t\t "+s4);
    StringBuffer sb1=new StringBuffer(s4);
    s5=sb1.append(s3).toString();
    System.out.println("\nThe appended string is : \t\t "+s5);

 }
      }
  }

3. a. Demonstrate Inheritance

/* Write a JAVA Program to demonstrate Inheritance.*/

// InheritMain.java

class SuperClass
{
int a,b;
SuperClass(int x,int y)
{
a=x;
b=y;
}
void show()
{
System.out.println("In Super Class");
System.out.println(" A and B are " + a + " " + b);
}
}
class SubClass extends SuperClass
{
int ans;
int add;
SubClass(int a,int b,int c)
{
super(a,b);
ans=c;
}
void show()
{
System.out.println("In Sub Class");
System.out.println("C value is: " + ans);
super.show();
add=a+b+ans;
System.out.println("Addition of A B and C :" + add);
}
}
class InheritMain
{
public static void main(String args[])
{
SubClass ob=new SubClass(10,20,30);
ob.show();
}
}

3.b. Implementation of multiple inheritance using interfaces to calculate the area of a rectangle and triangle

/*Simple Program on Java for the implementation of multiple inheritance using interfaces to calculate the area of a rectangle and triangle.*/


// InterfaceMain.java

import java.io.*;
interface area
  {
    float compute(float x, float y);
  }

class rectangle
  {
    public float compute(float x, float y)
      {
        return (x*y);
      }
  }

class triangle
  {
    public float compute(float x, float y)
      {
        return (x*y/2);
      }
  }

class result extends rectangle implements area
  {
    public float compute(float x, float y)
      {
        return (x*y);
      }
  }

class result1 extends triangle implements area
  {
    public float compute(float x, float y)
      {
        return (x*y/2);
      }
  }

class InterfaceMain
  {
    public static void main(String args[])
      {
        result rect = new result();
        result1 tri = new result1();
        area a;
        a = rect;
        System.out.println("\nArea of rectangle = " + a.compute(10,20));
        a = tri;
        System.out.println("\nArea of triangle  = " +a.compute(10,2));
      }
  }

4. Bank Statements (Account, LessBalanceException)

/*Write a JAVA program which has i. A Class called Account that creates account with 500Rs minimum balance, a deposit()    method to deposit amount, a withdraw() method to withdraw amount and also throws    LessBalanceException if an account holder tries to withdraw money which makes the    balance becomes less than 500Rs. ii. A Class called LessBalanceException which returns the statement that says withdraws    amount (Rs) is not valid. iii. A Class which creates 2 accounts, both account deposit money and one account    tries to withdraw more money which generates a LessBalanceException take    appropriate action for the same.*/

import java.io.*;
import java.lang.*;
class LessBalanceException extends Exception
{
LessBalanceException(double amt)
{
System.out.println("Withdrawing "+amt+" is invlaid");
}
}
class Account
{
static int count=0;
int accno;
double bal;
String name;
Account(double bal,String n,int accno)
{
System.out.println("\nNew Account opened....!!");
this.bal=bal;
count++;
System.out.println("Account Holder Name : " + n);
name=n;
System.out.println("Your Account Number is : "+accno);
this.accno=accno;
System.out.println("Total number of accounts : "+count);

}
void deposit(double amt)
{
System.out.println("Availabe Balance : "+bal);
bal=bal+amt;
System.out.println("Rs. : "+amt+" /- Created");
System.out.println("Balance : "+bal);
}
void withdraw(double amt) throws LessBalanceException
{
System.out.println("\nAvailabe Balance : "+bal);
bal-=amt;
if(bal<500)
{
bal+=amt;
throw new LessBalanceException(amt);
}
System.out.println("Rs. : "+amt+ "/-Debited");
System.out.println("Balacne : "+bal);
}
void balance()
{
System.out.println("\n***************Customer information****************");
System.out.println("============================================");
System.out.println("Customer Name : "+name);
System.out.println("Account Number : "+accno);
System.out.println("Balance : "+bal);
}
}
class AccountDemo
{
static int i=0;
public static void main(String argv[]) throws IOException
{
Account ob[]=new Account[10];
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
double amt;
String name;
int ch,accno,k;
boolean t=false;
while(true)
{
System.out.println("\n******* Bank Transaction *********");
System.out.println("1.Open new Account\n2.Deposit");
System.out.println("3.Withdraw\n4.Balance\n5.Exit");
System.out.print("Enter your choice : ");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
System.out.println("Opening New Account : ");
System.out.print("Enter your name : ");
name=br.readLine();
System.out.print("\nEnter Account Number : ");
accno=Integer.parseInt(br.readLine());
System.out.print("\nEnter initial amount(to be >=500) : ");
amt=Double.parseDouble(br.readLine());
if(amt<500)
System.out.println("You cannot create an account with less than Rs.500/-");
else
{
ob[i]=new Account(amt,name,accno);
i++;
}
break;

case 2:
System.out.print("\nEnter Account number : ");
accno=Integer.parseInt(br.readLine());
for(k=0;k<i;k++)
if(accno==ob[k].accno)
{
t=true;
break;
}

if(t)
{
System.out.print("\nEnter the Amount for Deposit : ");
amt=Double.parseDouble(br.readLine());
ob[k].deposit(amt);
}
else
System.out.println("Invalid Account Number...!!!");
t=false;
break;

case 3:
System.out.print("\nEnter Account number : ");
accno=Integer.parseInt(br.readLine());
for(k=0;k<i;k++)
if(accno==ob[k].accno)
{
t=true;
break;
}

if(t)
{
System.out.print("\nEnter the Amount for Withdraw : ");
amt=Double.parseDouble(br.readLine());
try
{
ob[k].withdraw(amt);
}
catch(LessBalanceException e)
{}
}
else
System.out.println("Invalid Account Number...!!!");
t=false;
break;

case 4:
System.out.print("\nEnter Account number : ");
accno=Integer.parseInt(br.readLine());
for(k=0;k<i;k++)
if(accno==ob[k].accno)
{
t=true;
break;
}

if(t)
{
//System.out.println(accno +" asdfsdf " +ob[k].accno);
ob[k].balance();
}
else
System.out.println("Invalid Account Number...!!!");
t=false;
break;

case 5:
System.exit(1);
default: System.out.println("Invalid Choice !!!");
}
}
}
}

5. Synchronized Threads, which demonstrates Producer Consumer concept.

/*Write a JAVA program using Synchronized Threads, which demonstrates     Producer Consumer concept.*/

/* Restaurant.java */

import java.io.*;

class Order
    {
        private static int i=0;
        private int count=i++;
        public  Order()
            {
                if(count==10)
                    {
                        System.out.println("\n out of food stock");
                        System.exit(0);
                    }      
            }
        public String toString()
            {
                return "Order" +count;
            }
    }


class waitperson extends Thread
    {
        private Restaurant rest;
        public waitperson(Restaurant r)
            {
rest = r;
start();
            }
        public void run()
            {
while(rest.order==null)
synchronized(this)
   {
       try
           {
wait();
           }
       catch(InterruptedException e)
           {
throw new RuntimeException(e);
           }
       System.out.println("wait person got"+rest.order);
       rest.order=null;
                    }
           }
    }


class chef extends Thread
    {
        private Restaurant rest;
        private waitperson wp;
        public chef(Restaurant r,waitperson w)
            {
rest = r;
wp = w;
start();
            }
        public void run()
            {
while(true)
   {
       if(rest.order==null)
           {
rest.order = new Order();
System.out.println("order up");
synchronized(wp)
  {
       wp.notify();
   }
           }
       try
           {
sleep(1000);
           }
       catch(InterruptedException e)
           {
throw new RuntimeException(e);
           }
    }
            }
   }




class Restaurant
    {
        Order order;
        public static void main(String args[])
            {
Restaurant rest = new Restaurant();
waitperson wp = new waitperson(rest);
chef ch = new chef(rest,wp);
            }
    }

6. JAVA program to implement a Queue using user defined Exception Handling

import java.io.*;       
public class MainClass    
{      
public static void main(String args[])      
{         
Queue queue=new Queue(5);           
try            
{              
queue.push(1);               
queue.push(2);              
queue.push(3);             
queue.push(4);               
queue.push(5);
//queue.push(6);          
queue.display();               
queue.pop();               
queue.pop();               
queue.pop();               
queue.pop();               
queue.pop();               
queue.pop();            
}
catch(QueueException e)           
{              
e.Error();            
}
catch(ArrayIndexOutOfBoundsException e)          
{     
System.out.println("Queue is empty");         
}          
}  
}

/*Queue.java*/
import java.io.*;          
public class Queue         
{      
int front;      
int  rear;      
int size;      
int Array[];     
public Queue(int s)    
 {         
front=0;         
rear=-1;         
size=s;        
Array=new int[size];      
System.out.println("Inserted : " + ele);     
}
public void push(int ele)throws QueueException     
{        
if(rear==size-1)             
throw new QueueException();        
else          
{             
Array[++rear]=ele;           
}     
}
   public void pop()     
{        
if(rear==-1)          
{              
throw new ArrayIndexOutOfBoundsException();          
}        
System.out.println("Deleted : " + ++front);        
if(front>rear)          
{                 
front=0;                 
rear=-1;           
}     
}
public void display()     
{        
System.out.println("elements in queue");        
for(int i=front;i<=rear;i++)        
System.out.println(Array[i]+" ");        
System.out.println();     }}
      /*QueueException*/            
import java.io.*;       
public class QueueException extends Exception        
{        
public void Error()      
 {          
System.out.println("Queue is full");
}
}

7. Complete the following: a. Create a package named shape. b. Create some classes in the package representing some common shapes like Square, Triangle, and Circle. c. Import and compile these classes in other program.

/*Mainclass.java*/
import shape.Square;
import shape.Triangle;
import shape.Circle;
public class MainClass
{
public static void main(String args[])
{
Square square=new Square();
Triangle triangle=new Triangle();
Circle circle=new Circle();
square.getData((float)5.5);
System.out.println("The area of square is:"+square.area());
triangle.getData((double)20.56,(double)23.90);
System.out.println("The area of triangle is:"+triangle.area());
circle.getData((double)5.5);
System.out.println("The area of circle is:"+circle.area());
}
}

/*Square.java*/
package shape;
public class Square
{
float side;
public void getData(float temp)
{
side=temp;
}
public double area()
{
return (side*side);
}
}


/*Triangle.java*/
package shape;
public class Triangle
{
double base;
double height;
public void getData(double temp1,double temp2)
{
base=temp1;
height=temp2;
}
public double area()
{
return ((1.0/2.0)*(base*height));
}
}


/*Circle.java*/
package shape;
public class Circle
{
double radius;
double height;
public void getData(double temp)
{
radius=temp;
}
public double area()
{
return ((3.1427*(2.0*radius)*(2.0*radius))/4.00);
}
}

8. Write a JAVA Program a. Create an enumeration Day of Week with seven values SUNDAY through SATURDAY. Add a method is Workday( ) to the DayofWeek class that returns true if the value on which it is called is MONDAY through FRIDAY. For example, the call DayOfWeek.SUNDAY.isWorkDay ( ) returns false.

import java.io.*;
class Enumaration
  {
     public enum DayOfWeek
         {
                     MONDAY(1),TUESDAY(2),WEDNESDAY(3),THURSDAY(4),FRIDAY(5),
SATURDAY(6),SUNDAY(7);
                     public int val;
                     DayOfWeek(int val)
                         {
                                 this.val=val;
                         }
                     boolean isWorkDay()
                         {
                                 if(val<6)
                                             return true;
                                 else
                                             return false;
                         }
         }
    public static void main(String[] args)
         {
                     DayOfWeek Day;
                     System.out.println(" verfication of sunday(isWorkDay())");  
                     System.out.println(DayOfWeek.SUNDAY.isWorkDay());
                     System.out.println(" verfication of Wednesday(isWorkDay())");  
                     System.out.println(DayOfWeek.WEDNESDAY.isWorkDay());
         }

  }