Anda di halaman 1dari 67

EAST WEST INSTITUTE OF TECHNOLOGY

# 63 Off Magadi Main Road, Vishwaneedam Post, Bangalore-91

(Affiliated to VTU, Belagavi, Approved by AICTE, New Delhi & Recognized by Govt. of Karnataka)

Department of

Computer Science and Engineering

Computer Network laboratory


(15CSL57)
V Semester B.E
Prepared by,

Dr. Arun Biradar


Prof. Chandan Raj B R
Prof. Manjushree Patel R
Prof. Dhanraj

Reviewed by

Dr. Arun Biradar Dr. T.G Basavaraju


Head of the Department Professor & Head
Department of Computer Science & Engg Department of Computer Science & Engg
East West Institute of Technology Government SKSJ Technical Institute
Bangalore-560091 Bangalore-560001
PREFACE
The rising importance of the computer systems to everyday life makes the role of the computer
networks vital. Computer networks are used to transfer data between the communicating
systems. Computer networks need to be designed using appropriate topology and network
technologies in order to be fast, reliable and easy expandable. The transmitted data is divided
into the appropriate Protocol Data Units. Ability to analyse the data is required to understand
the network protocols and to troubleshoot the network problems. Local Area Networks
interconnect to one another and compose Wide Area Networks. Routing is critical in WANs.

This manual for practical “Computer Network Laboratory” is an introduction to all popular
concepts in networking and their implementation with the Java language. It is planned for
beginners who would like to learn the subject through programs. Java programming language
offers several facilities to group data and methods together in convenient packages, or classes.
With the emergence of Java as the most popular language of implementation blossomed from
Sun Microsystems.

The introduction of network Simulator-2 helps the students to simulate the designed network
and gain knowledge on network performance by using TCL scripting.

This edition emphasizes on abstract concepts of Networking and few of the algorithms and
describes how to simulate the designed network which is useful in problem solving using
available packages and utility from java packages and TCL scripts. Students will gain a good
appreciation of the subject as this manual has a clear display of syntax and elegant
programming examples. To simplify concepts of NS2 and networking algorithm given are
implemented in simple Java language understandable even by beginners

--Dr. T.G Basavaraju


--Dr. Arun Biradar
Department of Computer Science and Engineering
ABOUT
The department of Computer Science and Engineering was established in the year 2001.The
department offer undergraduate and post graduate programmed in Computer Science &
Engineering. The department has a very good infrastructure and faculty to provide excellent
education to meet the industry standards.

Today, the department caters to the needs of more than 500 UG students and 72 PG Students.
It houses state of the art computing facilities with high end servers which support the LAN,
provide a Linux/Unix environment, also provides exclusive library facility to its students and
boasts of well trained and experienced faculty teaching the departments various courses in the
areas of Computer Networks, Computer Architecture, Database Systems, Microprocessor,
Operating Systems, Analysis and Design of Algorithms and Software Engineering.

The department lays stress on the practical and application based aspects through
laboratories, seminars, group discussions, viva-voce and project work, keeping pace with the
growth in Computer Science & Engineering technology.

The Students are given scope to conduct experiments on innovative ideas. A sound theoretical
and practical work prepares the students in wider field of Computer Science & Engineering to
take up challenging jobs in the area of:

System Software Development

Application Software Development

Computer Networking

Vision
To become a leader in providing high quality education and research in the area of Computer
Science & Engineering.

Mission
To impart & Enhance Advanced Knowledge & Skills for Students & Staff to meet Global
Challenges.
To take-up Research & Consultancy in Computer Science & Engineering for the Benefit of
Society.

I
TABLE OF CONTENTS

Sl. No. PARTICULARS Page No.

1 Vision And Mission of Department I

2 COURSE DETAILS
Course Objectives III
Course Outcomes III
Syllabus IV

3 Evaluation Process V

4 Basics of NS2 1-5

Program 1: Implement three nodes point–to–point network with


5 6-9
duplex links.

6 Program 2: Implement transmission of ping messages. 10-14

7 Program 3: Implement an Ethernet LAN using n nodes. 15-18

8 Program 4: Implement simple ESS. 19-23

9 Program 5: Implement and study the performance of GSM. 24-28

10 Program 6: Implement and study the performance of CDMA. 29-33

Program 7: Write a java program for error detecting code using CRC-
11 34-38
CCITT.

12 Program 8: Implementation of bellman-ford algorithm in java. 39-42

Program 9: Using TCP/IP sockets, write a java client – server


13 43-47
program.
4

Program 10: Write a java program on datagram socket for


14 48-51
client/server to display the messages on client side.

Program 11: Write a java program for simple RSA algorithm to


15 52-56
encrypt and decrypt the data.

Program 12: Write a java program for congestion control using leaky
16 57-60
bucket algorithm.
COURSE DETAILS
Course Name: COMPUTER NETWORK LABORATORY

Course Code: 15CSL57

COURSE OBJECTIVES
This Course will enable the students to

 Demonstrate operation of network and its management commands

 Simulate and demonstrate the performance of GSM and CDMA

 Implement data link layer and transport layer protocols.

COURSE OUTCOMES

 Analyze and Compare various networking protocols.

 Demonstrate the working of different concepts of networking.

 Implement, analyze and evaluate networking protocols in NS2 / NS3

III
SYLLABUS

Subject Code 15CSL57 IA Marks 20


Number of Lecture Hours/Week 01I + 02P Exam Marks 80
Total Number of Lecture Hours 40 Exam Hours 03

PART A
1. Implement three nodes point – to – point network with duplex links between them. Set
the queue size, vary the bandwidth and find the number of packets dropped.
2. Implement transmission of ping messages/trace route over a network topology
consisting of 6 nodes and find the number of packets dropped due to congestion.
3. Implement an Ethernet LAN using n nodes and set multiple traffic nodes and plot
congestion window for different source / destination.
4. Implement simple ESS and with transmitting nodes in wire-less LAN by simulation
and determine the performance with respect to transmission of packets.
5. Implement and study the performance of GSM on NS2/NS3 (Using MAC layer) or
equivalent environment.
6. Implement and study the performance of CDMA on NS2/NS3 (Using stack called
Call net) or equivalent environment.

PART B
Implement the following in Java:
7. Write a program for error detecting code using CRC-CCITT (16- bits).
8. Write a program to find the shortest path between vertices using bellman-ford
algorithm.
9. Using TCP/IP sockets, write a client-server program to make the client send the file
name and to make the server send back the contents of the requested file if present.
10. Write a program on datagram socket for client/server to display the messages on client
side, typed at the server side.
11. Write a program for simple RSA algorithm to encrypt and decrypt the data.
12. Write a program for congestion control using leaky bucket algorithm.

IV
LAB EVALUATION PROCESS

WEEK WISE EVALUATION OF EACH PROGRAM


SL.NO ACTIVITY MARKS

1 Observation Book 6

2 Record 6

TOTAL 12

EXTERNAL ASSESSMENT (End of Semester)


SL.NO ACTIVITY MARKS

1 Write-Up 20

2 Conduction 50

3 Viva Voce 10
TOTAL 80

INTERNAL ASSESSMENT
SL.NO ACTIVITY MARKS

1 Average of Weekly Entries 12

2 Internal Assessment Reduced 8


To

TOTAL 20

V
Computer Network Laboratory 15CSL57
Basics of NS2
NS2 is an open-source simulation tool that runs on Linux. It is a discreet event
simulator targeted at networking research and provides substantial support for simulation of
routing, multicast protocols and IP protocols, such as UDP, TCP, RTP and SRM over wired
and wireless (local and satellite)networks
 Widely known as NS2, is simply an event driven simulation tool.
 Useful in studying the dynamic nature of communication networks.
 Simulation of wired as well as wireless network functions and protocols (e.g., routing
algorithms, TCP, UDP) can be done using NS2.
 In general, NS2 provides users with a way of specifying such network protocols and
simulating their corresponding behaviors.
Basic Architecture of NS2

Fig 1: Architecture of NS2

Simple Script Explanation

set ns [new Simulator] : generates an NS simulator object instance, and assigns it to


variable ns. What this line does is the following:

 Initialize the packet format (ignore this for now)


 Create a scheduler (default is calendar scheduler)
 Select the default address format (ignore this for now)

The "Simulator" object has member functions that do the following:

 Create compound objects such as nodes and links (described later)


 Connect network component objects created (ex. attach-agent)

