Вы находитесь на странице: 1из 63

NS2 simulation using Link State routing protocol

set ns [new Simulator]

set nf [open out.nam w]


$ns namtrace-all $nf

set tr [open out.tr w]


$ns trace-all $tr

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

set n0 [$ns node]


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

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


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

$ns duplex-link-op $n0 $n1 orient right-down


$ns duplex-link-op $n1 $n3 orient right
$ns duplex-link-op $n2 $n1 orient right-up

set tcp [new Agent/TCP]


$ns attach-agent $n0 $tcp

set ftp [new Application/FTP]


$ftp attach-agent $tcp

set sink [new Agent/TCPSink]


$ns attach-agent $n3 $sink

set udp [new Agent/UDP]


$ns attach-agent $n2 $udp

set cbr [new Application/Traffic/CBR]


$cbr attach-agent $udp

set null [new Agent/Null]


$ns attach-agent $n3 $null

$ns connect $tcp $sink


$ns connect $udp $null

$ns rtmodel-at 1.0 down $n1 $n3


$ns rtmodel-at 2.0 up $n1 $n3
$ns rtproto LS

$ns at 0.0 "$ftp start"


$ns at 0.0 "$cbr start"

$ns at 5.0 "finish"

$ns run

NS2 simulation using Distance Vector routing protocol


set ns [new Simulator]

set nf [open out.nam w]


$ns namtrace-all $nf

set tr [open out.tr w]


$ns trace-all $tr

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

set n0 [$ns node]


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

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


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

$ns duplex-link-op $n0 $n1 orient right-down


$ns duplex-link-op $n1 $n3 orient right
$ns duplex-link-op $n2 $n1 orient right-up

set tcp [new Agent/TCP]


$ns attach-agent $n0 $tcp

set ftp [new Application/FTP]


$ftp attach-agent $tcp

set sink [new Agent/TCPSink]


$ns attach-agent $n3 $sink

set udp [new Agent/UDP]


$ns attach-agent $n2 $udp

set cbr [new Application/Traffic/CBR]


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

$ns connect $tcp $sink


$ns connect $udp $null

$ns rtmodel-at 1.0 down $n1 $n3


$ns rtmodel-at 2.0 up $n1 $n3

$ns rtproto DV

$ns at 0.0 "$ftp start"


$ns at 0.0 "$cbr start"

$ns at 5.0 "finish"

$ns run

NS2 simulation with TCP and UDP packets


set ns [new Simulator]

set nf [open out.nam w]


$ns namtrace-all $nf

set nt [open out.tr w]


$ns trace-all $nt

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

set h1 [$ns node]


set r1 [$ns node]
set h2 [$ns node]
set h3 [$ns node]
set r2 [$ns node]
set h4 [$ns node]

$ns duplex-link $h1 $r1 10Mb 20ms DropTail


$ns duplex-link $h2 $r1 10Mb 20ms DropTail
$ns duplex-link $r1 $r2 1.5Mb 20ms DropTail
$ns duplex-link $r2 $h3 10Mb 20ms DropTail
$ns duplex-link $r2 $h4 5Mb 20ms DropTail

$ns duplex-link-op $h1 $r1 orient right-down


$ns duplex-link-op $h2 $r1 orient right-up
$ns duplex-link-op $r1 $r2 orient right
$ns duplex-link-op $r2 $h3 orient right-up
$ns duplex-link-op $r2 $h4 orient right-down

set udp [new Agent/UDP]


$ns attach-agent $h2 $udp

set cbr [new Application/Traffic/CBR]


#$cbr set interval_ 0.0005
$cbr attach-agent $udp

set null [new Agent/Null]


$ns attach-agent $h4 $null

set tcp [new Agent/TCP]


$ns attach-agent $h1 $tcp

set ftp [new Application/FTP]


#$ftp set interval_ 0.0005
$ftp attach-agent $tcp

set sink [new Agent/TCPSink]


$ns attach-agent $h3 $sink

$ns connect $udp $null


$ns connect $tcp $sink

$ns at 0.0 "$cbr start"


$ns at 0.0 "$ftp start"
$ns at 10.0 "finish"

$ns run

NS2 simulation for UDP packets in a network


set ns [new Simulator]

set nf [open out.nam w]


$ns namtrace-all $nf

set nt [open out.tr w]


$ns trace-all $nt

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

set n0 [$ns node]


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

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


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

$ns duplex-link-op $n0 $n1 orient right-up


$ns duplex-link-op $n0 $n2 orient right

set udp0 [new Agent/UDP]


$ns attach-agent $n0 $udp0

set cbr0 [new Application/Traffic/CBR]


$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0

set null0 [new Agent/Null]


$ns attach-agent $n2 $null0

$ns connect $udp0 $null0

$ns at 0.5 "$cbr0 start"


$ns at 4.5 "$cbr0 stop"

$ns run

NS2 simulation for TCP packets in a network


set ns [new Simulator]

set nf [open out.nam w]


$ns namtrace-all $nf

set nt [open out.tr w]


$ns trace-all $nt

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

set n0 [$ns node]


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

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


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

$ns duplex-link-op $n0 $n1 orient right-down


$ns duplex-link-op $n1 $n2 orient right
$ns duplex-link-op $n3 $n1 orient right-up

set tcp [new Agent/TCP]


$ns attach-agent $n0 $tcp

set ftp [new Application/FTP]


#$ftp set packet_size_ 4.5Mb
$ftp set interval_ 0.05
$ftp attach-agent $tcp

set sink [new Agent/TCPSink]


$ns attach-agent $n2 $sink

$ns connect $tcp $sink

$ns at 0.3 "$ftp start"


$ns at 3.0 "finish"

$ns run

Simple Script Explanation


To start we have to set a few variables like simulator object, trace file and object, nam file and object.

set ns [new Simulator]

This would set the simulator with the simulator object which is to be accessed in the script.

set nf [open out.nam w]


$ns namtrace-all $nf

This would set the nam file (network animation file) with the object and connect to ns.

set tr [open out.tr w]


$ns trace-all $tr

This would set the trace file and would connect to the simulator. The trace file is required to analyze the
various packets which are send, received type of application used etc.

set n0 [$ns node]

Now the nodes could be set as many as you want, for loop could be used if many nodes are to be made.

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

The connection for the various nodes with each other with the band width and rate.

$ns duplex-link-op $n0 $n1 orient right-up

The nodes could be given with various orientations with this option. right, right-up and right down could be
used depending on the node.

For the application like tcp or udp to run, we need to set two agents and the application which should run
in between.

When using tcp, we have ftp as the application and tcpsink as the end agent. connection must be made
between tcp and tcpsink, same in udp with cbr and null respectively.

set tcp [new Agent/TCP]


$ns attach-agent $n0 $tcp

This would make a tcp agent and connect it with the node.
set ftp [new Application/FTP]
$ftp attach-agent $tcp

Now the ftp is connected with the tcp

set agent [new Agent/TCPSink]


$ns attach-agent $n3 $sink

Now the tcpsink is set to a node where the tcp packets are received.

The tcp and sink (agents) needs to be connected, such that the network flows.

$ns connect $tcp $sink


Same for udp

set udp [new Agent/UDP]


$ns attach-agent $n2 $udp

set cbr [new Application/Traffic/CBR]


$cbr attach-agent $udp

set null [new Agent/Null]


$ns attach-agent $n3 $null

