Network Lab Manual
Network Lab Manual
Network Lab Manual
1 D/F
Channabasaveshwara Institute of Technology
(An ISO 9001:2008 Certified Institution)
NH 206 (B.H. Road), Gubbi, Tumkur – 572 216. Karnataka.
LAB MANUAL
( 2017–18 )
V Semester CSE
Name : _________________________________________________
U S N : _________________________________________________
2. Students will not be permitted to attend the laboratory unless they bring the
practical record fully completed in all respects pertaining to the experiment
conducted in the previous class.
4. They should obtain the signature of the staff-in-charge in the observation book
after completing each experiment.
5. Theory regarding each experiment should be written in the practical record before
procedure in your own words.
TABLE OF CONTENTS
BASICS OF NS2
1. Introduction to NS2 1
2. XGraph 9
3. Awk and advanced 10
Part-A
4. Three node point to point network 12
5. Transmission of Ping messages 14
6. Ethernet Lan using n-nodes with multiple traffic 18
7. Simple ESS with wireless Lan 22
8. Performance of GSM using MAC layer 26
9. Performance of CDMA 30
Part-B
1. CRC-CCITT 34
2. Bellman-Ford Algorithm 39
3. Client server using TCP/IP sockets 42
4. Client-Server Communication 46
5. RSA Algorithm to Encrypt and Decrypt the Data 49
6. Congestion Control Using Leaky Bucket Algorithm 54
Viva-voice 58
References 61
Computer Network Laboratory 2017-18
PART-A
Introduction to NS-2:
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.
Tcl scripting
• Tcl is a general purpose scripting language. [Interpreter]
• Tcl runs on most of the platforms such as Unix, Windows, and Mac.
• The strength of Tcl is its simplicity.
• It is not necessary to declare a data type for variable prior to the usage.
Basics of TCL
Syntax: command arg1 arg2 arg3
Hello World!
puts stdout{Hello, World!}
Hello, World!
Variables Command Substitution
set a 5 set len [string length foobar]
set b $a set len [expr [string length foobar] + 9]
Simple Arithmetic
expr 7.2 / 4
Procedures
proc Diag {a b} {
set c [expr sqrt($a * $a + $b * $b)]
return $c }
puts ―Diagonal of a 3, 4 right triangle is [Diag 3 4]‖
Output: Diagonal of a 3, 4 right triangle is 5.0
Loops
while{$i < $n} { for {set i 0} {$i < $n} {incr i} {
... ...
} }
Wired TCL Script Components
Create the event scheduler
Open new files & turn on the tracing
Create the nodes
Setup the links
Configure the traffic type (e.g., TCP, UDP, etc)
Set the time of traffic generation (e.g., CBR, FTP)
Terminate the simulation
NS Simulator Preliminaries.
1. Initialization and termination aspects of the ns simulator.
2. Definition of network nodes, links, queues and topology.
3. Definition of agents and of applications.
4. The nam visualization tool.
5. Tracing and random variables.
Which is thus the first line in the tcl script? This line declares a new variable as using the set
command, you can call this variable as you wish, In general people declares it as ns because
it is an instance of the Simulator class, so an object the code[new Simulator] is indeed the
installation of the class Simulator using the reserved word new.
In order to have output files with data on the simulation (trace files) or files used for
visualization (nam files), we need to create the files using ―open‖ command:
#Open the Trace file
set tracefile1 [open out.tr w]
The above creates a trace file called ―out.tr‖ and a nam visualization trace file called
―out.nam‖. Within the tcl script, these files are not called explicitly by their names, but
instead by pointers that are declared above and called ―tracefile1‖ and ―namfile‖ respectively.
Remark that they begins with a # symbol. The second line open the file ―out.tr‖ to be used for
writing, declared with the letter ―w‖. The third line uses a simulator method called trace-all
that have as parameter the name of the file where the traces will go.
The last line tells the simulator to record all 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.
In our case, this will be the file pointed at by the pointer ―$namfile‖, i.e the file ―out.tr‖.
The termination of the program is done using a ―finish‖ procedure.
#Define a „finish‟ procedure
Proc finish { } {
$ns flush-trace
Close $tracefile1
Close $namfile
Exit 0
The word proc declares a procedure in this case called finish and without arguments.
The word global is used to tell that we are using variables declared outside the procedure.
The simulator method ―flush-trace” will dump the traces on the respective files. The tcl
command ―close” closes the trace files defined before and exec executes the nam program for
visualization. The command exit will ends the application and return the number 0 as status
to the system. Zero is the default for a clean exit. Other values can be used to say that is a exit
because something fails.
At the end of ns program we should call the procedure ―finish‖ and specify at what
time the termination should occur. For example,
$ns at 125.0 “finish”
will be used to call ―finish‖ at time 125sec.Indeed,the at method of the simulator allows us to
schedule events explicitly.
The simulation can then begin using the command
$ns run
The node is created which is printed by the variable n0. When we shall refer to that node in
the script we shall thus write $n0.
Once we define several nodes, we can define the links that connect them. An example
of a definition of a link is:
$ns duplex-link $n0 $n2 10Mb 10ms DropTail
Which means that $n0 and $n2 are connected using a bi-directional link that has 10ms
of propagation delay and a capacity of 10Mb per sec for each direction.
To define a directional link instead of a bi-directional one, we should replace ―duplex-
link‖ by ―simplex-link‖.
In NS, an output queue of a node is implemented as a part of each link whose input is
that node. The definition of the link then includes the way to handle overflow at that queue.
In our case, if the buffer capacity of the output queue is exceeded then the last packet to
arrive is dropped. Many alternative options exist, such as the RED (Random Early Discard)
Dept. of CSE, CIT, Gubbi Page no 4
Computer Network Laboratory 2017-18
mechanism, the FQ (Fair Queuing), the DRR (Deficit Round Robin), the stochastic Fair
Queuing (SFQ) and the CBQ (which including a priority and a round-robin scheduler).
In ns, an output queue of a node is implemented as a part of each link whose input is
that node. We should also define the buffer capacity of the queue related to each link. An
example would be:
#set Queue Size of link (n0-n2) to 20
The command $ns attach-agent $n0 $tcp defines the source node of the tcp connection.
The command
set sink [new Agent /TCPSink]
Defines the behavior of the destination node of TCP and assigns to it a pointer called sink.
Scheduling Events
NS is a discrete event based simulation. The tcp script defines when event should
occur. The initializing command set ns [new Simulator] creates an event scheduler, and
events are then scheduled using the format:
$ns at <time> <event>
The scheduler is started when running ns that is through the command $ns run.
The beginning and end of the FTP and CBR application can be done through the following
command
$ns at 0.1 “$cbr start”
1. The first field is the event type. It is given by one of four possible symbols r, +, -, d which
correspond respectively to receive (at the output of the link), enqueued, dequeued and
dropped.
2. The second field gives the time at which the event occurs.
3. Gives the input node of the link at which the event occurs.
4. Gives the output node of the link at which the event occurs.
5. Gives the packet type (eg CBR or TCP)
6. Gives the packet size
7. Some flags
8. This is the flow id (fid) of IPv6 that a user can set for each flow at the input OTcl script
one can further use this field for analysis purposes; it is also used when specifying stream
color for the NAM display.
XGRAPH
The xgraph program draws a graph on an x-display given data read from either data
file or from standard input if no files are specified. It can display upto 64 independent data
sets using different colors and line styles for each set. It annotates the graph with a title, axis
labels, grid lines or tick marks, grid labels and a legend.
Syntax:
Xgraph [options] file-name
Awk- An Advanced
Here, selection_criteria filters input and select lines for the action component to act
upon. The selection_criteria is enclosed within single quotes and the action within the curly
braces. Both the selection_criteria and action forms an awk program.
Example: $ awk „/manager/ {print}‟ emp.lst
Variables
Awk allows the user to use variables of there choice. You can now print a serial
number, using the variable kount, and apply it those directors drawing a salary exceeding
6700:
$ awk –F”|” „$3 == “director” && $6 > 6700 {
kount =kount+1
printf “ %3f %20s %-12s %d\n”, kount,$2,$3,$6 }‟ empn.lst
Part-A
Experiment No: 1 Date:
THREE NODE POINT TO POINT NETWORK
Aim: 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.
proc finish { } {
global ns nf tf
$ns flush-trace # clears trace file contents
close $nf
close $tf
exec nam lab1.nam &
exit 0
}
set n0 [$ns node] # creates 3 nodes
set n2 [$ns node]
set n3 [$ns node]
AWK file: (Open a new editor using “vi command” and write awk file and save with “.awk”
extension)
#immediately after BEGIN should open braces „{„
BEGIN{ c=0;}
{
if($1= ="d")
{ c++;
printf("%s\t%s\n",$5,$11);
}
}
END{ printf("The number of packets dropped is %d\n",c); }
proc finish { } {
global ns nf tf
$ns flush-trace
close $nf
close $tf
exec nam lab2.nam &
exit 0
}
$ns at 0.1 "$p1 send"
$ns at 0.2 "$p1 send"
$ns at 0.3 "$p1 send"
$ns at 0.4 "$p1 send"
$ns at 0.5 "$p1 send"
$ns at 0.6 "$p1 send"
$ns at 0.7 "$p1 send"
$ns at 0.8 "$p1 send"
$ns at 0.9 "$p1 send"
$ns at 1.0 "$p1 send"
AWK file: (Open a new editor using “gedit command” and write awk file and save with
“.awk” extension)
BEGIN{
drop=0;
}
{
if($1= ="d" )
{
drop++;
}
}
END{
printf("Total number of %s packets dropped due to congestion =%d\n",$5,drop);
}
Topology Output
Output
Aim: Implement an Ethernet LAN using n nodes and set multiple traffic nodes and plot
congestion window for different source / destination
$ns make-lan "$n0 $n1 $n2 $n3 $n4" 100Mb 100ms LL Queue/ DropTail Mac/802_3
$ns duplex-link $n4 $n5 1Mb 1ms DropTail
$tcp0 trace cwnd_ # must put underscore ( _ ) after cwnd and no space between them
$tcp2 trace cwnd_
proc finish { } {
global ns nf tf
$ns flush-trace
close $tf
close $nf
exec nam lab3.nam &
exit 0
}
$ns at 16 "finish"
$ns run
AWK file: (Open a new editor using “gedit command” and write awk file and save with
“.awk” extension)
BEGIN {
}
{
if($6= ="cwnd_") # don‟t leave space after writing cwnd_
printf("%f\t%f\t\n",$1,$7); # you must put \n in printf
}
END {
}
Topolgy:
Output:
Aim: Implement simple ESS and with transmitting nodes in wire-less LAN by simulation and
determine the performance with respect to transmission of packets.
create-god 3
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
$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
AWK file: (Open a new editor using “gedit command” and write awk file and save with
“.awk” extension)
BEGIN{
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", ((count2*pack2*8)/(time2*1000000)));
}
Aim: Implement and study the performance of GSM on NS2/NS3 (Using MAC layer) or
equivalent environment.
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 plots
set opt(srcTrace) is ;# where to plot traffic
set opt(dstTrace) bs2 ;# where to plot traffic
set opt(gsmbuf) 10 ; # buffer size for gsm
#default downlink bandwidth in bps
set bwDL(gsm) 9600
#default uplink bandwidth in bps
set bwUL(gsm) 9600
#default downlink propagation delay in seconds
set propDL(gsm) .500
#default uplink propagation delay in seconds
set propUL(gsm) .500
#default buffer size in packets
set buf(gsm) 10
Aim: Implement and study the performance of CDMA on NS2/NS3 (Using stack called Call
net) or equivalent environment.
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
set bwDL(umts) 384000
#default uplink bandwidth in bps
set bwUL(umts) 64000
#default downlink propagation delay in seconds
set propDL(umts) .150
#default uplink propagation delay in seconds
set propUL(umts) .150
#default buffer size in packets
set buf(umts) 20
Output:
Part-B
Experiment No: 1 Date:
Error Detecting Code Using CRC-CCITT (16-bit)
Aim: Write a Program for ERROR detecting code using CRC-CCITT (16bit).
Whenever digital data is stored or interfaced, data corruption might occur. Since the
beginning of computer science, developers have been thinking of ways to deal with this type
of problem. For serial data they came up with the solution to attach a parity bit to each sent
byte. This simple detection mechanism works if an odd number of bits in a byte changes, but
an even number of false bits in one byte will not be detected by the parity check. To
overcome this problem developers have searched for mathematical sound mechanisms to
detect multiple false bits. The CRC calculation or cyclic redundancy check was the result of
this. Nowadays CRC calculations are used in all types of communications. All packets sent
over a network connection are checked with a CRC. Also each data block on your hard disk
has a CRC value attached to it. Modern computer world cannot do without these CRC
calculations. So let's see why they are so widely used. The answer is simple; they are
powerful, detect many types of errors and are extremely fast to calculate especially when
dedicated hardware chips are used.
The idea behind CRC calculation is to look at the data as one large binary number.
This number is divided by a certain value and the remainder of the calculation is called the
CRC. Dividing in the CRC calculation at first looks to cost a lot of computing power, but it
can be performed very quickly if we use a method similar to the one learned at school. We
will as an example calculate the remainder for the character 'm'—which is 1101101 in binary
notation—by dividing it by 19 or 10011. Please note that 19 is an odd number. This is
necessary as we will see further on. Please refer to your schoolbooks as the binary calculation
method here is not very different from the decimal method you learned when you were
young. It might only look a little bit strange. Also notations differ between countries, but the
method is similar.
With decimal calculations you can quickly check that 109 divided by 19 gives a
quotient of 5 with 14 as the remainder. But what we also see in the scheme is that every bit
extra to check only costs one binary comparison and in 50% of the cases one binary
subtraction. You can easily increase the number of bits of the test data string—for example to
56 bits if we use our example value "Lammert"—and the result can be calculated with 56
binary comparisons and an average of 28 binary subtractions. This can be implemented in
hardware directly with only very few transistors involved. Also software algorithms can be
very efficient.
All of the CRC formulas you will encounter are simply checksum algorithms based
on modulo-2 binary division where we ignore carry bits and in effect the subtraction will be
equal to an exclusive or operation. Though some differences exist in the specifics across
different CRC formulas, the basic mathematical process is always the same:
The message bits are appended with c zero bits; this augmented message is the
dividend
A predetermined c+1-bit binary sequence, called the generator polynomial, is the
divisor
The checksum is the c-bit remainder that results from the division operation
Table 1 lists some of the most commonly used generator polynomials for 16- and 32-bit
CRCs. Remember that the width of the divisor is always one bit wider than the remainder.
So, for example, you’d use a 17-bit generator polynomial whenever a 16-bit checksum is
required.
Table 1: International Standard CRC Polynomials
CRC-CCITT CRC-16 CRC-32
Checksum
16 bits 16 bits 32 bits
Width
Generator
10001000000100001 11000000000000101 100000100110000010001110110110111
Polynomial
Error detection with CRC
Consider a message represented by the polynomial M(x)
802.3:
x32+x26+x23+x22 +x16+x12+x11+x10 +x8+x7+x5+x4+x2+x+1
o Used in: Ethernet, PPP rootion
Source Code:
import java.util.*;
class crc
{ void div(int a[],int k)
{ int gp[]={1,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,1};
int count=0;
for(int i=0;i<k;i++)
{
if(a[i]==gp[0])
{
for(int j=i;j<17+i;j++)
{
a[j]=a[j]^gp[count++];
}
count=0;
}
}
}
public static void main(String args[])
{
int a[]=new int[100];
int b[]=new int[100];
int len,k;
crc ob=new crc();
System.out.println("Enter the length of Data Frame:");
Scanner sc=new Scanner(System.in);
len=sc.nextInt();
int flag=0;
System.out.println("Enter the Message:");
for(int i=0;i<len;i++)
{ a[i]=sc.nextInt();
}
for(int i=0;i<16;i++)
{ a[len++]=0;
}
k=len-16;
for(int i=0;i<len;i++)
{ b[i]=a[i];
}
ob.div(a,k);
for(int i=0;i<len;i++)
a[i]=a[i]^b[i];
System.out.println("Data to be transmitted: ");
for(int i=0;i<len;i++)
Dept. of CSE, CIT, Gubbi Page no 37
Computer Network Laboratory 2017-18
{
System.out.print(a[i]+" ");
}
System.out.println();
System.out.println("Enter the Reveived Data: ");
for(int i=0;i<len;i++)
{
a[i]=sc.nextInt();
}
ob.div(a, k);
for(int i=0;i<len;i++)
{
if(a[i]!=0)
{
flag=1;
break;
}
}
if(flag==1)
System.out.println("error in data");
else
System.out.println("no error");
}
}
Output:
Aim: Write a program to find the shortest path between vertices using bellman-ford
algorithm.
Distance Vector Algorithm is a decentralized routing algorithm that requires that each
router simply inform its neighbors of its routing table. For each network path, the receiving
routers pick the neighbor advertising the lowest cost, then add this entry into its routing table
for re-advertisement. To find the shortest path, Distance Vector Algorithm is based on one of
two basic algorithms: the Bellman-Ford and the Dijkstra algorithms.
Routers that use this algorithm have to maintain the distance tables (which is a one-
dimension array -- "a vector"), which tell the distances and shortest path to sending packets to
each node in the network. The information in the distance table is always upd by exchanging
information with the neighboring nodes. The number of data in the table equals to that of all
nodes in networks (excluded itself). The columns of table represent the directly attached
neighbors whereas the rows represent all destinations in the network. Each data contains the
path for sending packets to each destination in the network and distance/or time to transmit
on that path (we call this as "cost"). The measurements in this algorithm are the number of
hops, latency, the number of outgoing packets, etc.\
The Bellman–Ford algorithm is an algorithm that computes shortest paths from a single
source vertex to all of the other vertices in a weighted digraph. It is slower than Dijkstra's
algorithm for the same problem, but more versatile, as it is capable of handling graphs in which
some of the edge weights are negative numbers. Negative edge weights are found in various
applications of graphs, hence the usefulness of this algorithm. If a graph contains a "negative
cycle" (i.e. a cycle whose edges sum to a negative value) that is reachable from the source, then
there is no cheapest path: any path that has a point on the negative cycle can be made cheaper by
one more walk around the negative cycle. In such a case, the Bellman–Ford algorithm can detect
negative cycles and report their existence
Implementation Algorithm:
1. send my routing table to all my neighbors whenever my link table changes
2. when I get a routing table from a neighbor on port P with link metric M:
a. add L to each of the neighbor's metrics
b. for each entry (D, P', M') in the updated neighbor's table:
i. if I do not have an entry for D, add (D, P, M') to my routing table
ii. if I have an entry for D with metric M", add (D, P, M') to my routing
table if M' < M"
3. if my routing table has changed, send all the new entries to all my neighbors.
Source Code:
import java.util.Scanner;
public class BellmanFord
{ private int D[];
private int num_ver;
public static final int MAX_VALUE = 999;
public BellmanFord(int n)
{ this.n=n;
D = new int[n+1];
}
public void shortest(int s,int A[][])
{ for (int i=1;i<=n;i++)
{ D[i]=MAX_VALUE;
} D[s] = 0;
for(int k=1;k<=n-1;k++)
{ for(int i=1;i<=n;i++)
{ for(int j=1;j<=n;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<=n;i++)
{ for(int j=1;j<=n;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;
} }
}
}
for(int i=1;i<=n;i++)
{
System.out.println("Distance of source " + s + " to "+ i + " is " + D[i]);
}
}
public static void main(String[ ] args)
{ int n=0,s;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of vertices");
n = sc.nextInt();
Socket is an interface which enables the client and the server to communicate and pass on
information from one another. Sockets provide the communication mechanism between two
computers using TCP. A client program creates a socket on its end of the communication and
attempts to connect that socket to a server. When the connection is made, the server creates a
socket object on its end of the communication. The client and the server can now communicate
by writing to and reading from the socket.
Source Code:
TCP Client
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.Scanner;
class Client
{
public static void main(String args[])throws Exception
{
String address = "";
Scanner sc=new Scanner(System.in);
System.out.println("Enter Server Address: ");
address=sc.nextLine();
//create the socket on port 5000
Socket s=new Socket(address,5000);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Send Get to start...");
String str="",filename="";
try
{
while(!str.equals("start"))
str=br.readLine();
dout.writeUTF(str);
dout.flush();
filename=din.readUTF();
try
{
String str="";
str=din.readUTF();
System.out.println("SendGet....Ok");
if(!str.equals("stop"))
{ System.out.println("Sending File: "+filename);
dout.writeUTF(filename);
dout.flush();
File f=new File(filename);
FileInputStream fin=new FileInputStream(f);
long sz=(int) f.length();
byte b[]=new byte [1024];
int read;
dout.writeUTF(Long.toString(sz));
dout.flush();
System.out.println ("Size: "+sz);
System.out.println ("Buf size: "+ss.getReceiveBufferSize()); while((read = fin.read(b)) != -1)
{
dout.write(b, 0, read); dout.flush();
}
fin.close();
System.out.println("..ok"); dout.flush();
}
dout.writeUTF("stop");
System.out.println("Send Complete"); dout.flush();
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("An error occured");
}
din.close();
s.close();
ss.close();
}
}
}
Output:
At server side:
At Client Side:
Aim: Write a program on datagram socket for client/server to display the messages on client
side, typed at the server side.
A datagram socket is the one for sending or receiving point for a packet delivery service.
Each packet sent or received on a datagram socket is individually addressed and routed. Multiple
packets sent from one machine to another may be routed differently, and may arrive in any order.
Source Code:
UDP Client
import java.io.*;
import java.net.*;
public class UDPC
{
public static void main(String[] args)
{
DatagramSocket skt; try
{
skt=new DatagramSocket();
String msg= "text message ";
byte[] b = msg.getBytes();
InetAddress host=InetAddress.getByName("127.0.0.1");
int serverSocket=6788;
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 received:" +new String(reply.getData()));
skt.close();
}
catch(Exception ex)
{
}
}
}
UDP Server
import java.io.*;
import java.net.*;
public class UDPS
{
public static void main(String[] args)
{
DatagramSocket skt=null;
try
{
skt=new DatagramSocket(6788);
byte[] buffer = new byte[1000];
while(true)
{
DatagramPacket request = new DatagramPacket(buffer,buffer.length);
skt.receive(request);
String[] message = (new String(request.getData())).split(" ");
byte[] sendMsg= (message[1]+ " server processed").getBytes();
DatagramPacket reply = new DatagramPacket(sendMsg,sendMsg.length,request.getAddress
(),request.getPort());
skt.send(reply);
}
}
catch(Exception ex)
{
}
}
}
Output:
AT SERVER SIDE
[root@localhost ]# cc prg6s.c
[root@localhost ]# ./a.out
SERVER online!
CLIENT online!
Waiting for request....SERVER: /Test.txt found!
Transfering the contents...
SERVER transfer Completed!
SERVER transfer Completed!
Output:
AT CLIENT SIDE
[root@localhost]# cc prg6c.c
[root@localhost]# ./a.out
Waiting for SERVER...
SERVER online!
CLIENT: Enter the path: /Test.txt
Wating for reply...
File recieved! Displaying the contents:
Sockets are a mechanism for exchanging data between processes. These processes can
either be on the same machine, or on different machines connected via a network. Once a
socket connection is established, data can be sent in both directions until one of the endpoints
closes the connection.
I needed to use sockets for a project I was working on, so I developed and refined a few
C++ classes to encapsulate the raw socket API calls. Generally, the application requesting the
data is called the client, and the application servicing the request is called the server. I created
two primary classes, C ZlientSocket and ServerSocket, that the client and server could use to
exchange data.
Output:
At Server Side:
At Client Side:
m 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
c 29 24 28 14 21 22 23 30 16 20 15 7 2 6 25 32
Note that all 33 values of m (0 to 32) map to a unique code c in the same range in a
sort of random manner. In this case we have nine values of m that map to the same value of c
- these are known as unconcealed messages. m = 0 and 1 will always do this for any N, no
matter how large. But in practice, higher values shouldn't be a problem when we use large
values for N.
If we wanted to use this system to keep secrets, we could let A=2, B=3, ..., Z=27. (We
specifically avoid 0 and 1 here for the reason given above). Thus the plaintext message
"HELLOWORLD" would be represented by the set of integers m1, m2, ...
{9,6,13,13,16,24,16,19,13,5}
Using our table above, we obtain ciphertext integers c1, c2, ...
{3,18,19,19,4,30,4,28,19,26}
Note that this example is no more secure than using a simple Caesar substitution
cipher, but it serves to illustrate a simple example of the mechanics of RSA encryption.
Remember that calculating m^e mod n is easy, but calculating the inverse c^-e mod n
is very difficult, well, for large n's anyway. However, if we can factor n into its prime factors
p and q, the solution becomes easy again, even for large n's. Obviously, if we can get hold of
the secret exponent d, the solution is easy, too.
Key Generation Algorithm
1. Generate two large random primes, p and q, of approximately equal size such that
their product n = pq is of the required bit length, e.g. 1024 bits. [See note 1].
2. Compute n = pq and (φ) phi = (p-1)(q-1).
3. Choose an integer e, 1 < e < phi, such that gcd(e, phi) = 1. [See note 2].
4. Compute the secret exponent d, 1 < d < phi, such that
ed ≡ 1 (mod phi). [See note 3].
5. The public key is (n, e) and the private key is (n, d). The values of p, q, and phi
should also be kept secret.
n is known as the modulus.
e is known as the public exponent or encryption exponent.
d is known as the secret exponent or decryption exponent.
Encryption
Sender A does the following:-
1. Obtains the recipient B's public key (n, e).
2. Represents the plaintext message as a positive integer m [see note 4].
3. Computes the ciphertext c = m^e mod n.
4. Sends the ciphertext c to B.
Decryption
Recipient B does the following:-
1. Uses his private key (n, d) to compute m = c^d mod n.
2. Extracts the plaintext from the integer representative m.
Source Code:
import java.util.*;
import java.io.*;
public class rsa
{ static int gcd(int m,int n)
{ while(n!=0)
{ int r=m%n;
m=n;
n=r;
}
return m;
}
int i=0,j=0,nofelem=0;
Scanner sc=new Scanner(System.in);
String message ;
System.out.println("Enter the Message tobe encrypted:");
message= sc.nextLine();
System.out.println("Enter value of p and q\n");
p=sc.nextInt();
q=sc.nextInt();
n=p*q;
phi=(p-1)*(q-1);
for(i=2;i<phi;i++)
if(gcd(i,phi)==1) break;
e=i;
for(i=2;i<phi;i++)
if((e*i-1)%phi==0)
break;
d=i;
for(i=0;i<message.length();i++)
{
char c = message.charAt(i);
int a =(int)c;
nummes[i]=c-96;
}
nofelem=message.length();
for(i=0;i<nofelem;i++)
{
encrypted[i]=1;
for(j=0;j<e;j++)
encrypted[i] =(encrypted[i]*nummes[i])%n;
}
System.out.println("\n Encrypted message\n");
for(i=0;i<nofelem;i++)
{
System.out.print(encrypted[i]);
System.out.print((char)(encrypted[i]+96));
}
for(i=0;i<nofelem;i++)
{ decrypted[i]=1;
for(j=0;j<d;j++)
decrypted[i]=(decrypted[i]*encrypted[i])%n;
}
#********************************************************
**RESULT**
Implementation Algorithm:
Steps:
1. Read The Data For Packets
2. Read The Queue Size
3. Divide the Data into Packets
4. Assign the random Propagation delays for each packets to input into the bucket
(input_packet).
5. wlile((Clock++<5*total_packets)and
(out_packets< total_paclets))
a. if (clock == input_packet)
i. insert into Queue
b. if (clock % 5 == 0 )
i. Remove paclet from Queue
6. End
Source Code:
import java.util.*;
public class leaky
{
static int min(int x,int y)
{
if(x<y)
return x;
else
return y;
}
public static void main(String[] args)
{ int drop=0,mini,nsec,cap,count=0,i,process;
int inp[]=new int[25];
Scanner sc=new Scanner(System.in);
}
System.out.println("\nSecond | Packet Recieved | Packet Sent | Packet Left |
Packet Dropped|\n");
//System.out.println("--------------------------------------------------------------------
----\n");
for(i=0;i<nsec;i++)
{ count+=inp[i];
if(count>cap)
{ drop=count-cap;
count=cap;
}
System.out.print(i+1);
System.out.print("\t\t"+inp[i]);
mini=min(count,process);
System.out.print("\t\t"+mini);
count=count-mini;
System.out.print("\t\t"+count);
System.out.print("\t\t"+drop);
drop=0;
System.out.println();
}
for(;count!=0;i++)
{
if(count>cap)
{
drop=count-cap;
count=cap;
}
System.out.print(i+1);
System.out.print("\t\t0");
mini=min(count,process);
System.out.print("\t\t"+mini);
count=count-mini;
System.out.print("\t\t"+count);
System.out.print("\t\t"+drop);
System.out.println();
}
}
Output:
VIVA QUESTIONS
1. What are functions of different layers?
2. Differentiate between TCP/IP Layers and OSI Layers
3. Why header is required?
4. What is the use of adding header and trailer to frames?
5. What is encapsulation?
6. Why fragmentation requires?
7. What is MTU?
8. Which layer imposes MTU?
9. Differentiate between flow control and congestion control.
10. Differentiate between Point-to-Point Connection and End-to-End connections.
11. What are protocols running in different layers?
12. What is Protocol Stack?
13. Differentiate between TCP and UDP.
14. Differentiate between Connectionless and connection oriented connection.
15. Why frame sorting is required?
16. What is meant by subnet?
17. What is meant by Gateway?
18. What is an IP address?
19. What is MAC address?
20. Why IP address is required when we have MAC address?
21. What is meant by port?
22. What are ephemerical port number and well known port numbers?
23. What is a socket?
24. What are the parameters of socket()?
25. Describe bind(), listen(), accept(),connect(), send() and recv().
26. What are system calls? Mention few of them.
27. What is IPC? Name three techniques.
28. Explain mkfifo(), open(), close() with parameters.
29. What is meant by file descriptor?
30. What is meant by traffic shaping?
31. How do you classify congestion control algorithms?
32. Differentiate between Leaky bucket and Token bucket.
33. How do you implement Leaky bucket?
Dept. of CSE, CIT, Gubbi Page no 58
Computer Network Laboratory 2017-18
REFERENCE