Dept. of CSE, EWIT Page 1


Computer Network Laboratory 15CSL57
 Set network component parameters (mostly for compound objects)
 Create connections between agents (ex. make connection between a "tcp" and
"sink")
 Specify NAM display options, etc.

Comments: A Tcl comment line begins with #. More generally, any occurrence of the #
sign in a command line means that text to the right of it is considered as comment and is
ignored.

Assignment and Interrogation of Variables: The command set is used to assign variables,
and a $ sign is used to obtain the value of a variable. All variables in Tcl are stored as
strings.
set a 1
set b $a

Sets both variables a and b to the string "1".

Continuation lines: The backslash may be used to continue a Tcl command on another
line. For example,
set a \
b

$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 on the
actual simulation.

$ns namtrace-all file-descriptor: This member function tells the simulator to record
simulation traces in NAM input format. It also gives the file name that the trace will be
written 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 is compound
object made of address and port classifiers.

$ns duplex-link node1 node2 bandwidth delay queue-type: creates two simplex links of
specified bandwidth and delay, and connects the two specified nodes. In NS, the output
queue of a node is implemented as a part of a link; therefore users should specify the queue-
type when creating links. The queue can be either of type DropTail or RED.

Dept. of CSE, EWIT Page 2


Computer Network Laboratory 15CSL57
$ns queue-limit node1 node2 number: This line sets the queue limit of the two simplex
links that connect node1 and node2 to the number specified.

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 in fact
basic objects (not compound objects), mostly implemented in C++ and linked to OTcl.
Therefore, there are no specific Simulator object member functions that create these object
instances. To create agents or traffic sources, a user should know the class names these
objects (Agent/TCP, Agnet/TCPSink, Application/FTP and so on.

$ns attach-agent node agent: The attach-agent member function attaches an agent object
created to a node object. Actually, what this function does is call the attach member 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 agent object has a member
function attach-agent that attaches a traffic source object to itself

$ns connect agent1 agent2: After two agents that will communicate with each other are
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 each others' network
and port address pair.

$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 specified string at
given simulation time.

For example, $ns at 0.1 "$cbr start" will make the scheduler call a start member function
of the CBR traffic source object, which starts the CBR to transmit data. In NS, usually a
traffic source does not transmit actual data, but it notifies the underlying agent that it has
some amount of data to transmit, and the agent, just knowing how much of the data to
transfer, creates packets and sends them.

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.

Dept. of CSE, EWIT Page 3


Computer Network Laboratory 15CSL57
settcp [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

setudp [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

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

Dept. of CSE, EWIT Page 4


Computer Network Laboratory 15CSL57
Ns2 Trace file format

$1
$1 $2 $3 $4 $5 $6 $7 $8 $9 $10 $11
2
Pk
Fro To Pkt Pk
Even Tim t Flag Flo Srcadd Destadd Seqnu
m nod typ t
t e siz s w id r r m
node e e id
e

 Event or type identifier


+: a packet enqueue event
-: a packet dequeue event
r: a packet reception event
d: a packet drop event
c: a packet collision at the MAC level
 Time: at which the packet tracing string is created.
 Source and destination node: source and destination ID’s of tracing objects
 Packet type: type of the packet such as, TCP, UDP, CBR, ACK, FTP etc.
 Packet size: size of packets in bytes.
 Flags: 7 digit string
“-“: disable
1st: “E”-ECN (Explicit Congestion Notification) echo is enabled.
2nd: “P”-the priority in the IP header is enabled.
3rd: not in use
4th: “A”-Congestion action.
5th: “E”-Congestion has occurred.
6th: “F”-the TCP fast start is used.
7th: “N”-Explicit Congestion Notification (ECN) is on.
 Flow id
 Source and destination address: The format of these two fields is “a.b”, where “a"
is the address and "b" is the port.
 Sequence number
 Packet unique ID

Dept. of CSE, EWIT Page 5


Computer Network Laboratory 15CSL57
1. Implement three nodes point – to – point network with duplex links
between them. Set the queue size, vary the bandwidth and find the
number of packets dropped.

Topology Design:

Fig 2: Topology of 3 nodes point-to-point network.

Source code:

set ns [ new Simulator ]


settf [ open lab1.tr w ]
$ns trace-all $tf
setnf [ open lab1.nam w ]
$ns namtrace-all $nf
# The below code is used to create the nodes.
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
#This is used to give color to the packets.
$ns color 1 "red"
$ns color 2 "blue"

Dept. of CSE, EWIT Page 6


Computer Network Laboratory 15CSL57
$n0 label "Source/udp0"
$n1 label "Source/udp1"
$n2 label "Router"
$n3 label "Destination/Null"

#Vary the below Bandwidth and see the number of packets dropped.
$ns duplex-link $n0 $n2 10Mb 300ms DropTail
$ns duplex-link $n1 $n2 10Mb 300ms DropTail
$ns duplex-link $n2 $n3 1Mb 300ms DropTail

#The below code is used to set the queue size b/w the nodes
$ns set queue-limit $n0 $n2 10
$ns set queue-limit $n1 $n2 10
$ns set queue-limit $n2 $n3 5

#the below code is used to attach an UDP0 agent to n0, UDP1


#agentton1 and null agentton3.

set udp0 [newAgent/UDP]

$ns attach-agent $n0 $udp0


set cbr0 [new Application/Traffic/CBR]
$cbr0 attach-agent $udp0
set null3 [new Agent/Null]
$ns attach-agent $n3 $null3

set udp1 [new Agent/UDP]


$ns attach-agent $n1 $udp1
set cbr1 [new Application/Traffic/CBR]
$cbr1 attach-agent $udp1

#The below code sets the udp0 packets to red and udp1
#packets to blue color

$udp0 set class_ 1


$udp1 set class_ 2

#Thebelow code is used to connect theagents.


$ns connect $udp0 $null3
$ns connect $udp1 $null3

Dept. of CSE, EWIT Page 7


Computer Network Laboratory 15CSL57
#The below code is used to set the packet size to 500

$cbr1 set packetSize_ 500Mb

#The below code is used to set the interval of the packets,


#i.e., Data rate of the packets. if the data rate is high

#then packets drops are high.

$cbr1 set interval_ 0.005


proc finish { } {
global ns nftf
$ns flush-trace exec nam
lab1.nam & close$tf
close $nf
exit 0
}
$ns at 0.1 "$cbr0 start"

$ns at 0.1 "$cbr1 start"

$ns at 10.0 "finish"

$ns run

AWK Script:
BEGIN{
#include<stdio.h>
count=0;
}
{
if($1==”d”)
count++;
}END {
printf(“Total no. of packets dropped due to congestion is:%d”,count);
}

To run:
ns lab1.tcl

awk –f lab1.awk lab1.tr

The Total no of packets Dropped due to congestion: 750

Dept. of CSE, EWIT Page 8


Computer Network Laboratory 15CSL57

Snapshot:

Fig 3: The drop of packets at node 2

Dept. of CSE, EWIT Page 9


Computer Network Laboratory 15CSL57
2. Implement transmission of ping messages/trace route over a network
topology consisting of 6 nodes and find the number of packets
dropped due to congestion.

Topology Design:

Fig 4: Topology of network with 6 nodes to demonstrate ping message transmission

Note:

1. Vary the bandwidth and queue size between the nodes n0-n2 , n2-n4. n6-n2 and n2-
n5 and see the number of packets dropped at thenodes.

2. The ping agent can be attached to the nodes bygiving


i. set ping0 [newAgent/Ping]
$ns attach-agent $n0 $ping0
ii. The ping agents can be connected using the syntax givenbelow.
$ns connect $ping0 $ping4

Dept. of CSE, EWIT Page 10


Computer Network Laboratory 15CSL57
Source code:

set ns [new Simulator]

settf [open ping.tr w]


$ns trace-all $tf

setnf [open ping.nam w]


$ns namtrace-all $nf

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]

$n0 label "Ping0"


$n4 label "Ping4"
$n5 label "Ping5"
$n6 label "Ping6"
$n2 label "Router"

$ns color 1 "red"


$ns color 2 "green"

$ns duplex-link $n0 $n2 100Mb 300ms DropTail


$ns duplex-link $n2 $n6 1Mb 300ms DropTail
$ns duplex-link $n5 $n2 100Mb 300ms DropTail
$ns duplex-link $n2 $n4 1Mb 300ms DropTail
$ns duplex-link $n3 $n2 1Mb 300ms DropTail
$ns duplex-link $n1 $n2 1Mb 300ms DropTail

$ns queue-limit $n0 $n2 5


$ns queue-limit $n2 $n6 2
$ns queue-limit $n2 $n4 3
$ns queue-limit $n5 $n2 5

#The below code is used to connect between the ping agents to the node n0, n4 , n5 and
n6.

set ping0 [new Agent/Ping]


$ns attach-agent $n0 $ping0

set ping4 [new Agent/Ping]


Dept. of CSE, EWIT Page 11
Computer Network Laboratory 15CSL57
$ns attach-agent $n4 $ping4

set ping5 [new Agent/Ping]


$ns attach-agent $n5 $ping5

set ping6 [new Agent/Ping]


$ns attach-agent $n6 $ping6

$ping0 set packetSize_ 50000


$ping0 set interval_ 0.0001

$ping5 set packetSize_ 60000


$ping5 set interval_ 0.00001

$ping0 set class_ 1


$ping5 set class_ 2

$ns connect $ping0 $ping4


$ns connect $ping5 $ping6

#The below function is executed when the ping agent receives a reply from the
destination

Agent/Ping instprocrecv {from rtt} {


$self instvar node_
puts " The node [$node_ id] received an reply from $from with round trip time of $rtt"
}

proc finish {} {
global ns nftf
execnamping.nam&
$ns flush-trace
close $tf
close $nf
exit 0
}

#The below code makes the link down(failure) at 0.9 from n2 to n6 and when the time
becomes 1.5 the link between n2 to n6 is enabled.

$ns rtmodel-at 0.9 down $n2 $n6


$ns rtmodel-at 1.5 up $n2 $n6

$ns at 0.1 "$ping0 send"


$ns at 0.2 "$ping0 send"
$ns at 0.3 "$ping0 send"

Dept. of CSE, EWIT Page 12


Computer Network Laboratory 15CSL57
$ns at 0.4 "$ping0 send"
$ns at 0.5 "$ping0 send"
$ns at 0.6 "$ping0 send"
$ns at 0.7 "$ping0 send"
$ns at 0.8 "$ping0 send"
$ns at 0.9 "$ping0 send"
$ns at 1.0 "$ping0 send"
$ns at 1.1 "$ping0 send"
$ns at 1.2 "$ping0 send"
$ns at 1.3 "$ping0 send"
$ns at 1.4 "$ping0 send"
$ns at 1.5 "$ping0 send"
$ns at 1.6 "$ping0 send"
$ns at 1.7 "$ping0 send"
$ns at 1.8 "$ping0 send"
$ns at 0.1 "$ping5 send"
$ns at 0.2 "$ping5 send"
$ns at 0.3 "$ping5 send"
$ns at 0.4 "$ping5 send"
$ns at 0.5 "$ping5 send"
$ns at 0.6 "$ping5 send"
$ns at 0.7 "$ping5 send"
$ns at 0.8 "$ping5 send"
$ns at 0.9 "$ping5 send"
$ns at 1.0 "$ping5 send"
$ns at 1.1 "$ping5 send"
$ns at 1.2 "$ping5 send"
$ns at 1.3 "$ping5 send"
$ns at 1.4 "$ping5 send"
$ns at 1.5 "$ping5 send"
$ns at 1.6 "$ping5 send"
$ns at 1.7 "$ping5 send"
$ns at 1.8 "$ping5 send"
$ns at 5.0 "finish"
$ns run
AWK Script:
BEGIN{
#include<stdio.h>
count=0;
}
{
if($1==”d”)
count++;
} END {
printf(“Total no. of packets dropped due to congestion is:%d”,count);
}

Dept. of CSE, EWIT Page 13


Computer Network Laboratory 15CSL57
To run:

nsping.tcl
awk –f ping.awk ping.tr
Total no. of packets dropped due to congestion is: 20

Snapshot:

Fig 5: The pinging of the nodes.

Fig 6: RTT taken to receive ping messages between nodes.

Dept. of CSE, EWIT Page 14


Computer Network Laboratory 15CSL57
3. Implement an Ethernet LAN using n nodes and set multiple traffic
nodes and plot congestion window for different source / destination.

Topology Design:

Fig 7: Topology of Ethernet LAN network with 4 nodes.

Note:
The congestion at the nodes can be traced by the followingsteps:
Step 1: Create a file1.tr and file2.tr
set file1 [open file1.tr w]
set file2 [open file2.tr w]
Step 2: Attach these files (file1.tr & file2.tr) to the agents
tcp0 and tcp1 as shown below.
$tcp0attach $file1
$tcp1attach $file2

Step 3: To trace the congestion window value we use the trace


command to trace the congestion window values.
$tcp0 tracecwnd_
$tcp1 tracecwnd_
Then, the congestion window values are stored in the
file1 and file2.
Step 4: To plot the graph the steps are given below
ns lab7.tcl
awk -f lab7.awk file1.tr>tcp1
awk –f lab7.awk file2.tr >tcp2
xgraph –x “Time” -y “cwnd” tcp1tcp2

Dept. of CSE, EWIT Page 15


Computer Network Laboratory 15CSL57
Source code:
set ns [new Simulator]
settf [open lan.tr w]

$ns trace-all $tf

setnf [open lan.nam w]


$ns namtrace-all $nf

set n0 [$ns node]


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

$ns color 1 "red"


$ns color 2 "green"

$ns make-lan "$n0 $n1 $n2 $n3" 10Mb 10ms LL Queue/DropTail Mac/802_3

set tcp0 [new Agent/TCP]


$ns attach-agent $n0 $tcp0

set ftp0 [new Application/FTP]


$ftp0 attach-agent $tcp0

set sink0 [new Agent/TCPSink]


$ns attach-agent $n3 $sink0

$ns connect $tcp0 $sink3

set tcp1 [new Agent/TCP]


$ns attach-agent $n2 $tcp1

set ftp1 [new Application/FTP]


$ftp1 attach-agent $tcp1

set sink1 [new Agent/TCPSink]


$ns attach-agent $n1 $sink1

$ns connect $tcp2 $sink2

######To trace the congestion window#########


set file1 [open file1.tr w]
$tcp0 attach $file1
$tcp0 trace cwnd_

$tcp0 set maxcwnd_ 10

set file2 [open file2.tr w]


$tcp1 attach $file2
$tcp1 trace cwnd_

Dept. of CSE, EWIT Page 16


Computer Network Laboratory 15CSL57

$tcp0 set class_ 1


$tcp1 set class_ 2

proc finish {} {
globalnftf ns
$ns flush-trace
execnamlan.nam&
close $nf
close $tf
exit 0
}
$ns at 0.1 "$ftp0 start"
$ns at 1.5 "$ftp0 stop"

$ns at 2 "$ftp0 start"


$ns at 3 "$ftp0 stop"
$ns at 0.2 "$ftp1 start"
$ns at 2 "$ftp1 stop"

$ns at 2.5 "$ftp1 start"


$ns at 4 "$ftp1 stop"
$ns at 5.0 "finish"
$ns run

AWK Script:

BEGIN {
#include<stdio.h>
}
{
if($6=="cwnd_")
printf("%f\t%f\n",$1,$7);
}
END{
}

To run:

nslan.tcl
awk –f lan.awk file1.tr>tcp0
awk –f lan.awk file2.tr>tcp1
xgraph –x “time” –y “congestion value” tcp0 tcp1

Dept. of CSE, EWIT Page 17


Computer Network Laboratory 15CSL57
Snapshot:

Fig 8: Traffic flow through LAN

Fig 9: The congestion window graph

Dept. of CSE, EWIT Page 18


Computer Network Laboratory 15CSL57
4. Implement simple ESS and with transmitting nodes in wire-less LAN by
simulation and determine the performance with respect to transmission
of packets.

Topology Design:

Fig 10: Simple ESS with 3 wireless nodes.

Simulation parameters:

Area 1000*1000M
Simulation time 250s
No. of wireless nodes 3
Adhoc routing protocol like
adhocRouting
PUMA,DSR,TORA,SODV
llType Link Layer
macType MAC type like Mac/802_11
Propagation model like
propType
Propagation/TwoRayGround
ifqType Interface queue type like Queue/DropTail
ifqLen Interface queue length like 50
phyType Network interface type like Phy/WirelessPhy

Dept. of CSE, EWIT Page 19


Computer Network Laboratory 15CSL57

antType Antenna type like Antenna/OmniAntenna


Channel Channel type like Channel/WirelessChannel
topoInstance The topography instance
agentTrace Tracing at agent level turned ON or OFF
routerTrace Tracing at router level turned ON or OFF

General Operation Director


Two nodes can transmit data to each other if those nodes lie in range of each other. If a
node moves away from range of another node in this case connection will be terminated. For this
purpose ns2 has general operation director (GOD).

GOD (general operation director) keeps information of each node in wireless simulation.
For every wireless simulation GOD need to be created. At time of GOD creation number of
nodes needs to be specified so that GOD can reserve memory space for those nodes for keeping
their information.

Source code:
set ns [new Simulator]
settf [open ess.tr w]
$ns trace-all $tf

settopo [new Topography]


$topoload_flatgrid 1000 1000

setnf [open ess.nam w]


$ns namtrace-all-wireless $nf 1000 1000

$ns node-config -adhocRouting DSDV \


-llType LL \
-macType Mac/802_11 \
-ifqType Queue/DropTail \
-ifqLen 50 \
-phyTypePhy/WirelessPhy \
-channelType Channel/WirelessChannel \
-propType Propagation/TwoRayGround \
-antType Antenna/OmniAntenna \
-topoInstance $topo \
-agentTrace ON \
-routerTrace ON

create-god 3
set n0 [$ns node]

Dept. of CSE, EWIT Page 20


Computer Network Laboratory 15CSL57
set n1 [$ns node]
set n2 [$ns node]

$n0 label "tcp0"


$n1 label "sink1/tcp1"
$n2 label "sink2"

$n0 set X_ 50
$n0 set Y_ 50
$n0 set Z_ 0

$n1 set X_ 100


$n1 set Y_ 100
$n1 set Z_ 0

$n2 set X_ 600


$n2 set Y_ 600
$n2 set Z_ 0
$ns at 0.1 "$n0 setdest 50 50 15"
$ns at 0.1 "$n1 setdest 100 100 25"
$ns at 0.1 "$n2 setdest 600 600 25"

set tcp0 [new Agent/TCP]


$ns attach-agent $n0 $tcp0
set ftp0 [new Application/FTP]
$ftp0 attach-agent $tcp0
set sink1 [new Agent/TCPSink]
$ns attach-agent $n1 $sink1
$ns connect $tcp0 $sink1

set tcp1 [new Agent/TCP]


$ns attach-agent $n1 $tcp1
set ftp1 [new Application/FTP]
$ftp1 attach-agent $tcp1
set sink2 [new Agent/TCPSink]
$ns attach-agent $n2 $sink2
$ns connect $tcp1 $sink2

$ns at 5 "$ftp0 start"


$ns at 5 "$ftp1 start"

$ns at 100 "$n1 setdest 550 550 15"


$ns at 190 "$n1 setdest 70 70 15"

proc finish {} {
global ns nftf
$ns flush-trace

Dept. of CSE, EWIT Page 21


Computer Network Laboratory 15CSL57
execnam lab8.nam &
close $tf
exit 0
}
$ns at 250 "finish"
$ns run

AWK Script

BEGIN {
#includ<stdio.h>
count1=0
count2=0
pack1=0
pack2=0
time1=0
time2=0
}
{
if($1=="r"&&$3=="_1_"&&$4=="AGT")
{
count1++
pack1=pack1+$8
time1=$2
}
if($1=="r"&&$3=="_2_"&&$4=="AGT")
{
count2++
pack2=pack2+$8
time2=$2

}
} END{

printf("the throughput from n0 to n1:%f Mbps\n",((count1*pack1*8)/(time1*1000000)));


printf("the throughput from n1 to n2:%f Mbps\n",((count2*pack2*8)/(time2*1000000)));

To run:
nsess.tcl

awk –f ess.awk ess.tr

Snapshot:

Dept. of CSE, EWIT Page 22


Computer Network Laboratory 15CSL57

Fig 11: Data transmission among wireless nodes.

Dept. of CSE, EWIT Page 23


Computer Network Laboratory 15CSL57
5. Implement and study the performance of GSM on NS2/NS3 (Using MAC
layer) or equivalent environment.

Second Generation (2G) technology is based on the technology known as global system
for mobile communication (GSM). This technology enabled various networks to provide services
like text messages, picture messages and MMS. The technologies used in 2G are either TDMA
(Time Division Multiple Access) which divides signal into different time slots or CDMA (Code
Division Multiple Access) which allocates a special code to each user so as to communicate over
a multiplex physical channel.

GSM uses a variation of time division multiple access (TDMA). 2G networks developed
as a replacement for first generation (1G) analog cellular networks, and the GSM standard
originally described as a digital, circuit-switched network optimized for fullduplex voice
telephony. This expanded over time to include data communications, first by circuit-switched
transport, then by packet data transport via GPRS (General Packet Radio Services).

GSM can be implemented on all the versions of NS2 (Since year 2004: ns-2.27, and later
versions of NS2)

Topology Design:

Fig 12: Topology design of GSM network.

Dept. of CSE, EWIT Page 24


Computer Network Laboratory 15CSL57
Source code:
# General Parameters
set opt(title) zero ;
set opt(stop) 100 ;# Stop time.
set opt(ecn) 0 ;
# Topology
set opt(type) gsm ;#type of link:
set opt(secondDelay) 55 ;# average delay of access links in ms
# AQM parameters
set opt(minth) 30 ;
set opt(maxth) 0 ;
set opt(adaptive) 1 ;# 1 for Adaptive RED, 0 for plain RED
# Traffic generation.
set opt(flows) 0 ;# number of long-lived TCP flows
set opt(window) 30 ;# window for long-lived traffic
set opt(web) 2 ;# number of web sessions
# plotting statistics.
set opt(quiet) 0 ;# popup anything?
set opt(wrap) 100 ;# wrap plot1s?
set opt(srcTrace) is ;# where to plot1 traffic
set opt(dstTrace) bs2 ;# where to plot1 traffic
set opt(gsmbuf) 10 ; # buffer size for gsm

#default downlink bandwidth in bps


setbwDL(gsm) 9600
#default uplink bandwidth in bps
setbwUL(gsm) 9600
#default downlink propagation delay in seconds
setpropDL(gsm) .500
#default uplink propagation delay in seconds
setpropUL(gsm) .500
#default buffer size in packets
setbuf(gsm) 10

set ns [new Simulator]


settf [open out1.tr w]
$ns trace-all $tf

set nodes(is) [$ns node]


set nodes(ms) [$ns node]
set nodes(bs1) [$ns node]
set nodes(bs2) [$ns node]
set nodes(lp) [$ns node]

Dept. of CSE, EWIT Page 25


Computer Network Laboratory 15CSL57
proccell_topo {} {
global ns nodes
$ns duplex-link $nodes(lp) $nodes(bs1) 3Mbps 10ms DropTail
$ns duplex-link $nodes(bs1) $nodes(ms) 1 1 RED
$ns duplex-link $nodes(ms) $nodes(bs2) 1 1 RED
$ns duplex-link $nodes(bs2) $nodes(is) 3Mbps 50ms DropTail
puts "Cell Topology"
}
procset_link_params {t} {
global ns nodes bwULbwDLpropULpropDLbuf
$ns bandwidth $nodes(bs1) $nodes(ms) $bwDL($t) simplex
$ns bandwidth $nodes(ms) $nodes(bs1) $bwUL($t) simplex
$ns bandwidth $nodes(bs2) $nodes(ms) $bwDL($t) simplex
$ns bandwidth $nodes(ms) $nodes(bs2) $bwUL($t) simplex
$ns delay $nodes(bs1) $nodes(ms) $propDL($t) simplex
$ns delay $nodes(ms) $nodes(bs1) $propDL($t) simplex
$ns delay $nodes(bs2) $nodes(ms) $propDL($t) simplex
$ns delay $nodes(ms) $nodes(bs2) $propDL($t) simplex
$ns queue-limit $nodes(bs1) $nodes(ms) $buf($t)
$ns queue-limit $nodes(ms) $nodes(bs1) $buf($t)
$ns queue-limit $nodes(bs2) $nodes(ms) $buf($t)
$ns queue-limit $nodes(ms) $nodes(bs2) $buf($t)
}
# RED and TCP parameters
Queue/RED set summarystats_ true
Queue/DropTail set summarystats_ true
Queue/RED set adaptive_ $opt(adaptive)
Queue/RED set q_weight_ 0.0
Queue/RED set thresh_ $opt(minth)
Queue/RED set maxthresh_ $opt(maxth)
Queue/DropTail set shrink_drops_ true
Agent/TCP set ecn_ $opt(ecn)
Agent/TCP set window_ $opt(window)
DelayLink set avoidReordering_ true

sourceweb.tcl

#Create topology
switch $opt(type) {
gsm -
gprs -
umts {cell_topo}
}
set_link_params $opt(type)
$ns insert-delayer $nodes(ms) $nodes(bs1) [new Delayer]
$ns insert-delayer $nodes(bs1) $nodes(ms) [new Delayer]
$ns insert-delayer $nodes(ms) $nodes(bs2) [new Delayer]
$ns insert-delayer $nodes(bs2) $nodes(ms) [new Delayer]

Dept. of CSE, EWIT Page 26


Computer Network Laboratory 15CSL57
# Set up forward TCP connection
if {$opt(flows) == 0} {
set tcp1 [$ns create-connection TCP/Sack1 $nodes(is) TCPSink/Sack1 $nodes(lp) 0]
set ftp1 [[set tcp1] attach-app FTP]
$ns at 0.8 "[set ftp1] start"
}
if {$opt(flows) > 0} {
set tcp1 [$ns create-connection TCP/Sack1 $nodes(is) TCPSink/Sack1 $nodes(lp) 0]
set ftp1 [[set tcp1] attach-app FTP]
$tcp1 set window_ 100
$ns at 0.0 "[set ftp1] start"
$ns at 3.5 "[set ftp1] stop"
set tcp2 [$ns create-connection TCP/Sack1 $nodes(is) TCPSink/Sack1 $nodes(lp) 0]
set ftp2 [[set tcp2] attach-app FTP]
$tcp2 set window_ 3
$ns at 1.0 "[set ftp2] start"
$ns at 8.0 "[set ftp2] stop"
}

proc stop {} {
global nodes opt nf
set wrap $opt(wrap)
setsid [$nodes($opt(srcTrace)) id]
set did [$nodes($opt(dstTrace)) id]
if {$opt(srcTrace) == "is"} {
set a "-a out1.tr"
} else {
set a "out1.tr"
}
set GETRC "/home/dell/ns-allinone-2.35/ns-2.35/bin/getrc"
set RAW2XG "/home/dell/ns-allinone-2.35/ns-2.35/bin/raw2xg"

exec $GETRC -s $sid -d $did -f 0 out1.tr | $RAW2XG -s 0.01 -m $wrap -r >> plot1.xgr
exec $GETRC -s $did -d $sid -f 0 out1.tr | $RAW2XG -a -s 0.01 -m $wrap >> plot1.xgr

exec $GETRC -s $sid -d $did -f 1 out1.tr | $RAW2XG -s 0.01 -m $wrap -r >> plot1.xgr
exec $GETRC -s $did -d $sid -f 1 out1.tr | $RAW2XG -s 0.01 -m $wrap -a >> plot1.xgr

exec ./xg2gp.awk plot1.xgr


if {!$opt(quiet)} {
execxgraph -bb -tk -nl -m -x "time" -y "packets" plot1.xgr &
}
exit 0
}
$ns at $opt(stop) "stop"
$ns run

Dept. of CSE, EWIT Page 27


Computer Network Laboratory 15CSL57
To run:
nsgsm.tcl

Snapshot:

Fig 13: Performance of GSM.

Dept. of CSE, EWIT Page 28


Computer Network Laboratory 15CSL57
6. Implement and study the performance of CDMA on NS2/NS3 (Using stack
called Call net) or equivalent environment.
3G networks developed as a replacement for second generation (2G) GSM standard
network with full duplex voice telephony. CDMA is used as the access method in many
mobilephone standards. IS-95, also called cdmaOne, and its 3G evolution CDMA2000, are often
simply referred to as CDMA, but UMTS(The Universal Mobile Telecommunications System is a
third generation mobile cellular system for networks based on the GSM standard.), the 3G
standard used by GSM carriers, also uses wideband CDMA. Long-Term Evolution (LTE) is a
standard for high-speed wireless communication which uses CDMA network technology.

3G technology generally refers to the standard of accessibility and speed of mobile


devices. The standards of the technology were set by the International Telecommunication Union
(ITU). This technology enables use of various services like GPS (Global PositioningSystem),
mobile television and video conferencing. It not only enables them to be used worldwide, but
also provides with better bandwidth and increased speed. The main aim of this technology is to
allow much better coverage and growth with minimum investment.

CDMA can be implemented on all the versions of NS2 (Since year 2004: ns-2.27, and later
versions of NS2)

Topology Design:

Fig 14: Topology of CDMA network.

Dept. of CSE, EWIT Page 29


Computer Network Laboratory 15CSL57
Source code:
# General Parameters
set opt(title) zero ;
set opt(stop) 100 ;# Stop time.
set opt(ecn) 0 ;
# Topology
set opt(type) umts ;#type of link:
set opt(secondDelay) 55 ;# average delay of access links in ms
# AQM parameters
set opt(minth) 30 ;
set opt(maxth) 0 ;
set opt(adaptive) 1 ;# 1 for Adaptive RED, 0 for plain RED
# Traffic generation.
set opt(flows) 0 ;# number of long-lived TCP flows
set opt(window) 30 ;# window for long-lived traffic
set opt(web) 2 ;# number of web sessions
# Plotting statistics.
set opt(quiet) 0 ;# popup anything?
set opt(wrap) 100 ;# wrap plots?
set opt(srcTrace) is ;# where to plot traffic
set opt(dstTrace) bs2 ;# where to plot traffic
set opt(umtsbuf) 10 ; # buffer size for umts

#default downlink bandwidth in bps


setbwDL(umts) 384000
#default uplink bandwidth in bps
setbwUL(umts) 64000
#default downlink propagation delay in seconds
setpropDL(umts) .150
#default uplink propagation delay in seconds
setpropUL(umts) .150
#default buffer size in packets
setbuf(umts) 20

set ns [new Simulator]


settf [open out.tr w]
$ns trace-all $tf

set nodes(is) [$ns node]


set nodes(ms) [$ns node]
set nodes(bs1) [$ns node]
set nodes(bs2) [$ns node]
set nodes(lp) [$ns node]

proccell_topo {} {
global ns nodes
$ns duplex-link $nodes(lp) $nodes(bs1) 3Mbps 10ms DropTail

Dept. of CSE, EWIT Page 30


Computer Network Laboratory 15CSL57
$ns duplex-link $nodes(bs1) $nodes(ms) 1 1 RED
$ns duplex-link $nodes(ms) $nodes(bs2) 1 1 RED
$ns duplex-link $nodes(bs2) $nodes(is) 3Mbps 50ms DropTail
puts "Cell Topology"
}
procset_link_params {t} {
global ns nodes bwULbwDLpropULpropDLbuf
$ns bandwidth $nodes(bs1) $nodes(ms) $bwDL($t) simplex
$ns bandwidth $nodes(ms) $nodes(bs1) $bwUL($t) simplex
$ns delay $nodes(bs1) $nodes(ms) $propDL($t) simplex
$ns delay $nodes(ms) $nodes(bs1) $propDL($t) simplex
$ns queue-limit $nodes(bs1) $nodes(ms) $buf($t)
$ns queue-limit $nodes(ms) $nodes(bs1) $buf($t)
$ns bandwidth $nodes(bs2) $nodes(ms) $bwDL($t) simplex
$ns bandwidth $nodes(ms) $nodes(bs2) $bwUL($t) simplex
$ns delay $nodes(bs2) $nodes(ms) $propDL($t) simplex
$ns delay $nodes(ms) $nodes(bs2) $propDL($t) simplex
$ns queue-limit $nodes(bs2) $nodes(ms) $buf($t)
$ns queue-limit $nodes(ms) $nodes(bs2) $buf($t)
}

# RED and TCP parameters


Queue/RED set summarystats_ true
Queue/DropTail set summarystats_ true
Queue/RED set adaptive_ $opt(adaptive)
Queue/RED set q_weight_ 0.0
Queue/RED set thresh_ $opt(minth)
Queue/RED set maxthresh_ $opt(maxth)
Queue/DropTail set shrink_drops_ true
Agent/TCP set ecn_ $opt(ecn)
Agent/TCP set window_ $opt(window)
DelayLink set avoidReordering_ true

sourceweb.tcl

#Create topology
switch $opt(type) {
umts {cell_topo}
}
set_link_params $opt(type)
$ns insert-delayer $nodes(ms) $nodes(bs1) [new Delayer]
$ns insert-delayer $nodes(bs1) $nodes(ms) [new Delayer]
$ns insert-delayer $nodes(ms) $nodes(bs2) [new Delayer]
$ns insert-delayer $nodes(bs2) $nodes(ms) [new Delayer]

# Set up forward TCP connection


if {$opt(flows) == 0} {
set tcp1 [$ns create-connection TCP/Sack1 $nodes(is) TCPSink/Sack1 $nodes(lp) 0]

Dept. of CSE, EWIT Page 31


Computer Network Laboratory 15CSL57
set ftp1 [[set tcp1] attach-app FTP]
$ns at 0.8 "[set ftp1] start"
}
if {$opt(flows) > 0} {
set tcp1 [$ns create-connection TCP/Sack1 $nodes(is) TCPSink/Sack1 $nodes(lp) 0]
set ftp1 [[set tcp1] attach-app FTP]
$tcp1 set window_ 100
$ns at 0.0 "[set ftp1] start"
$ns at 3.5 "[set ftp1] stop"
set tcp2 [$ns create-connection TCP/Sack1 $nodes(is) TCPSink/Sack1 $nodes(lp) 0]
set ftp2 [[set tcp2] attach-app FTP]
$tcp2 set window_ 3
$ns at 1.0 "[set ftp2] start"
$ns at 8.0 "[set ftp2] stop"
}

proc stop {} {
global nodes opt nf
set wrap $opt(wrap)
setsid [$nodes($opt(srcTrace)) id]
set did [$nodes($opt(dstTrace)) id]
if {$opt(srcTrace) == "is"} {
set a "-a out.tr"
} else {
set a "out.tr"
}
set GETRC "/home/dell/ns-allinone-2.35/ns-2.35/bin/getrc"
set RAW2XG "/home/dell/ns-allinone-2.35/ns-2.35/bin/raw2xg"

exec $GETRC -s $sid -d $did -f 0 out.tr | $RAW2XG -s 0.01 -m $wrap -r >plot.xgr


exec $GETRC -s $did -d $sid -f 0 out.tr | $RAW2XG -a -s 0.01 -m $wrap >>plot.xgr

exec $GETRC -s $sid -d $did -f 1 out.tr | $RAW2XG -s 0.01 -m $wrap -r >>plot.xgr


exec $GETRC -s $did -d $sid -f 1 out.tr | $RAW2XG -s 0.01 -m $wrap -a >>plot.xgr

exec ./xg2gp.awk plot.xgr


if {!$opt(quiet)} {
execxgraph -bb -tk -nl -m -x "time" -y "packets" plot.xgr&
}
exit 0
}
$ns at $opt(stop) "stop"
$ns run

To run:

nscdma.tcl
Snapshot:

Dept. of CSE, EWIT Page 32


Computer Network Laboratory 15CSL57

Fig 15: Performance of CDMA network.

Dept. of CSE, EWIT Page 33


Computer Network Laboratory 15CSL57
PART B
7. Write a program for error detecting code using CRC-CCITT (16- bits).

The cyclic redundancy check (CRC) is a technique used to detect errors in digital data.
CRC is a hash function that detects accidental changes to raw computer data commonly used in
digital telecommunications networks and storage devices such as hard disk drives. This
technique was invented by W. Wesley Peterson in 1961 and further developed by the CCITT
(International Telegraph and Telephone Consultative Committee). Cyclic redundancy checks are
quite simple to implement in hardware and can be easily analyzed mathematically. It is one of
the better techniques in detecting common transmission errors.

As explained above cyclic redundancy check is also applied to storage devices like hard
disks. In this case, check bits are allocated to each block in the hard disk. When a corrupt or
incomplete file is read by the computer, the cyclic redundancy error is reported. This could be
from another storage device or from CD/DVDs. The common reasons for errors include system
crashes, incomplete or corrupt files, or files with lots of bugs.

Fig 16: Block diagram of CRC.

Dept. of CSE, EWIT Page 34


Computer Network Laboratory 15CSL57
Steps:
 First, a string of n-1 0s is appended to the data unit.

 The number of 0s is one less than the number of bits in the divisor which is n bits.

 Then the newly elongated data unit is divided by the divisor using a process called binary
division (XOR).

 The remainder is CRC. The CRC replaces the appended 0s at the end of the data unit.

 The data unit arrives at the receiver first, followed by the CRC.

 The receiver treats whole string as the data unit and divides it by the same divisor that was
used to find the CRC remainder.

 If the remainder is 0 then the data unit is error free. Otherwise it having some error and it
must be discarded.

Source code:

import java.io.*;
importjava.util.*;
class CRC
{
public static void main(String a[]) throws IOException
{
Scanner sc=new Scanner(System.in);
int[] message;
int[] gen;
int[] app_message;
int[] rem;
int[] trans_message;
intmessage_bits,gen_bits,total_bits;

System.out.println("Enter no bits in mwssage:");


message_bits=sc.nextInt();

message=new int [message_bits];


System.out.println("\nEnter message bits:");
for(int i=0; i<message_bits;i++)
message[i]= sc.nextInt();

System.out.println("\nEnter number of bits in gen:");


gen_bits= sc.nextInt();

Dept. of CSE, EWIT Page 35


Computer Network Laboratory 15CSL57

gen=new int[gen_bits];
System.out.println("\nEnter gen bits:");
for(int i=0;i<gen_bits;i++)
gen[i]= sc.nextInt();

total_bits=message_bits+gen_bits-1;

app_message=new int[total_bits];
rem=new int[total_bits];
trans_message=new int[total_bits];

for(int i=0;i<message.length;i++)
app_message[i]=message[i];

System.out.println("\nMessage bits are:");


for(int i=0;i<message_bits;i++)
System.out.print("\t"+message[i]);

System.out.println("\nGenerators bits are:");


for(int i=0;i<gen_bits;i++)
System.out.print("\t"+gen[i]);

System.out.println("\nAppended message is:");


for(int i=0;i<app_message.length;i++)
System.out.print("\t"+app_message[i]);

for(int j=0;j<app_message.length;j++)
rem[j]=app_message[j];

rem=computecrc(app_message,gen,rem);

for(int i=0;i<app_message.length;i++)
trans_message[i]=(app_message[i]^rem[i]);

System.out.println("\nTransmitted message from the transmitter is:");


for(int i=0;i<trans_message.length;i++)
System.out.print("\t"+trans_message[i]);

System.out.println("\nEnter received message of"+total_bits+"bits at receiver


end:");
for(int i=0;i<trans_message.length;i++)
trans_message[i]=sc.nextInt();

System.out.println("\nReceived message is:");


for(int i=0;i<trans_message.length;i++)
System.out.print("\t"+trans_message[i]);

Dept. of CSE, EWIT Page 36


Computer Network Laboratory 15CSL57
for(int j=0;j<trans_message.length;j++)
rem[j]=trans_message[j];

rem=computecrc(trans_message,gen,rem);
for(int i=0;i<rem.length;i++)
{
if(rem[i]!=0)
{
System.out.println("\nThere is error in the received message");
break;
}
if(i==rem.length-1)
System.out.println("\nThere is no erron in the received mesage!!");
}
}
staticint[] computecrc(intapp_message[],int gen[], int rem[])
{
int current=0;
while(true)
{
for(int i=0;i<gen.length;i++)
rem[current+i]=(rem[current+i]^gen[i]);
while(rem[current]==0 && current!=rem.length-1)
current++;
if((rem.length-current)<gen.length)
break;
}
return rem;
}
}

Dept. of CSE, EWIT Page 37


Computer Network Laboratory 15CSL57
Snapshot:

Fig 17: Output of CRC 16 bits.

Dept. of CSE, EWIT Page 38


Computer Network Laboratory 15CSL57

8. Write a program to find the shortest path between vertices using bellman-
ford algorithm.

Algorithm

Steps:

Input:Graph and a source vertexsrc.

Output: Shortest distance to all vertices from src. If there is a negative weight cycle, then
shortest distances are not calculated, negative weight cycle is reported.

1. This step initializes distances from source to all vertices as infinite and distance to source itself
as 0. Create an array dist[] of size |V| with all values as infinite except dist[src] where src is
source vertex.

2. This step calculates shortest distances. Do following |V|-1 times where |V| is the number of
vertices in given graph.

a)Do following for each edge u-v.

If dist[v] >dist[u] + weight of edge uv, then update dist[v].

dist[v] = dist[u] + weight of edge uv

3. This step reports if there is a negative weight cycle in graph. Do following for each edge u-v.

If dist[v] >dist[u] + weight of edge uv, then

“Graph contains negative weight cycle”.

The idea of step 3 is, step 2 guarantees shortest distances if graph doesn’t contain
negative weight cycle. If we iterate through all edges one more time and get a shorter path for
any vertex, then there is a negative weight cycle.

Dept. of CSE, EWIT Page 39


Computer Network Laboratory 15CSL57

Source Code:

importjava.util.Scanner;
public class BellmanFord
{
privateint D[];
privateintNoV;
public static final int MAX_VALUE = 999;

publicBellmanFord(intNoV)
{
this.NoV = NoV;
D = new int[NoV + 1];
}
public void BellmanFordEvaluation(int source, int A[][])
{
for (int node = 1; node <= NoV; node++)
{
D[node] = MAX_VALUE;
}
D[source] = 0;
for (int node = 1; node <= NoV - 1; node++)
{
for (int i = 1; i <= NoV; i++)
{
for (int j = 1; j <= NoV; j++)
{
if (A[i][j] != MAX_VALUE)
{
if (D[j] > D[i] + A[i][j])
D[j] = D[i]+ A[i][j];
}
}
}
}
for (int i = 1; i <= NoV; i++)
{
for (int j = 1; j <= NoV; j++)
{
if (A[i][j] != MAX_VALUE)
{
if (D[j] > D[i]+ A[i][j])
{
System.out.println("The Graph contains negative
egde cycle");
return;
}

Dept. of CSE, EWIT Page 40


Computer Network Laboratory 15CSL57
}
}
}
for (int vertex = 1; vertex <= NoV; vertex++)
{
System.out.println("distance of source " + source + " to "+ vertex + " is "
+ D[vertex]);
}
}

public static void main(String... arg)


{
intNoV = 0;
int source;
Scanner scanner = new Scanner(System.in);

System.out.println("Enter the number of vertices");


NoV = scanner.nextInt();
int A[][] = new int[NoV + 1][NoV + 1];

System.out.println("Enter the adjacency matrix");


for (int i = 1; i <= NoV; i++)
{
for (int j = 1; j <= NoV; j++)
{
A[i][j] = scanner.nextInt();
}
}

System.out.println("Enter the source vertex");


source = scanner.nextInt();
BellmanFordbellmanford = new BellmanFord(NoV);
bellmanford.BellmanFordEvaluation(source, A);
scanner.close();
}
}

Fig 18: Example directed graph

Dept. of CSE, EWIT Page 41


Computer Network Laboratory 15CSL57
Snapshot:

Fig 19: Output of Bellman Ford algorithm

Dept. of CSE, EWIT Page 42


Computer Network Laboratory 15CSL57
9. Using TCP/IP sockets, write a client – server program to make the client
send the file name and to make the server send back the contents of the
requested file if present.

Fig 20: TCP client/server communication flow.

Dept. of CSE, EWIT Page 43


Computer Network Laboratory 15CSL57
Methods and description

 publicServerSocket(int port) throws IOException: Attempts to create a server socket


bound to the specified port. An exception occurs if the port is already bound by another
application.

 public Socket accept() throws IOException: Waits for an incoming client. This
method blocks until either a client connects to the server on the specified port or the
socket times out, assuming that the time-out value has been set using the setSoTimeout()
method. Otherwise, this method blocks indefinitely.

 public Socket(InetAddress host, int port) throws IOException: This method attempts
to connect to the specified server at the specified port. If this constructor does not throw
an exception, the connection is successful and the client is connected to the server.

 publicInetAddressgetInetAddress(): This method returns the address of the other


computer that this socket is connected to.

 publicintgetPort(): Returns the port the socket is bound to on the remote machine.

 publicInputStreamgetInputStream() throws IOException: Returns the input stream


of the socket. The input stream is connected to the output stream of the remote socket.

 publicOutputStreamgetOutputStream() throws IOException: Returns the output


stream of the socket. The output stream is connected to the input stream of the remote
socket.

Dept. of CSE, EWIT Page 44


Computer Network Laboratory 15CSL57
TCP Server Source code:

import java.net.*;
import java.io.*;
public class ContentsServer
{
public static void main(String args[]) throws Exception
{ // establishing the connection with the server
ServerSocketsersock = new ServerSocket(4000);
System.out.println("Server ready for connection");
Socket sock = sersock.accept(); // binding with port: 4000
System.out.println("Connection is successful and wating for chatting");

// reading the file name from client


InputStreamistream = sock.getInputStream( );
BufferedReaderfileRead =new BufferedReader(new InputStreamReader(istream));
String fname = fileRead.readLine( );
// reading file contents
BufferedReadercontentRead = new BufferedReader(new FileReader(fname) );

// keeping output stream ready to send the contents


OutputStreamostream = sock.getOutputStream( );
PrintWriterpwrite = new PrintWriter(ostream, true);

String str;
while((str = contentRead.readLine()) != null) // reading line-by-line from file
{
pwrite.println(str); // sending each line to client
}

sock.close(); sersock.close(); // closing network sockets


pwrite.close(); fileRead.close(); contentRead.close();
}
}

Dept. of CSE, EWIT Page 45


Computer Network Laboratory 15CSL57
TCP Client Source code:

import java.net.*;
import java.io.*;
public class ContentsClient
{
public static void main( String args[ ] ) throws Exception
{
Socket sock = new Socket( "127.0.0.1", 4000);

// reading the file name from keyboard. Uses input stream


System.out.print("Enter the file name: ");
BufferedReaderkeyRead = new BufferedReader(new InputStreamReader(System.in));
String fname = keyRead.readLine();

// sending the file name to server. Uses PrintWriter


OutputStreamostream = sock.getOutputStream( );
PrintWriterpwrite = new PrintWriter(ostream, true);
pwrite.println(fname);
// receiving the contents from server. Uses input stream
InputStreamistream = sock.getInputStream();
BufferedReadersocketRead = new BufferedReader(new InputStreamReader(istream));

String str;
while((str = socketRead.readLine()) != null) // reading line-by-line
{
System.out.println(str);
}
pwrite.close(); socketRead.close(); keyRead.close();
}
}

Dept. of CSE, EWIT Page 46


Computer Network Laboratory 15CSL57
Snapshot:

Fig 21: TCP server

Fig 22: TCP client.

Dept. of CSE, EWIT Page 47


Computer Network Laboratory 15CSL57
10. Write a program on datagram socket for client/server to display the
messages on client side, typed at the server side.

Fig 23: UDP client/server communication flow.

Methods and description

 DatagramSocket(int port) throws SocketEeption: it creates a datagram socket and


binds it with the given Port Number.
 DatagramPacket(byte[] buffer, int length): it creates a datagram packet. This
constructor is used to receive the packets.

Dept. of CSE, EWIT Page 48


Computer Network Laboratory 15CSL57

 DatagramPacket(byte[] buffer, int length, InetAddress address, int port): it creates a


datagram packet. This constructor is used to send the packets.

UDP Server Source code:


import java.io.*;
import java.net.*;
importjava.util.*;
public class udps
{
public static void main(String[] args)
{
DatagramSocketskt=null;
Scanner sc=new Scanner(System.in);
try
{
skt=new DatagramSocket(2400);
byte[] buffer=new byte[1000];
while(true)
{
DatagramPacket request=new DatagramPacket(buffer,buffer.length);
skt.receive(request);
String message=sc.nextLine();
byte[] sendMsg=message.getBytes();
DatagramPacket reply=new
DatagramPacket(sendMsg,sendMsg.length,request.getAddress(),request.getPort());
skt.send(reply);
}
}
catch(Exception ex)
{
}
}
}

Dept. of CSE, EWIT Page 49


Computer Network Laboratory 15CSL57
UDP Client Source code:

import java.io.*;
import java.net.*;
public class udpc
{
public static void main(String[] args)
{
DatagramSocketskt;
try
{
skt=new DatagramSocket();
String msg="text message";
byte[]b=msg.getBytes();
InetAddress host=InetAddress.getByName("127.0.0.1");
intserverSocket=2400;
DatagramPacket request=new DatagramPacket(b,b.length,host,serverSocket);
skt.send(request);
byte[]buffer=new byte[1000];
DatagramPacket reply=new DatagramPacket(buffer,buffer.length);
skt.receive(reply);
System.out.println("client recieved:"+new String(reply.getData()));
skt.close();
}
catch(Exception ex){}
}
}

Dept. of CSE, EWIT Page 50


Computer Network Laboratory 15CSL57
Snapshot:

Fig 24: UDP server

Fig 25: UDP client

Dept. of CSE, EWIT Page 51


Computer Network Laboratory 15CSL57
11. Write a program for simple RSA algorithm to encrypt and decrypt the data.
RSA is an algorithm used by modern computers to encrypt and decrypt messages. It is an
asymmetric cryptographic algorithm. Asymmetric means that there are two different keys (one is
public key and another is private key). This is also called public key cryptography, because one
of them can be given to everyone. The other key must be kept private. It is based on the fact that
finding the factors of an integer is hard (the factoring problem). RSA stands for Ron Rivest, Adi
Shamir and Leonard Adleman, who first publicly described it in 1978.
Following are the steps of RSA algorithm.
Key Generation
1. Generate two large prime numbers p and q, such that p!=q.
2. Let n=p*q.
3. Let t=(p-1)*(q-1)
4. Choose a small number e, co-prime to t, with
GCD (t, e) =1 and 1<e<t.
5. Find d, such that d*e mod t=1.
Publish e and n as public key.
Keep d and t as secret key.

Encryption
Cipher = (Message)e mod n
Decryption

Message = (Cipher)d mod n

Dept. of CSE, EWIT Page 52


Computer Network Laboratory 15CSL57
Source code:
importjava.util.Scanner;
public class RSA
{
public static intp,q,n,t,flag,msg,m,temp;
public static int e[]=new int[100];
public static int d[]=new int[100];
public static int prime( intpr)
{
int i;

Double a=(Math.sqrt(pr));
m=a.intValue();

for (i=2;i<=m;i++)
{
if(pr%i==0)
return 0;
}

return 1;

public static void ce()


{
int k=0;

for (int i=2;i<t;i++)


{
if(t%i==0)
continue;

flag=prime(i);

if(flag==1&&i!=p&&i!=q)
{

e[k]=i;
flag=cd(e[k]);

if(flag>0)
{
d[k]=flag;
k++;
}

Dept. of CSE, EWIT Page 53


Computer Network Laboratory 15CSL57
if(k==99)
break;
}
}
}

public static int cd( int x)


{
int k=1;

while(true)
{
k=k+t;

if(k%x==0)
return(k/x);
}

public static void encrypt()


{

intpt,ct,key=e[0],k;

pt=msg;
k=1;

for (int j=0;j<key;j++)


{

k=k*pt;

k=k%n;
}

ct=k;
temp=ct;
System.out.println("\nTHE ENCRYPTED MESSAGE IS:"+ct);

public static void decrypt()


{
intpt,ct,key=d[0],k;
ct=temp;

k=1;

Dept. of CSE, EWIT Page 54


Computer Network Laboratory 15CSL57

for (int j=0;j<key;j++)


{
k=k*ct;
k=k%n;
}

pt=k;

System.out.println("\nTHE DECRYPTED MESSAGE IS:"+pt);


}

public static void main(String args[])


{
Scanner sc=new Scanner(System.in);
System.out.println("ENTER FIRST PRIME NUMBER");
p=sc.nextInt();
flag=prime(p);
if(flag==0)
{
System.out.println("WRONG INPUT");
System.exit(1);
}

System.out.println("ENTER ANOTHER PRIME NUMBER");


q=sc.nextInt();
flag=prime(q);
if(flag==0||p==q)
{
System.out.println("WRONG INPUT");
System.exit(1);
}

System.out.println("ENTER MESSAGE");
msg=sc.nextInt();
n=p*q;
t=(p-1)*(q-1);

ce();

System.out.println("POSSIBLE VALUES OF e AND d ARE");


for (int i=0;i< m-1;i++)
System.out.printf("\n%d\t%d",e[i],d[i]);

encrypt();
decrypt();
}
}

Dept. of CSE, EWIT Page 55


Computer Network Laboratory 15CSL57
Snapshot:

Fig 26: Simple RSA encryption and decryption.

Dept. of CSE, EWIT Page 56


Computer Network Laboratory 15CSL57
12. Write a program for congestion control using leaky bucket algorithm.
To understand this concept first we have to know little about traffic shaping.
Traffic Shaping: This is a mechanism to control the amount and the rate of the traffic sent to the
network.
Two techniques can shape traffic:
1. Leaky Bucket
2. Token Bucket.
Suppose we have a bucket in which we are pouring water in a random order but we have to get
water in a fixed rate, for this we will make a hole at the bottom of the bucket. It will ensure that
water coming out is in some fixed rate. And also if bucket is full we will stop pouring in it.
The input rate can vary, but the output rate remains constant. Similarly, in networking, a
technique called leaky bucket can smooth out bursty traffic. Bursty chunks are stored in the
bucket and sent out at an average rate.

Fig 27: Leaky bucket scenario

In the above figure, we assume that the network has committed a bandwidth of 3 Mbps for a
host. The use of the leaky bucket shapes the input traffic to make it conform to this commitment.
In Figure the host sends a burst of data at a rate of 12 Mbps for 2 s, for a total of 24 Mbits of
data. The host is silent for 5 s and then sends data at a rate of 2 Mbps for 3 s, for a total of 6
Mbits of data. In all, the host has sent 30 Mbits of data in 10 s. The leaky bucket smoothes the
traffic by sending out data at a rate of 3 Mbps during the same 10 s. Without the leaky bucket,

Dept. of CSE, EWIT Page 57


Computer Network Laboratory 15CSL57
the beginning burst may have hurt the network by consuming more bandwidth than is set aside
for this host. We can also see that the leaky bucket may prevent congestion.
Source code:

importjava.util.Random;
import java.util.Scanner;
public class Leaky
{
public static intbsize=0,packet,tgen,j=1;
public static String stop;
public static final intbmax=1024;
public static final int orate=100;
public static final int delay=1500;
public static Random r=new Random();
public static Random t=new Random();
public class generating extends Thread
{
public void run()
{
while(stop==null)
{
tgen=t.nextInt(3000);
packet=r.nextInt(512);
if(bsize+packet<bmax)
{
bsize=bsize+packet;
System.out.printf("%13d%10d%15d%20d\n",j++,packet,bsize,bmax-bsize);
}
else
System.out.println("Bucket OverFlow, "+packet+" size of packet discarded");
try{Thread.sleep(tgen);}catch(Exception e){};
}
}
}
public class leaking extends Thread
{
public void run()
{
while(true)
{
if(bsize>0 &&bsize-orate>0) //output packet rate is 100bytes

Dept. of CSE, EWIT Page 58


Computer Network Laboratory 15CSL57
{
bsize=bsize-orate;
System.out.printf("%38d%20d%15d\n",bsize,(bmax-bsize),orate);
}
else
{
System.out.printf("%38d%20d%15d\n",0,bmax,bsize);
bsize=0;
if(stop!=null)
return;}
try{Thread.sleep(delay);}catch(Exception e){};
}
}
}
//@SuppressWarnings("resource")
public static void main(String[] args)
{
Leaky le=new Leaky();
Scanner in=new Scanner(System.in);
generating g=le.new generating();
leaking l=le.new leaking();
System.out.println("Started");
System.out.println("Output Rate is:"+orate+"\nAnd it is flowing at interval:"+
((float)delay/1000)+"sec");
System.out.println("Enter any key to stop input");
System.out.printf("Packet number | Input Packet | Bucket filled | Remaining space|Output
rate");
System.out.println();
g.start();
try{Thread.sleep(10);}catch(Exception e){};
l.start();
stop=in.next();
}
}

Dept. of CSE, EWIT Page 59


Computer Network Laboratory 15CSL57
Snapshot:

Fig 28: Congestion control using Leaky bucket algorithm.

Dept. of CSE, EWIT Page 60

Anda mungkin juga menyukai