$ns connect $udp $null

We can use the routing protocols in the simulator using rtmodel (to break the link), rtproto (to use the
protocol)

$ns rtmodel-at 1.0 down $n1 $n2


$ns rtmodel-at 2.0 up $n1 $n3

For distance vector we could use

$ns rtproto DV

For linkstate we could use

$ns rtproto LS

When all this is done the tcp could be started at some point and could call the finish procedure to end.

The out.tr file is used to trace the packets. A normal awk command could be used to analyse the packets.

$ns at 0.0 "$ftp start"


$ns at 0.0 "$cbr start"

$ns at 5.0 "finish"

We could also stop the tcp or udp in between using stop instead of start, hence nam out.nam need to be
used if finish is not used.

run is used to run the whole simulation.

$ns run
The file should be saved in .tcl format and should use ns filename.tcl to run

Simple NS2 Program

#Create a simulator object


set ns [new Simulator]

#Define different colors for data flows


$ns color 1 Blue
$ns color 2 Red

#Open the nam trace file


set nf [open out.nam w]
$ns namtrace-all $nf

#Define a ‘finish’ procedure


proc finish {} {
global ns nf
$ns flush-trace
#Close the trace file
close $nf
#Execute nam on the trace file
exec nam out.nam &
exit 0
}

#Create four nodes


#for {set i 1}{i<= 4}{incr i}{
#set n($i) [$ns node]
#}
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]

#Create links between the nodes


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

$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
$ns duplex-link-op $n3 $n4 orient right-up
$ns duplex-link-op $n3 $n5 orient right-down

#Monitor the queue for the link between node 2 and node 3
$ns duplex-link-op $n2 $n3 queuePos 0.5

#Create a UDP agent and attach it to node n0


set udp0 [new Agent/UDP]
$udp0 set class_ 1
$ns attach-agent $n0 $udp0

# Create a CBR traffic source and attach it to udp0


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

#Create a Null agent (a traffic sink) and attach it to node n3


set null0 [new Agent/Null]
$ns attach-agent $n5 $null0
#Connect the traffic sources with the traffic sink
$ns connect $udp0 $null0

#Create a TCP agent and attach it to node n1


set tcp0 [new Agent/TCP]
$tcp0 set class_ 2
$ns attach-agent $n1 $tcp0

# Create a FTP traffic source and attach it to tcp0


set ftp0 [new Application/FTP]
$ftp0 set type_ FTP
$ftp0 attach-agent $tcp0

#Create a TCPSink (a traffic sink) and attach it to node n3


set null1 [new Agent/TCPSink]
$ns attach-agent $n4 $null1

#Connect the traffic sources with the traffic sink


$ns connect $tcp0 $null1

#Schedule events for the CBR agents


$ns at 0.5 “$cbr0 start”
$ns at 1.0 “$ftp0 start”
$ns at 4.0 “$ftp0 stop”
$ns at 4.5 “$cbr0 stop”
#Call the finish procedure after 5 seconds of simulation time
$ns at 5.0 “finish”

#Run the simulation


$ns run
Static Routing (NS2)
set ns [new Simulator]

#Define different colors for data flows (for NAM)


$ns color 1 Blue
$ns color 2 Red

#Open the Trace file


set file1 [open out.tr w]
$ns trace-all $file1

#Open the NAM trace file


set file2 [open out.nam w]
$ns namtrace-all $file2

#Define a ‘finish’ procedure


proc finish {} {
global ns file1 file2
$ns flush-trace
close $file1
close $file2
exec nam out.nam &
exit 0
}
#Create six nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]

#Create links between the nodes


$ns duplex-link $n0 $n1 0.3Mb 10ms DropTail
$ns duplex-link $n1 $n2 0.3Mb 10ms DropTail
$ns duplex-link $n2 $n3 0.3Mb 10ms DropTail
$ns duplex-link $n1 $n4 0.3Mb 10ms DropTail
$ns duplex-link $n3 $n5 0.5Mb 10ms DropTail
$ns duplex-link $n4 $n5 0.5Mb 10ms DropTail

#Give node position (for NAM)


$ns duplex-link-op $n0 $n1 orient right
$ns duplex-link-op $n1 $n2 orient right
$ns duplex-link-op $n2 $n3 orient up
$ns duplex-link-op $n1 $n4 orient up-left
$ns duplex-link-op $n3 $n5 orient left-up
$ns duplex-link-op $n4 $n5 orient right-up

#Setup a TCP connection


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

#Setup a FTP over TCP connection


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

$ns rtmodel-at 1.0 down $n1 $n4


$ns rtmodel-at 4.5 up $n1 $n4

$ns at 0.1 “$ftp start”


$ns at 6.0 “finish”
$ns run
Dynamic Routing (NS2)
set ns [new Simulator]

#Define different colors for data flows (for NAM)


$ns color 1 Blue
$ns color 2 Red

$ns rtproto DV
#Open the Trace file
set file1 [open out.tr w]
$ns trace-all $file1

#Open the NAM trace file


set file2 [open out.nam w]
$ns namtrace-all $file2

#Define a ‘finish’ procedure


proc finish {} {
global ns file1 file2
$ns flush-trace
close $file1
close $file2
exec nam out.nam &
exit 0
}
#Create six nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
#Create links between the nodes
$ns duplex-link $n0 $n1 0.3Mb 10ms DropTail
$ns duplex-link $n1 $n2 0.3Mb 10ms DropTail
$ns duplex-link $n2 $n3 0.3Mb 10ms DropTail
$ns duplex-link $n1 $n4 0.3Mb 10ms DropTail
$ns duplex-link $n3 $n5 0.5Mb 10ms DropTail
$ns duplex-link $n4 $n5 0.5Mb 10ms DropTail

#Give node position (for NAM)


$ns duplex-link-op $n0 $n1 orient right
$ns duplex-link-op $n1 $n2 orient right
$ns duplex-link-op $n2 $n3 orient up
$ns duplex-link-op $n1 $n4 orient up-left
$ns duplex-link-op $n3 $n5 orient left-up
$ns duplex-link-op $n4 $n5 orient right-up

#Setup a TCP connection


set tcp [new Agent/TCP/Newreno]
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink/DelAck]
$ns attach-agent $n5 $sink
$ns connect $tcp $sink
$tcp set fid_ 1

#Setup a FTP over TCP connection


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

$ns rtmodel-at 1.0 down $n1 $n4


$ns rtmodel-at 4.5 up $n1 $n4

$ns at 0.1 “$ftp start”


$ns at 6.0 “finish”
$ns run
Stop & Wait (NS2)
set ns [new Simulator]
$ns color 1 Blue
set nf [open out.nam w]
$ns namtrace-all $nf

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

set n0 [$ns node]


set n1 [$ns node]
$ns at 0.0 “$n0 label \” sender \” ”
$ns at 0.0 “$n1 label \”receiver\” ”

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


$ns duplex-link-op $n0 $n1 orient right

set tcp [new Agent/TCP]


$ns attach-agent $n0 $tcp
$tcp set fid_ 1
$tcp set window_ 1
$tcp set maxcwnd_ 1
$ns add-agent-trace $tcp tcp
$ns monitor-agent-trace $tcp
set tcpsink [new Agent/TCPSink]
$ns attach-agent $n1 $tcpsink
$ns connect $tcp $tcpsink
set ftp [new Application/FTP]
$ftp attach-agent $tcp

