Ilovepdf Merged
Ilovepdf Merged
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 analyze 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 (21CS52) 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.
Department of Computer Science and Engineering
ABOUT
Department of Artificial Intelligence & Machine Learning was established in the year 2022. 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 200 UG 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 be a Department of Excellence in Technical Education through Innovative Learning
Approach with Social Commitment in the field of Computer Science & Engineering.
Mission:
M1: To impart quality technical education that nurtures the young minds by providing the best
of teaching learning process and state of the art infrastructure.
M2: To foster technological advancement through research.
M3: To inculcate holistic personality development through best practices.
M4: To implant ethical and social commitment that grooms the students to become
responsible citizens.
Program Educational Objectives (PEOs)
PEO1: To achieve sustainable growth as Computer Science Engineers in reputed
organizations.
PEO2: To accomplish higher education and research with highest degree of professionalism
and integrity.
PEO3: To extend the services to mankind by exhibiting leadership qualities and ethical
values.
PSO1 Apply the strong knowledge and principles of Computer Science and Engineering to
model and design various computing systems.
PSO2 Develop the diverse applications in well promised domains by adopting the practices
of Computer Science & Engineering.
PROGRAM OUTCOMES (POs)
PO’s DESCRIPTION
PO1 Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering
problems.
PO2 Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.
PO3 Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
PO4 Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of
the information to provide valid conclusions.
PO5 Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities
with an understanding of the limitations.
PO6 The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to
the professional engineering practice.
PO7 Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.
PO8 Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
PO9 Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
PO10 Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.
PO11 Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
PO12 Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
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)
engineering
Prof. Gangambika G
COMPUTER NETWORK LABORATORY
(Effective from the academic year 2018 -2019)
SEMESTER – V
Course Code BCS502 CIE Marks 25
Number of Contact 3:0:2:0 SEE Marks 00
Hours/Week
Credits – 2
COURSE OBJECTIVES
This Course will enable the students:
Study the TCP/IP protocol suite, switching criteria and Medium Access Control
protocols for reliable and noisy channels.
Learn network layer services and IP versions.
Discuss transport layer services and understand UDP and TCP protocols.
Demonstrate the working of different concepts of networking layers and protocols.
COURSE OUTCOMES
COURSE
OUTCOME PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
CO1 2 0 0 0 1 1 1 1 0 0 0 1
CO2 3 1 0 0 1 1 1 1 0 0 0 1
CO3 3 2 0 0 1 1 2 1 0 0 0 1
CO4 3 2 0 0 1 1 1 1 0 0 0 1
PSO 1 2
CO1 1
CO2 2
CO3 2 1
CO4 2 1
LAB EVALUATION PROCESS
1 Observation Book 5
2 Record 5
TOTAL 10
INTERNAL ASSESSMENT
PART B
SL.NO ACTIVITY MARKS
1 Procedure 2.5
2 Conduction 10
TOTAL 15
PART A + PART B 25
COMPUTER NETWORK LABORATORY
(Effective from the academic year 2023 -2024)
SEMESTER – V
Course Code BCS502 CIE Marks 25
Number of Contact 3:0:2:0 SEE Marks 00
Hours/Week
Credits – 2
Sl. PROGRAMS
No.
Implement three nodes point – to – point network with duplex links between
1 them. Set the queue size, vary the bandwidth, and find the number of packets
dropped
Implement transmission of ping messages/trace route over a network
2 topology consisting of 6 nodes and find the number of packets dropped due
to congestion.
Implement an Ethernet LAN using n nodes and set multiple traffic nodes and
3
plot congestion window for different source / destination..
4 Develop a program for error detecting code using CRC-CCITT (16- bits).
Develop a program to implement a sliding window protocol in the data link
5
layer
Develop a program to find the shortest path between vertices using the
6
Bellman-Ford and path vector routing algorithm.
Using TCP/IP sockets, write a client – server program to make the client
7 send the file name and to make the server send back the contents of the
requested file if present.
Develop a program on a datagram socket for client/server to display the
8 messages on client side, typed at the server side.
Develop a program for a simple RSA algorithm to encrypt and decrypt the
8 data.
Develop a program for congestion control using a leaky bucket algorithm.
10
Computer Network Laboratory BCS502
BasicsofNS2
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.
BasicArchitectureofNS2
Fig1:ArchitectureofNS2
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
Continuation lines: The backslash may be used to continue a Tcl command on another
line. For example,
seta\
b
$nscolorfid 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.
procfinish {}: is called after this simulation is over by the command $nsat 5.0 "finish". In
this function, post-simulation processes are specified.
set n0[$nsnode]: The member function node creates a node. A node in NS is compound
object made of address and port classifiers.
$nsqueue-limit node1 node2 number: This line sets the queue limit of the two simplex links
that connect node1 and node2 to the number specified.
settcp[newAgent/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 factbasic
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/TCP Sink, Application/FTP and so on.
$nsattach-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, $n0attach$tcp.Similarly, each agent object has a member function
attach-agent that attaches a traffic source object to itself
$nsconnect 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.
$nsat 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, $nsat 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 tcp sink as
the end agent. Connection must be made between tcp and tcp sink, same in udp with cbr and
null respectively.
$nsattach-agent$n3$sink
Now the tcp sink 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.
$nsconnect$tcp$sink
setudp [newAgent/UDP]
$nsattach-agent$n2$udp
setcbr[new Application/Traffic/CBR]
$cbrattach-agent$udp
setnull[new Agent/Null]
$nsattach-agent$n3$null
$nsconnect$udp $null
The file should be saved in .tcl format and should use ns filename.tcl to run
Ns2Tracefile 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 tid
t e siz s wid r r m
node e e e
Topology Design:
Source code:
#Vary the below Bandwidth and see the number of packets dropped.
#The below code is used to set the queue size b/w the nodes
#The below code sets the udp0 packets to red and udp1
proc finish { } {
global ns nf tf
$ns flush-trace
close $tf
close $nf
exit 0
$ns run
AWKScript:
BEGIN{
#include<stdio.h>
count=0;
}
{
if($1==”d”)
count++;
}END{
printf (“Total no.of packets dropped due to congestion is:%d”, count);
}
Torun:
ns lab1.tcl
awk–flab1.awklab1.tr
TheTotalnoofpacketsDroppedduetocongestion:750
Snapshot:
Topology Design:
Fig4:Topologyofnetworkwith6nodestodemonstratepingmessage transmission
Note:
1. Vary the bandwidth and queue size between the nodes n0-n2 , n2-n4. n6-n2 and n2-
n5and see the number of packets dropped at thenodes.
AWKScript:
BEGIN{
#include<stdio.h>
count=0;
}
{
if($1=="d")
count++;
} END {
printf("Total no. of packets dropped due to congestion is:%d\n",count);
}
nsping.tcl
awk–f ping.awk ping.tr
Total no. of packets dropped due to congestion is:20
Snapshot:
Topology Design:
Note:
The congestion at the nodes can be traced by the following steps:
Step1:Createafile1.trandfile2.tr set
file1 [open file1.trw] set
file2 [open file2.trw]
Step 2: Attach these files(file1.tr&file2.tr)to the agents
tcp0 and tcp1 as shown below.
$tcp0attach$file1
$tcp1attach $file2
AWK file
BEGIN{
#include<stdio.h>
if($6=="cwnd_")
END{
puts "DONE"
Torun:
nslan.tcl
awk–flan.awkfile1.tr>tcp0
awk–flan.awkfile2.tr>tcp1
xgraph –x“time” –y“congestion value”tcp0tcp1
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.
Then the newly elongated data unit is divided by the divisor using a process called binary
division (XOR).
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:
//Calculation of CRC
for(int i=0;i<message.length();i++)
{
if(data[i]==1)
Dept. of CSE, EWIT Page21
Computer Network Laboratory BCS502
for(int j=0;j<divisor.length;j++)
data[i+j] ^= divisor[j];
}
//Display CRC
System.out.print("The checksum code is: ");
for(int i=0;i<message.length();i++)
data[i] = Integer.parseInt(message.charAt(i)+"");
for(int i=0;i<data.length;i++)
System.out.print(data[i]);
System.out.println();
//Calculation of remainder
for(int i=0;i<message.length();i++) {
if(data[i]==1)
for(int j=0;j<divisor.length;j++)
data[i+j] ^= divisor[j];
}
if(valid==true)
System.out.println("Data stream is valid");
else
System.out.println("Data stream is invalid. CRC error occurred.");
}
The sliding window protocol is a well-known technique that plays a significant role in ensuring
reliable and orderly data exchange between a sender and a receiver. In this section, we will delve
into the concept of the sliding window protocol and demonstrate how to implement it using Java.
Source Code:
package dev;
import java.util.Random;
import java.util.Scanner;
long i = 1;
long[] tt = {0}; // Using an array to allow passing by reference
transmission(i, N, tf, tt);
System.out.println("Total number of frames which were sent and resent are: " + tt[0]);
scanner.close();
}
}
OUTPUT 1:
Enter the window size: 3
Enter the total number of frames: 5
Starting Sliding Window Protocol Simulation
Sending frame: 0
Sending frame: 1
Sending frame: 2
Frame 0 lost, waiting for retransmission
Frame 1 lost, waiting for retransmission
Frame 2 lost, waiting for retransmission
Sending frame: 0
Sending frame: 1
Dept. of CSE, EWIT Page25
Computer Network Laboratory BCS502
Sending frame: 2
Received ACK for frame: 0
Received ACK for frame: 1
Frame 2 lost, waiting for retransmission
Sending frame: 2
Sending frame: 3
Sending frame: 4
Frame 2 lost, waiting for retransmission
Frame 3 lost, waiting for retransmission
Received ACK for frame: 4
Sending frame: 2
Sending frame: 3
Sending frame: 4
Received ACK for frame: 2
Received ACK for frame: 3
Frame 4 lost, waiting for retransmission
Simulation complete
OUTPUT 2:
Enter the window size: 3
Enter the total number of frames: 5
Starting Sliding Window Protocol Simulation
Sending frame: 0
Sending frame: 1
Sending frame: 2
Received ACK for frame: 0
Frame 1 lost, waiting for retransmission
Frame 2 lost, waiting for retransmission
Sending frame: 1
Sending frame: 2
Sending frame: 3
Received ACK for frame: 1
Received ACK for frame: 2
Frame 3 lost, waiting for retransmission
Sending frame: 3
Sending frame: 4
Received ACK for frame: 3
Received ACK for frame: 4
Simulation complete
Algorithm
Steps:
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 in finite 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.
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.
Source Code:
import java.util.Scanner;
public class ford
{
private int D[];
private int num_ver;
public static final int MAX_VALUE = 999;
public ford(int num_ver)
{
this.num_ver = num_ver;
D = new int[num_ver + 1];
}
D[source] = 0;
Snapshot:
7. 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.
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 set
So Timeout() method. Otherwise, this method blocks indefinitely.
public Socket(Inet Address 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.
Public Inet Address get Inet Address(): This method returns the address of the
other computer that this socket is connected to.
Public int getPort():Returns the port the socket is bound to on there mote machine.
// TCP Server
import java.net.*;
import java.io.*;
public class TCPS
{
public static void main(String[] args) throws Exception
{
ServerSocket sersock=new ServerSocket(4000);
System.out.println("Server ready for connection");
Socket sock=sersock.accept();
System.out.println("Connection Is successful and waiting for chatting");
InputStream istream=sock.getInputStream();
BufferedReader fileRead=new BufferedReader(new InputStreamReader(istream));
String fname=fileRead.readLine();
BufferedReader ContentRead=new BufferedReader(new FileReader(fname));
OutputStream ostream=sock.getOutputStream();
PrintWriter pwrite=new PrintWriter(ostream,true);
String str;
while((str=ContentRead.readLine())!=null){
pwrite.println(str);
}
sock.close();
sersock.close();
pwrite.close();
fileRead.close();
ContentRead.close();
}
}
//TCP Client
import java.net.*;
import java.io.*;
public class TCPC
{
public static void main(String[] args) throws Exception
{
Socket sock=new Socket("127.0.01",4000);
System.out.println("Enter the filename");
BufferedReader keyRead=new BufferedReader(new InputStreamReader(System.in));
String fname=keyRead.readLine();
OutputStream ostream=sock.getOutputStream();
PrintWriter pwrite=new PrintWriter(ostream,true);
pwrite.println(fname);
InputStream istream=sock.getInputStream();
BufferedReader socketRead=new BufferedReader(new InputStreamReader(istream));
String str;
while((str=socketRead.readLine())!=null)
{
System.out.println(str);
import java.io.*;
importjava.net.*;
publicclassudpc
{
publicstaticvoid main(String[]args)
{
DatagramSocketskt;
try
{
skt=new DatagramSocket();
Stringmsg="textmessage";
byte[]b=msg.getBytes();
InetAddresshost=InetAddress.getByName("127.0.0.1");
intserverSocket=2400;
DatagramPacketrequest=newDatagramPacket(b,b.length,host,serverSocket);
skt.send(request);
byte[]buffer=newbyte[1000];
DatagramPacketreply=newDatagramPacket(buffer,buffer.length);
skt.receive(reply);
System.out.println("clientrecieved:"+newString(reply.getData()));
skt.close();
}
catch(Exceptionex){}
}
}
Snapshot:
9. 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 the m 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 numbere ,co-prime tot, with
GCD(t,e)=1and 1<e<t.
5. Find d, such that d*emodt=1.
Publish e and n as public key.
Keep d and t as secret key.
Encryption
Cipher=(Message)emodn
Decryption
Message=(Cipher)dmodn
Source code:
importjava.util.Scanner;
public class RSA
{
publicstaticintp,q,n,t,flag,msg,m,temp;
public staticint e[]=new int[100]; public
staticint d[]=new int[100]; public static
int prime( intpr)
{
inti;
Doublea=(Math.sqrt(pr));
m=a.intValue();
for(i=2;i<=m;i++)
{
if(pr%i==0)
return0;
}
return1;
publicstaticvoidce()
{
intk=0;
for(inti=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++;
}
if(k==99)
break;
}
}
}
publicstaticintcd( intx)
{
intk=1;
while(true)
{
k=k+t;
if(k%x==0)
return(k/x);
}
publicstaticvoid encrypt()
{
intpt,ct,key=e[0],k;
pt=msg;
k=1;
for(intj=0;j<key;j++)
{
k=k*pt;
k=k%n;
}
ct=k;
temp=ct;
System.out.println("\nTHEENCRYPTEDMESSAGEIS:"+ct);
publicstaticvoid decrypt()
{
intpt,ct,key=d[0],k;
ct=temp;
k=1;
for(intj=0;j<key;j++)
{
k=k*ct;
k=k%n;
}
pt=k;
System.out.println("\nTHEDECRYPTEDMESSAGEIS:"+pt);
}
publicstaticvoidmain(Stringargs[])
{
Scanner sc=new Scanner(System.in);
System.out.println("ENTERFIRSTPRIMENUMBER");
p=sc.nextInt();
flag=prime(p);
if(flag==0)
{
System.out.println("WRONGINPUT");
System.exit(1);
}
System.out.println("ENTERANOTHERPRIMENUMBER");
q=sc.nextInt();
flag=prime(q);
if(flag==0||p==q)
{
System.out.println("WRONGINPUT");
System.exit(1);
}
System.out.println("ENTERMESSAGE");
msg=sc.nextInt();
n=p*q;
t=(p-1)*(q-1);
ce();
System.out.println("POSSIBLEVALUESOFeANDdARE"); for
(int i=0;i< m-1;i++)
System.out.printf("\n%d\t%d",e[i],d[i]);
encrypt();
decrypt();
}
}
Snapshot:
10. 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
watercomingoutisinsomefixedrate.Andalsoifbucketisfullwewillstoppouringinit. 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.
Fig27:Leakybucketscenario
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 tot his commitment.
In Figure the host sends a burst of data at a rate of 12 Mbps for 2 s, for a total of 24 M bits 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 M
bits of data. In all, the host has sent 30 M bits of data in 10 s. The leaky bucket smoothes the
traffic by sending out data at a rate of 3Mbps during the same10s.Without the leaky bucket, the
importjava.util.Random;
importjava.util.Scanner;
public class Leaky
{
publicstaticintbsize=0,packet,tgen,j=1;
public static String stop;
publicstatic final intbmax=1024;
public static final int orate=100;
publicstaticfinalintdelay=1500;
publicstaticRandomr=newRandom();
publicstaticRandomt=newRandom();
public class generating extends Thread
{
publicvoidrun()
{
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("BucketOverFlow,"+packet+"sizeofpacketdiscarded");
try{Thread.sleep(tgen);}catch(Exception e){};
}
}
}
publicclassleakingextendsThread
{
publicvoidrun()
{
while(true)
{
if(bsize>0&&bsize-orate>0)//outputpacketrateis100bytes
Snapshot:
Design:
Note:
a. Calculate the total number of packets sent by tcp and udp by changing the
bandwidth from 100Mb,25Mb or 200mb in the topology and the data rate from
0.1,
0.001 as shown below.
Eg:
Bandwidth Data Rate TCP pkt sent UDP pkt sent
100Mb 0.1 2000 2500
200Mb 0.001 3400 6700
# The below code is used to set the color and name's to the
#nodes.
$ns color 1 "red"
$ns color 2 "blue"
$n0 label "source/TCP"
$n1 label "source/UDP"
$n2 label "Router"
$n3 label "destination"
# The below code is used to set the color and labels to the
#links.
$ns duplex-link-op $n0 $n2 color "green"
$ns duplex-link-op $n0 $n2 label "from 0-2"
$ns duplex-link-op $n1 $n2 color "green"
$ns duplex-link-op $n1 $n2 label "from 1-2"
$ns duplex-link-op $n2 $n3 color "green"
$ns duplex-link-op $n2 $n3 label "from 2-3"
# The below code is used create TCP and UDP agents and the
# traffic ftp & cbr respectively.
set tcp0 [new Agent/TCP]
$ns attach-agent $n0 $tcp0 set ftp0 [new
Application/FTP]
$ftp0 attach-agent $tcp0
set sink3 [new Agent/TCPSink]
$ns attach-agent $n3 $sink3
#The below code is used to set the packet size of ftp and
#udp.
$ftp0 set packetSize_ 500
$ftp0 set interval_ 0.001
proc finish { } {
global ns nf tf
$ns flush-trace exec nam
lab2.nam & close $nf
close $tf exit
0
}
$ns at 0.1 "$cbr1 start"
$ns at 0.2 "$ftp0 start"
$ns at 5.0 "finish"
$ns run
AWK Script:
BEGIN{
#include<stdio.h> tcp=0;
udp=0;
}
{
if($1=="r"&&$3=="2"&&$4=="3"&& $5=="tcp")
tcp++;
if($1=="r"&&$3=="2"&&$4=="3"&&$5=="cbr")
udp++;
}
END
{
Note:
1. The lan can be created by using the command:
$ns make-lan “ $n0 $n1 $n2 $n3 ” 100Mb 10ms LL Queue/DropTail Mac/802_3
2. The Error between the nodes n3 and n6 can be added as follows: Set
err [ new ErrorModel ]
$ns lossmodel $err $n3 $n6
$err set rate_ 0.1 # used to set error rate.
3. The throughput can analyzed by changing the datarate and errorrate as shown below.
i. First, Fix the data rate to 0.0001 and vary the error rate then
throughput decreases as shown below.
Eg:
Error rate Data rate Throughput
0.1 0.0001 78Mbps
0.2 0.0001 68Mbps
0.3 0.0001 58Mbps
0.4 0.0001 48Mbps
i. Now Fix the error rate to 0.1 and vary the data rate then throughput
increases as shown below.
Error rate Data rate Throughput
0.1 0.1 78Mbps
Program
set ns [new Simulator] set tf [open lab5.tr
w]
$ns trace-all $tf
set nf [open lab5.nam w]
$ns namtrace-all $nf
$ns make-lan "$n0 $n1 $n2 $n3" 10Mb 10ms LL Queue/DropTail Mac/802_3
$ns make-lan "$n4 $n5 $n6" 10Mb 10ms LL Queue/DropTail Mac/802_3
#The below code is used to connect node n3 of lan1 and n6 of
#lan2.
$ns duplex-link $n3 $n6 100Mb 10ms DropTail
if(Math.pow(2,parity_count) == i+parity_count + 1) {
parity_count++;
}
else {
i++;
}
}
// Initialize this array with '2' to indicate an 'unset' value in parity bit locations:
b[i-1] = 2;
j++;
}
else {
b[k+j] = a[k++];
}
}
for(i=0 ; i < parity_count ; i++) {
// Setting even parity bits at parity bit locations:
int k = i+1;
String s = Integer.toBinaryString(k);
//Nw if the bit at the 2^(power) location of the binary value of index is
1
//Then we need to check the value stored at that location.
//Checking if that value is 1 or 0, we will calculate the parity value.
int power;
// We shall use the value stored in 'power' to find the correct bits to check for parity.
int k = i+1;
String s = Integer.toBinaryString(k);
int bit = ((Integer.parseInt(s))/((int) Math.pow(10, power)))%10;
if(bit == 1) {
if(a[i] == 1) {
parity[power] = (parity[power]+1)%2;
}
}
}
syndrome = parity[power] + syndrome;
}
// This gives us the parity check equation values.
// Using these values, we will now check if there is a single bit error and then correct
it.
// Finally, we shall extract the original data from the received (and corrected) code:
System.out.println("Original data sent was:");
power = parity_count-1;
for(int i=a.length ; i > 0 ; i--) {
if(Math.pow(2, power) != i) {
System.out.print(a[i-1]);
}
else {
power--;
}
}
System.out.println();
}
}
DEPARTMENT OF COMPUTER
SCIENCE & ENGINEERING
LABORATORY MANUAL
B.E V SEMESTER
(CBCS SCHEME)
COMPUTER NETWORKS LAB
(BCS502)