$ns at 0.5 “$ftp start”


$ns at 3.0 “$ns detach-agent $n0 $tcp ; $ns detach-agent $n1 $tcpsink ”
$ns at 1.0 “$ns trace-annotate \”send packet 1\””
$ns at 1.4 “$ns trace-annotate \”recieve ack 1\””
$ns at 2.0 “$ns trace-annotate \”send packet 2\””
$ns at 2.5 “$ns trace-annotate \”receive ack 2\””
$ns at 3.2 “$ns trace-annotate \”send packet 3\””
$ns at 3.5 “$ns trace-annotate \”receive ack 3\””
$ns at 3.8 “$ns trace-annotate \”send packet 4\””
$ns at 4.0 “finish”
$ns run

#Aim : To monitor traffic for Ring topology using NS2


#***********************************************************************#

#Create a simulator object


set ns [new Simulator]

#Open the nam trace file


set nf [open out.nam w]
$ns namtrace-all $nf

#Define a 'finish' procedure


proc finish {} {
global ns nf
$ns flush-trace
#Close the trace file
close $nf
#Executenam on the trace file
exec nam out.nam &
exit0
}

#Create four nodes


set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
#Create links between the nodes
$ns duplex-link $n0 $n1 1Mb 10ms DropTail
$ns duplex-link $n1 $n2 1Mb 10ms DropTail
$ns duplex-link $n2 $n3 1Mb 10ms DropTail
$ns duplex-link $n3 $n4 1Mb 10ms DropTail
$ns duplex-link $n4 $n5 1Mb 10ms DropTail
$ns duplex-link $n5 $n0 1Mb 10ms DropTail

#Create a TCP agent and attach it to node n0


set tcp0 [new Agent/TCP]
$tcp0 set class_ 1
$ns attach-agent $n1 $tcp0
#Create a TCP Sink agent (a traffic sink) for TCP and attach it to node n3
set sink0 [new Agent/TCPSink]
$ns attach-agent $n3 $sink0
#Connect the traffic sources with the traffic sink
$ns connect $tcp0 $sink0

# Create a CBR traffic source and attach it to tcp0


set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.01
$cbr0 attach-agent $tcp0

#Schedule events for the CBR agents


$ns at 0.5 "$cbr0 start"
$ns at 4.5 "$cbr0 stop"

#Call the finish procedure after 5 seconds of simulation time


$ns at 5.0 "finish"

#Run the simulation


$ns run

#Aim : To monitor traffic for Mesh topology using NS2


#***********************************************************************#

#Create a simulator object


set ns [new Simulator]

#Open the nam trace file


set nf [open out.nam w]
$ns namtrace-all $nf

#Define a 'finish' procedure


proc finish {} {
global ns nf
$ns flush-trace
#Close the trace file
close $nf
#Executenam on the trace file
exec nam out.nam &
exit 0
}

#Create four nodes


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

#Create links between the nodes


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

#Create a TCP agent and attach it to node n0


set tcp0 [new Agent/TCP]
$tcp0 set class_ 1
$ns attach-agent $n1 $tcp0
#Create a TCP Sink agent (a traffic sink) for TCP and attach it to node n3
set sink0 [new Agent/TCPSink]
$ns attach-agent $n3 $sink0
#Connect the traffic sources with the traffic sink
$ns connect $tcp0 $sink0

# Create a CBR traffic source and attach it to tcp0


set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.01
$cbr0 attach-agent $tcp0

#Schedule events for the CBR agents


$ns at 0.5 "$cbr0 start"
$ns at 4.5 "$cbr0 stop"

#Call the finish procedure after 5 seconds of simulation time


$ns at 5.0 "finish"

#Run the simulation


$ns run

#Aim : To monitor traffic for Bus topology using NS2


#***********************************************************************#

#Create a simulator object


set ns [new Simulator]

#Open the nam trace file


set nf [open out.nam w]
$ns namtrace-all $nf

#Define a 'finish' procedure


proc finish {} {
global ns nf
$ns flush-trace
#Close the trace file
close $nf
#Executenam on the trace file
exec nam out.nam &
exit 0
}

#Create four nodes


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

#CreateLanbetween the nodes


set lan0 [$ns newLan "$n0 $n1 $n2 $n3 $n4" 0.5Mb 40ms LL Queue/DropTail MAC/Csma/Cd Ch
annel]

#Create a TCP agent and attach it to node n0


set tcp0 [new Agent/TCP]
$tcp0 set class_ 1
$ns attach-agent $n1 $tcp0
#Create a TCP Sink agent (a traffic sink) for TCP and attach it to node n3
set sink0 [new Agent/TCPSink]
$ns attach-agent $n3 $sink0
#Connect the traffic sources with the traffic sink
$ns connect $tcp0 $sink0

# Create a CBR traffic source and attach it to tcp0


set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.01
$cbr0 attach-agent $tcp0

#Schedule events for the CBR agents


$ns at 0.5 "$cbr0 start"
$ns at 4.5 "$cbr0 stop"

#Call the finish procedure after 5 seconds of simulation time


$ns at 5.0 "finish"

#Run the simulation


$ns run
set ns [new Simulator]

# There are several sources of TCP sharing a bottleneck link

# and a single destination. Their number is given by the paramter NodeNb

# S(1) ----

# . |

# . ---- ---- N -------- D(1)...D(NodeNb)

# . |

# S(NodeNb) ----

# Next file will contain the transfer time of different connections

set Out [open Out.ns w]

# Next file will contain the number of connections

set Conn [open Conn.tr w]

#Open the Trace file

set tf [open out.tr w]

$ns trace-all $tf

# We define three files that will be used to trace the queue size,

# the bandwidth and losses at the bottleneck.

set qsize [open queuesize.tr w]

set qbw [open queuebw.tr w]

set qlost [open queuelost.tr w]


# defining the topology

set N [$ns node]

set D [$ns node]

$ns duplex-link $N $D 2Mb 1ms DropTail

$ns queue-limit $N $D 3000

# Number of sources

set NodeNb 6

# Number of flows per source node

set NumberFlows 530

#Nodes and links

for {set j 1} {$j<=$NodeNb} { incr j } {

set S($j) [$ns node]

$ns duplex-link $S($j) $N 100Mb 1ms DropTail

$ns queue-limit $S($j) $N 1000

#TCP Sources and destinations

for {set i 1} {$i<=$NodeNb} { incr i } {

for {set j 1} {$j<=$NumberFlows} { incr j } {

set tcpsrc($i,$j) [new Agent/TCP/Newreno]

$tcpsrc($i,$j) set window_ 2000

set tcp_snk($i,$j) [new Agent/TCPSink]

}
}

#Connections

for {set i 1} {$i<=$NodeNb} { incr i } {

for {set j 1} {$j<=$NumberFlows} { incr j } {

$ns attach-agent $S($i) $tcpsrc($i,$j)

$ns attach-agent $D $tcp_snk($i,$j)

$ns connect $tcpsrc($i,$j) $tcp_snk($i,$j)

#FTP sources

for {set i 1} {$i<=$NodeNb} { incr i } {

for {set j 1} {$j<=$NumberFlows} { incr j } {

set ftp($i,$j) [$tcpsrc($i,$j) attach-source FTP]

# Generators for random size of files.

set rng1 [new RNG]

$rng1 seed 0

set rng2 [new RNG]

$rng2 seed 0
# Random inter-arrival times of TCP transfer at each source i

set RV [new RandomVariable/Exponential]

$RV set avg_ 0.045

$RV use-rng $rng1

# Random size of files to transmit

set RVSize [new RandomVariable/Pareto]

$RVSize set avg_ 10000

$RVSize set shape_ 1.5

$RVSize use-rng $rng2

# We now define the beginning times of transfers and the transfer sizes

# Arrivals of sessions follow a Poisson process.

for {set i 1} {$i<=$NodeNb} { incr i } {

set t [$ns now]

for {set j 1} {$j<=$NumberFlows} { incr j } {

# set the beginning time of next transfer from source i

set t [expr $t + [$RV value]]

set Conct($i,$j) $t

# set the size of next transfer from source i

set Size($i,$j) [expr [$RVSize value]]

$ns at $Conct($i,$j) "$ftp($i,$j) send $Size($i,$j)"


# update the number of flows

$ns at $Conct($i,$j) "countFlows $i 1"

# Next is a recursive procedure that checks for each session whether

# it has ended. The procedure calls itself each 0.1 sec (this is

# set in the variable "time").

# If a connection has ended then we print in the file $Out

# * the connection identifiers i and j,

# * the start and end time of the connection,

# * the throughput of the session,

# * the size of the transfer in bytes

# and we further define another beginning of transfer after a random time.

proc Test {} {

global Conct tcpsrc Size NodeNb NumberFlows ns RV ftp Out tcp_snk RVSize

set time 0.1

for {set i 1} {$i<=$NodeNb} { incr i } {

for {set j 1} {$j<=$NumberFlows} { incr j } {

# We now check if the transfer is over

if {[$tcpsrc($i,$j) set ack_]==[$tcpsrc($i,$j) set maxseq_]} {

if {[$tcpsrc($i,$j) set ack_]>=0} {


# If the transfer is over, we print relevant information in $Out

puts $Out "$i,$j\t$Conct($i,$j)\t[expr [$ns now]]\t\

[expr ($Size($i,$j))/(1000*([expr [$ns now]] - $Conct($i,$j)))]\t$Size($i,$j)"

countFlows $i 0

$tcpsrc($i,$j) reset

$tcp_snk($i,$j) reset

}}}}

$ns at [expr [$ns now]+$time] "Test"

for {set j 1} {$j<=$NodeNb} { incr j } {

set Cnts($j) 0

# The following recursive procedure updates the number of connections

# as a function of time. Each 0.2 it prints them into $Conn. This

# is done by calling the procedure with the "sign" parameter equal

# 3 (in which case the "ind" parameter does not play a role). The

# procedure is also called by the Test procedure whenever a connection

# from source i ends by assigning the "sign" parameter 0, or when

# it begins, by assigning it 1 (i is passed through the "ind" variable).

proc countFlows { ind sign } {

global Cnts Conn NodeNb


set ns [Simulator instance]

if { $sign==0 } { set Cnts($ind) [expr $Cnts($ind) - 1]

} elseif { $sign==1 } { set Cnts($ind) [expr $Cnts($ind) + 1]

} else {

puts -nonewline $Conn "[$ns now] \t"

set sum 0

for {set j 1} {$j<=$NodeNb} { incr j } {

puts -nonewline $Conn "$Cnts($j) \t"

set sum [expr $sum + $Cnts($j)]

puts $Conn "$sum"

$ns at [expr [$ns now] + 0.2] "countFlows 1 3"

#Define a 'finish' procedure

proc finish {} {

global ns tf qsize qbw qlost

$ns flush-trace

close $qsize

close $qbw

close $qlost

# Execute xgraph to display the queue size, queue bandwidth and loss rate

exec xgraph queuesize.tr -geometry 800x400 -t "Queue size" -x "secs" -y "# packets" &

exec xgraph queuebw.tr -geometry 800x400 -t "bandwidth" -x "secs" -y "Kbps" -fg white &
exec xgraph queuelost.tr -geometry 800x400 -t "# Packets lost" -x "secs" -y "packets" -fg red &

exit 0

####################

# QUEUE MONiTORiNG #

####################

set qfile [$ns monitor-queue $N $D [open queue.tr w] 0.05]

[$ns link $N $D] queue-sample-timeout;

# The following procedure records queue size, bandwidth and loss rate

proc record {} {

global ns qfile qsize qbw qlost N D

set time 0.05

set now [$ns now]

# print in the file $qsize the current queue size

# print in the file $qbw the current used bandwidth

# print in the file $qlost the loss rate

$qfile instvar parrivals_ pdepartures_ bdrops_ bdepartures_ pdrops_

puts $qsize "$now [expr $parrivals_-$pdepartures_-$pdrops_]"

puts $qbw "$now [expr $bdepartures_*8/1024/$time]"


set bdepartures_ 0

puts $qlost "$now [expr $pdrops_/$time]"

$ns at [expr $now+$time] "record"

$ns at 0.0 "record"

$ns at 0.01 "Test"

$ns at 0.5 "countFlows 1 3"

$ns at 20 "finish"

$ns run

set ns [new Simulator]

set nf [open out.nam w]

$ns namtrace-all $nf

set tf [open out.tr w]

set windowVsTime [open win w]

set param [open parameters w]

$ns trace-all $tf

#Define a 'finish' procedure

proc finish {} {

global ns nf tf
$ns flush-trace

close $nf

close $tf

exec nam out.nam &

exit 0

#Create bottleneck and dest nodes

set n2 [$ns node]

set n3 [$ns node]

#Create links between these nodes

$ns duplex-link $n2 $n3 0.7Mb 20ms DropTail

set NumbSrc 5

set Duration 10

#Source nodes

for {set j 1} {$j<=$NumbSrc} { incr j } {

set S($j) [$ns node]

# Create a random generator for starting the ftp and for bottleneck link delays

set rng [new RNG]

$rng seed 0
# paratmers for random variables for delays

set RVdly [new RandomVariable/Uniform]

$RVdly set min_ 1

$RVdly set max_ 5

$RVdly use-rng $rng

# parameters for random variables for begenning of ftp connections

set RVstart [new RandomVariable/Uniform]

$RVstart set min_ 0

$RVstart set max_ 7

$RVstart use-rng $rng

#We define two random parameters for each connections

for {set i 1} {$i<=$NumbSrc} { incr i } {

set startT($i) [expr [$RVstart value]]

set dly($i) [expr [$RVdly value]]

puts $param "dly($i) $dly($i) ms"

puts $param "startT($i) $startT($i) sec"

#Links between source and bottleneck

for {set j 1} {$j<=$NumbSrc} { incr j } {

$ns duplex-link $S($j) $n2 10Mb $dly($j)ms DropTail

$ns queue-limit $S($j) $n2 100


}

#Monitor the queue for link (n2-n3). (for NAM)

$ns duplex-link-op $n2 $n3 queuePos 0.5

#Set Queue Size of link (n2-n3) to 10

$ns queue-limit $n2 $n3 10

#TCP Sources

for {set j 1} {$j<=$NumbSrc} { incr j } {

set tcp_src($j) [new Agent/TCP/Reno]

#TCP Destinations

for {set j 1} {$j<=$NumbSrc} { incr j } {

set tcp_snk($j) [new Agent/TCPSink]

#Connections

for {set j 1} {$j<=$NumbSrc} { incr j } {

$ns attach-agent $S($j) $tcp_src($j)

$ns attach-agent $n3 $tcp_snk($j)

$ns connect $tcp_src($j) $tcp_snk($j)

}
#FTP sources

for {set j 1} {$j<=$NumbSrc} { incr j } {

set ftp($j) [$tcp_src($j) attach-source FTP]

#Parametrisation of TCP sources

for {set j 1} {$j<=$NumbSrc} { incr j } {

$tcp_src($j) set packetSize_ 552

#Schedule events for the FTP agents:

for {set i 1} {$i<=$NumbSrc} { incr i } {

$ns at $startT($i) "$ftp($i) start"

$ns at $Duration "$ftp($i) stop"

proc plotWindow {tcpSource file k} {

global ns

set time 0.03

set now [$ns now]

set cwnd [$tcpSource set cwnd_]

puts $file "$k $now $cwnd"

$ns at [expr $now+$time] "plotWindow $tcpSource $file $k" }

# The procedure will now be called for all tcp sources


for {set j 1} {$j<=$NumbSrc} { incr j } {

$ns at 0.1 "plotWindow $tcp_src($j) $windowVsTime $j"

$ns at [expr $Duration] "finish"

$ns run

# wrls1.tcl

# A 3-node example for ad-hoc simulation with DSDV

# Define options

set val(chan) Channel/WirelessChannel ;# channel type

set val(prop) Propagation/TwoRayGround ;# radio-propagation model

set val(netif) Phy/WirelessPhy ;# network interface type

set val(mac) Mac/802_11 ;# MAC type

set val(ifq) Queue/DropTail/PriQueue ;# interface queue type

set val(ll) LL ;# link layer type

set val(ant) Antenna/OmniAntenna ;# antenna model

set val(ifqlen) 50 ;# max packet in ifq

set val(nn) 3 ;# number of mobilenodes

set val(rp) AODV ;# routing protocol

set val(x) 500 ;# X dimension of topography

set val(y) 400 ;# Y dimension of topography

set val(stop) 150 ;# time of simulation end


set ns [new Simulator]

set tracefd [open simple.tr w]

set windowVsTime2 [open win.tr w]

set namtrace [open simwrls.nam w]

$ns trace-all $tracefd

$ns namtrace-all-wireless $namtrace $val(x) $val(y)

# set up topography object

set topo [new Topography]

$topo load_flatgrid $val(x) $val(y)

create-god $val(nn)

# Create nn mobilenodes [$val(nn)] and attach them to the channel.

# configure the nodes

$ns node-config -adhocRouting $val(rp) \

-llType $val(ll) \

-macType $val(mac) \

-ifqType $val(ifq) \
-ifqLen $val(ifqlen) \

-antType $val(ant) \

-propType $val(prop) \

-phyType $val(netif) \

-channelType $val(chan) \

-topoInstance $topo \

-agentTrace ON \

-routerTrace ON \

-macTrace OFF \

-movementTrace ON

for {set i 0} {$i < $val(nn) } { incr i } {

set node_($i) [$ns node]

# Provide initial location of mobilenodes

$node_(0) set X_ 5.0

$node_(0) set Y_ 5.0

$node_(0) set Z_ 0.0

$node_(1) set X_ 490.0

$node_(1) set Y_ 285.0

$node_(1) set Z_ 0.0

$node_(2) set X_ 150.0


$node_(2) set Y_ 240.0

$node_(2) set Z_ 0.0

# Generation of movements

$ns at 10.0 "$node_(0) setdest 250.0 250.0 3.0"

$ns at 15.0 "$node_(1) setdest 45.0 285.0 5.0"

$ns at 110.0 "$node_(0) setdest 480.0 300.0 5.0"

# Set a TCP connection between node_(0) and node_(1)

set tcp [new Agent/TCP/Newreno]

$tcp set class_ 2

set sink [new Agent/TCPSink]

$ns attach-agent $node_(0) $tcp

$ns attach-agent $node_(1) $sink

$ns connect $tcp $sink

set ftp [new Application/FTP]

$ftp attach-agent $tcp

$ns at 10.0 "$ftp start"

# Printing the window size

proc plotWindow {tcpSource file} {

global ns

set time 0.01

set now [$ns now]

set cwnd [$tcpSource set cwnd_]


puts $file "$now $cwnd"

$ns at [expr $now+$time] "plotWindow $tcpSource $file" }

$ns at 10.1 "plotWindow $tcp $windowVsTime2"

# Define node initial position in nam

for {set i 0} {$i < $val(nn)} { incr i } {

# 30 defines the node size for nam

$ns initial_node_pos $node_($i) 30

# Telling nodes when the simulation ends

for {set i 0} {$i < $val(nn) } { incr i } {

$ns at $val(stop) "$node_($i) reset";

# ending nam and the simulation

$ns at $val(stop) "$ns nam-end-wireless $val(stop)"

$ns at $val(stop) "stop"

$ns at 150.01 "puts \"end simulation\" ; $ns halt"

proc stop {} {

global ns tracefd namtrace

$ns flush-trace

close $tracefd

close $namtrace

}
$ns run

set ns [new Simulator]

#Define different colors for data flows (for NAM)

$ns color 1 Blue

$ns color 2 Red

#Open the Trace files

set file1 [open out.tr w]

set winfile [open WinFile w]

$ns trace-all $file1

#Open the NAM trace file

set file2 [open out.nam w]

$ns namtrace-all $file2

#Define a 'finish' procedure

proc finish {} {

global ns file1 file2

$ns flush-trace

close $file1
close $file2

exec nam out.nam &

exit 0

#Create six nodes

set n0 [$ns node]

set n1 [$ns node]

set n2 [$ns node]

set n3 [$ns node]

set n4 [$ns node]

set n5 [$ns node]

$n1 color red

$n1 shape box

#Create links between the nodes

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

$ns duplex-link $n1 $n2 2Mb 10ms DropTail

$ns simplex-link $n2 $n3 0.3Mb 100ms DropTail

$ns simplex-link $n3 $n2 0.3Mb 100ms DropTail

set lan [$ns newLan "$n3 $n4 $n5" 0.5Mb 40ms LL Queue/DropTail MAC/Csma/Cd Channel]

# $ns duplex-link $n3 $n4 0.5Mb 40ms DropTail


# $ns duplex-link $n3 $n5 0.5Mb 30ms DropTail

#Give node position (for NAM)

# $ns duplex-link-op $n0 $n2 orient right-down

# $ns duplex-link-op $n1 $n2 orient right-up

# $ns simplex-link-op $n2 $n3 orient right

# $ns simplex-link-op $n3 $n2 orient left

# $ns duplex-link-op $n3 $n4 orient right-up

# $ns duplex-link-op $n3 $n5 orient right-down

#Set Queue Size of link (n2-n3) to 10

# $ns queue-limit $n2 $n3 20

#Setup a TCP connection

set tcp [new Agent/TCP/Newreno]

$ns attach-agent $n0 $tcp

set sink [new Agent/TCPSink/DelAck]

$ns attach-agent $n4 $sink

$ns connect $tcp $sink

$tcp set fid_ 1

$tcp set window_ 8000

$tcp set packetSize_ 552

#Setup a FTP over TCP connection


set ftp [new Application/FTP]

$ftp attach-agent $tcp

$ftp set type_ FTP

#Setup a UDP connection

set udp [new Agent/UDP]

$ns attach-agent $n1 $udp

set null [new Agent/Null]

$ns attach-agent $n5 $null

$ns connect $udp $null

$udp set fid_ 2

#Setup a CBR over UDP connection

set cbr [new Application/Traffic/CBR]

$cbr attach-agent $udp

$cbr set type_ CBR

$cbr set packet_size_ 1000

$cbr set rate_ 0.01mb

$cbr set random_ false

$ns at 0.1 "$cbr start"

$ns at 1.0 "$ftp start"

$ns at 124.0 "$ftp stop"

$ns at 124.5 "$cbr stop"


# next procedure gets two arguments: the name of the

# tcp source node, will be called here "tcp",

# and the name of output file.

proc plotWindow {tcpSource file} {

global ns

set time 0.1

set now [$ns now]

set cwnd [$tcpSource set cwnd_]

set wnd [$tcpSource set window_]

puts $file "$now $cwnd"

$ns at [expr $now+$time] "plotWindow $tcpSource $file" }

$ns at 0.1 "plotWindow $tcp $winfile"

$ns at 5 "$ns trace-annotate \"packet drop\""

# PPP

$ns at 125.0 "finish"

$ns run
set ns [new Simulator]

#Define different colors for data flows (for NAM)

$ns color 1 Blue

$ns color 2 Red

#Open the Trace files

set file1 [open out.tr w]

set winfile [open WinFile w]

$ns trace-all $file1

#Open the NAM trace file

set file2 [open out.nam w]

$ns namtrace-all $file2

#Define a 'finish' procedure

proc finish {} {

global ns file1 file2

$ns flush-trace

close $file1

close $file2

exec nam out.nam &

exit 0

}
#Create six nodes

set n0 [$ns node]

set n1 [$ns node]

set n2 [$ns node]

set n3 [$ns node]

set n4 [$ns node]

set n5 [$ns node]

$n1 color red

$n1 shape box

#Create links between the nodes

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

$ns duplex-link $n1 $n2 2Mb 10ms DropTail

$ns simplex-link $n2 $n3 0.3Mb 100ms DropTail

$ns simplex-link $n3 $n2 0.3Mb 100ms DropTail

set lan [$ns newLan "$n3 $n4 $n5" 0.5Mb 40ms LL Queue/DropTail MAC/802_3 Channel]

# $ns duplex-link $n3 $n4 0.5Mb 40ms DropTail

# $ns duplex-link $n3 $n5 0.5Mb 30ms DropTail

#Give node position (for NAM)

# $ns duplex-link-op $n0 $n2 orient right-down

# $ns duplex-link-op $n1 $n2 orient right-up


# $ns simplex-link-op $n2 $n3 orient right

# $ns simplex-link-op $n3 $n2 orient left

# $ns duplex-link-op $n3 $n4 orient right-up

# $ns duplex-link-op $n3 $n5 orient right-down

#Set Queue Size of link (n2-n3) to 10

# $ns queue-limit $n2 $n3 20

#Setup a TCP connection

set tcp [new Agent/TCP/Newreno]

$ns attach-agent $n0 $tcp

set sink [new Agent/TCPSink/DelAck]

$ns attach-agent $n4 $sink

$ns connect $tcp $sink

$tcp set fid_ 1

$tcp set window_ 8000

$tcp set packetSize_ 552

#Setup a FTP over TCP connection

set ftp [new Application/FTP]

$ftp attach-agent $tcp

$ftp set type_ FTP


#Setup a UDP connection

set udp [new Agent/UDP]

$ns attach-agent $n1 $udp

set null [new Agent/Null]

$ns attach-agent $n5 $null

$ns connect $udp $null

$udp set fid_ 2

#Setup a CBR over UDP connection

set cbr [new Application/Traffic/CBR]

$cbr attach-agent $udp

$cbr set type_ CBR

$cbr set packet_size_ 1000

$cbr set rate_ 0.01mb

$cbr set random_ false

$ns at 0.1 "$cbr start"

$ns at 1.0 "$ftp start"

$ns at 124.0 "$ftp stop"

$ns at 124.5 "$cbr stop"

# next procedure gets two arguments: the name of the

# tcp source node, will be called here "tcp",

# and the name of output file.


proc plotWindow {tcpSource file} {

global ns

set time 0.1

set now [$ns now]

set cwnd [$tcpSource set cwnd_]

set wnd [$tcpSource set window_]

puts $file "$now $cwnd"

$ns at [expr $now+$time] "plotWindow $tcpSource $file" }

$ns at 0.1 "plotWindow $tcp $winfile"

$ns at 5 "$ns trace-annotate \"packet drop\""

# PPP

$ns at 125.0 "finish"

$ns run
Hello File Descriptors
1
/* Not stdio.h */
2
#include <unistd.h>
3

4
void main()
5
{
6
char str[100];
7

8 /*Write on screen*/

9 write(1,"\nType Something : ",17);

10

11 /*Read at most 100 chars from console into 'str' */

12 read(0,str,100);

13
write(1,"\nYou typed :\n",13);
14

15
/*write 10 chars from 'str' to screen */
16
write(1,str,10);
17

18
/*newline*/
19
write(1,"\n",1);
20
}
21

Output – For the lazy ones


1 Type Something :hi how are you

2
3 You typed :

4 hi how are

read/write
1 write(int fd, const void *buf, size_t n);

fd – File Descriptor to write to


buf – Pointer to Data to be written
n – Number of bytes to write
returns – Number of bytes written, negative if error
1 read(int fd, const void *buf, size_t n);

fd – File Descriptor to read from


buf – Pointer to where data read should be stored
n – Maximum number of bytes to be read.
returns – Number of bytes read, can be less than n if there is end of input , negative if error
Lets get to handling sockets now.

Hello Sockets – Echo Server


Echo Server is a device which sends back whatever data it has received
I have put comments in the code to explain what each function does. Apart from that I recommend you
Google each of them to know their prototype , as I won’t be mentioning them , or you can use man in
Linux.
1 /*Required Headers*/

2
#include <sys/types.h>
3
#include <sys/socket.h>
4
#include <netdb.h>
5
#include <stdio.h>
6
#include<string.h>
7

8
int main()
9
{
10

11 char str[100];

12 int listen_fd, comm_fd;


13

14 struct sockaddr_in servaddr;

15

16 listen_fd = socket(AF_INET, SOCK_STREAM, 0);

17
bzero( &servaddr, sizeof(servaddr));
18

19
servaddr.sin_family = AF_INET;
20
servaddr.sin_addr.s_addr = htons(INADDR_ANY);
21
servaddr.sin_port = htons(22000);
22

23
bind(listen_fd, (struct sockaddr *) &servaddr, sizeof(servaddr));
24

25
listen(listen_fd, 10);
26

27 comm_fd = accept(listen_fd, (struct sockaddr*) NULL, NULL);

28

29 while(1)

30 {

31

32 bzero( str, 100);

33
read(comm_fd,str,100);
34

35
printf("Echoing back - %s",str);
36

37
38 write(comm_fd, str, strlen(str)+1);

39

40 }

}
41

42

43

Line by Line
1 int listen_fd, comm_fd;

File Descriptors to be used

1 struct sockaddr_in servaddr;

Struct to hold IP Address and Port Numbers

1 listen_fd = socket(AF_INET, SOCK_STREAM, 0);

Each server needs to “listen” for connections. The above function creates a socket with AF_INET (
IP Addressing ) and of type SOCK_STREAM. Data from all devices wishing to connect on this
socket will be redirected to listen_fd.
1 bzero( &servaddr, sizeof(servaddr));

Clear servaddr ( Mandatory ).

1 servaddr.sin_family = AF_INET;

2 servaddr.sin_addr.s_addr = htons(INADDR_ANY);

3 servaddr.sin_port = htons(22000);

Set Addressing scheme to – AF_INET ( IP )


Allow any IP to connect – htons(INADDR_ANY)
Listen on port 22000 – htons(22000)
[ Remember how Google listened on Port 80 ? ]

1 bind(listen_fd, (struct sockaddr *) &servaddr, sizeof(servaddr));

Prepare to listen for connections from address/port specified in sockaddr ( Any IP on port 22000 ).
1 listen(listen_fd, 10);

Start Listening for connections , keep at the most 10 connection requests waiting.If there are more
than 10 computers wanting to connect at a time, the 11th one fails to.
1 comm_fd = accept(listen_fd, (struct sockaddr*) NULL, NULL);

Accept a connection from any device who is willing to connect, If there is no one who wants to
connect , wait. A file descriptor is returned. This can finally be used to communicate , whatever is
sent by the device accepted can be read from comm_fd, whatever is written to comm_fd is sent to
the other device.
1 bzero( str, 100);

2 read(comm_fd,str,100);

3 printf("Echoing back - %s",str);

4 write(comm_fd, str, strlen(str)+1);

The Server then does the above forever

 Clear str
 read at most 100 bytes into str
 display what it reads
 send back str , (length of string + 1) so that is sent as well
Hello Sockets – Client
1 #include <sys/types.h>

2 #include <sys/socket.h>

3 #include <netdb.h>

#include <stdio.h>
4
#include<string.h>
5

6
int main(int argc,char **argv)
7
{
8
int sockfd,n;
9
char sendline[100];
10 char recvline[100];

11 struct sockaddr_in servaddr;

12

13 sockfd=socket(AF_INET,SOCK_STREAM,0);

14 bzero(&servaddr,sizeof servaddr);
15

16 servaddr.sin_family=AF_INET;

17 servaddr.sin_port=htons(22000);

18
inet_pton(AF_INET,"127.0.0.1",&(servaddr.sin_addr));
19

20
connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));
21

22
while(1)
23
{
24
bzero( sendline, 100);
25
bzero( recvline, 100);
26 fgets(sendline,100,stdin); /*stdin = 0 , for standard input */

27

28 write(sockfd,sendline,strlen(sendline)+1);

29 read(sockfd,recvline,100);

30 printf("%s",recvline);

}
31

32
}
33

34

35

Line by Line
I’ll only go over the new parts

1 inet_pton(AF_INET,"127.0.0.1",&(servaddr.sin_addr));
Set IP address in servaddr to “127.0.0.1” ( computers way of saying myself ) since our server is also
on the same machine . The address in servaddr needs to be in integer format , hence the
function inet_pton
1 connect(sockfd,(struct sockaddr *)&servaddr,sizeof(servaddr));

Connect to the device whose address and port number is specified in servaddr.

1 bzero( sendline, 100);

2 bzero( recvline, 100);

3 fgets(sendline,100,stdin); /*stdin = 0 , for standard input */

4 write(sockfd,sendline,strlen(sendline)+1);

5 read(sockfd,recvline,100);

printf("%s",recvline);
6

The Client then does following forever.

 Clear sendline and recvline


 read string from stdin in sendline ( stdin is 0 for standard input )
 write sendline in sockfd
 read from sockfd in srecvline
 Display recvline
Output – Client/Server in a not so pleasant Conversation
1
Hi Server
2 Hi Server

3 How are you ?

4 How are you ?

5 Stop imitating me !!!

6 Stop imitating me !!!

STAAAAHHPPPPPPPP !
7
STAAAAHHPPPPPPPP !
8

I hope this post is of some help to whoever reads it. I tried to keep it as simple as possible . Leave
Comments
/****************************************************************************
*/
/*** myping.c
***/
/***
***/
/*** Use the ICMP protocol to request "echo" from destination.
***/
/****************************************************************************
*/

#include <fcntl.h>
#include <errno.h>
#include <sys/socket.h>
#include <resolv.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/ip_icmp.h>

#define PACKETSIZE 64
struct packet
{
struct icmphdr hdr;
char msg[PACKETSIZE-sizeof(struct icmphdr)];
};

int pid=-1;
struct protoent *proto=NULL;

/*--------------------------------------------------------------------*/
/*--- checksum - standard 1s complement checksum ---*/
/*--------------------------------------------------------------------*/
unsigned short checksum(void *b, int len)
{ unsigned short *buf = b;
unsigned int sum=0;
unsigned short result;

for ( sum = 0; len > 1; len -= 2 )


sum += *buf++;
if ( len == 1 )
sum += *(unsigned char*)buf;
sum = (sum >> 16) + (sum & 0xFFFF);
sum += (sum >> 16);
result = ~sum;
return result;
}

/*--------------------------------------------------------------------*/
/*--- display - present echo info ---*/
/*--------------------------------------------------------------------*/
void display(void *buf, int bytes)
{ int i;
struct iphdr *ip = buf;
struct icmphdr *icmp = buf+ip->ihl*4;
printf("----------------\n");
for ( i = 0; i < bytes; i++ )
{
if ( !(i & 15) )
printf("\n

X: ", i);
printf("X ", ((unsigned char*)buf)[i]);
}
printf("\n");
printf("IPv%d: hdr-size=%d pkt-size=%d protocol=%d TTL=%d src=%s ",
ip->version, ip->ihl*4, ntohs(ip->tot_len), ip->protocol,
ip->ttl, inet_ntoa(ip->saddr));
printf("dst=%s\n", inet_ntoa(ip->daddr));
if ( icmp->un.echo.id == pid )
{
printf("ICMP: type[%d/%d] checksum[%d] id[%d] seq[%d]\n",
icmp->type, icmp->code, ntohs(icmp->checksum),
icmp->un.echo.id, icmp->un.echo.sequence);
}
}

/*--------------------------------------------------------------------*/
/*--- listener - separate process to listen for and collect messages--*/
/*--------------------------------------------------------------------*/
void listener(void)
{ int sd;
struct sockaddr_in addr;
unsigned char buf[1024];

sd = socket(PF_INET, SOCK_RAW, proto->p_proto);


if ( sd < 0 )
{
perror("socket");
exit(0);
}
for (;;)
{ int bytes, len=sizeof(addr);

bzero(buf, sizeof(buf));
bytes = recvfrom(sd, buf, sizeof(buf), 0, (struct
sockaddr*)&addr, &len);
if ( bytes > 0 )
display(buf, bytes);
else
perror("recvfrom");
}
exit(0);
}

/*--------------------------------------------------------------------*/
/*--- ping - Create message and send it. ---*/
/*--------------------------------------------------------------------*/
void ping(struct sockaddr_in *addr)
{ const int val=255;
int i, sd, cnt=1;
struct packet pckt;
struct sockaddr_in r_addr;

sd = socket(PF_INET, SOCK_RAW, proto->p_proto);


if ( sd < 0 )
{
perror("socket");
return;
}
if ( setsockopt(sd, SOL_IP, IP_TTL, &val, sizeof(val)) != 0)
perror("Set TTL option");
if ( fcntl(sd, F_SETFL, O_NONBLOCK) != 0 )
perror("Request nonblocking I/O");
for (;;)
{ int len=sizeof(r_addr);

printf("Msg #%d\n", cnt);


if ( recvfrom(sd, &pckt, sizeof(pckt), 0, (struct
sockaddr*)&r_addr, &len) > 0 )
printf("***Got message!***\n");
bzero(&pckt, sizeof(pckt));
pckt.hdr.type = ICMP_ECHO;
pckt.hdr.un.echo.id = pid;
for ( i = 0; i < sizeof(pckt.msg)-1; i++ )
pckt.msg[i] = i+'0';
pckt.msg[i] = 0;
pckt.hdr.un.echo.sequence = cnt++;
pckt.hdr.checksum = checksum(&pckt, sizeof(pckt));
if ( sendto(sd, &pckt, sizeof(pckt), 0, (struct
sockaddr*)addr, sizeof(*addr)) <= 0 )
perror("sendto");
sleep(1);
}
}

/*--------------------------------------------------------------------*/
/*--- main - look up host and start ping processes. ---*/
/*--------------------------------------------------------------------*/
int main(int count, char *strings[])
{ struct hostent *hname;
struct sockaddr_in addr;

if ( count != 2 )
{
printf("usage: %s <addr>\n", strings[0]);
exit(0);
}
if ( count > 1 )
{
pid = getpid();
proto = getprotobyname("ICMP");
hname = gethostbyname(strings[1]);
bzero(&addr, sizeof(addr));
addr.sin_family = hname->h_addrtype;
addr.sin_port = 0;
addr.sin_addr.s_addr = *(long*)hname->h_addr;
if ( fork() == 0 )
listener();
else
ping(&addr);
wait(0);
}
else
printf("usage: myping <hostname>\n");
return 0;
}

Simple PING implementation in C


#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/signal.h>
#include <string.h>

#define DEFDATALEN 56
#define MAXIPLEN 60
#define MAXICMPLEN 76

static char *hostname = NULL;

static int in_cksum(unsigned short *buf, int sz)


{
int nleft = sz;
int sum = 0;
unsigned short *w = buf;
unsigned short ans = 0;

while (nleft > 1) {


sum += *w++;
nleft -= 2;
}

if (nleft == 1) {
*(unsigned char *) (&ans) = *(unsigned char *) w;
sum += ans;
}

sum = (sum >> 16) + (sum & 0xFFFF);


sum += (sum >> 16);
ans = ˜sum;
return (ans);
}

static void noresp(int ign)


{
printf("No response from %s\n", hostname);
exit(0);
}

static void ping(const char *host)


{
struct hostent *h;
struct sockaddr_in pingaddr;
struct icmp *pkt;
int pingsock, c;
char packet[DEFDATALEN + MAXIPLEN + MAXICMPLEN];

if ((pingsock = socket(AF_INET, SOCK_RAW, 1)) < 0) { /* 1 == ICMP */


perror("ping: creating a raw socket");
exit(1);
}

/* drop root privs if running setuid */


setuid(getuid());

memset(&pingaddr, 0, sizeof(struct sockaddr_in));

pingaddr.sin_family = AF_INET;
if (!(h = gethostbyname(host))) {
fprintf(stderr, "ping: unknown host %s\n", host);
exit(1);
}
memcpy(&pingaddr.sin_addr, h->h_addr, sizeof(pingaddr.sin_addr));
hostname = h->h_name;

pkt = (struct icmp *) packet;


memset(pkt, 0, sizeof(packet));
pkt->icmp_type = ICMP_ECHO;
pkt->icmp_cksum = in_cksum((unsigned short *) pkt, sizeof(packet));

c = sendto(pingsock, packet, sizeof(packet), 0,


(struct sockaddr *) &pingaddr, sizeof(struct sockaddr_in));

if (c < 0 || c != sizeof(packet)) {
if (c < 0)
perror("ping: sendto");
fprintf(stderr, "ping: write incomplete\n");
exit(1);
}

signal(SIGALRM, noresp);
alarm(2); /* give the host 5000ms to
respond */
/* listen for replies */
while (1) {
struct sockaddr_in from;
size_t fromlen = sizeof(from);

if ((c = recvfrom(pingsock, packet, sizeof(packet), 0,


(struct sockaddr *) &from, &fromlen)) < 0) {
if (errno == EINTR)
continue;
perror("ping: recvfrom");
continue;
}
if (c >= 76) { /* ip + icmp */
struct iphdr *iphdr = (struct iphdr *) packet;

pkt = (struct icmp *) (packet + (iphdr->ihl << 2)); /* skip ip hdr


*/
if (pkt->icmp_type == ICMP_ECHOREPLY)
break;
}
}
printf("%s is alive!\n", hostname);
return;
}

int main ()
{
ping ("192.168.1.2");

}
CRC :ERoor Correction & Detection

1. #include <stdio.h>
2. #include <conio.h>
3. #include <string.h>
4. void main() {
5. int i,j,keylen,msglen;
6. char input[100], key[30],temp[30],quot[100],rem[30],key1[30];
7. clrscr();
8. printf("Enter Data: ");
9. gets(input);
10. printf("Enter Key: ");
11. gets(key);
12. keylen=strlen(key);
13. msglen=strlen(input);
14. strcpy(key1,key);
15. for (i=0;i<keylen-1;i++) {
16. input[msglen+i]='0';
17. }
18. for (i=0;i<keylen;i++)
19. temp[i]=input[i];
20. for (i=0;i<msglen;i++) {
21. quot[i]=temp[0];
22. if(quot[i]=='0')
23. for (j=0;j<keylen;j++)
24. key[j]='0'; else
25. for (j=0;j<keylen;j++)
26. key[j]=key1[j];
27. for (j=keylen-1;j>0;j--) {
28. if(temp[j]==key[j])
29. rem[j-1]='0'; else
30. rem[j-1]='1';
31. }
32. rem[keylen-1]=input[i+keylen];
33. strcpy(temp,rem);
34. }
35. strcpy(rem,temp);
36. printf("\nQuotient is ");
37. for (i=0;i<msglen;i++)
38. printf("%c",quot[i]);
39. printf("\nRemainder is ");
40. for (i=0;i<keylen-1;i++)
41. printf("%c",rem[i]);
42. printf("\nFinal data is: ");
43. for (i=0;i<msglen;i++)
44. printf("%c",input[i]);
45. for (i=0;i<keylen-1;i++)
46. printf("%c",rem[i]);
47. getch();
48. }

AWk SCRIPT TO GET THROUGHPUT

#!/usr/bin/awk

BEGIN {
bytes_recvd = 0;
throughput = 0;
interval = 1;
current_time_instance = 0;
nxt_time_instance = current_time_instance + interval;
}
{
action = $1;
time = $2;
from = $3;
to = $4;
type = $5;
pkt_size = $6;
flow_id = $8;
src = $9;
dst = $10;
sequence_n0 = $11;
pkt_id = $12;

if (time < nxt_time_instance)


{
if (action == "r")
{
bytes_recvd = bytes_recvd + pkt_size;
}
}
else {
current_time_instance = nxt_time_instance;
nxt_time_instance += interval;
throughput = bytes_recvd / current_time_instance;
printf("%d %dn",current_time_instance, throughput/1024);
}
}
END {
}

Вам также может понравиться