Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

CN LAB programs

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 33

Introduction to Network Simulators

Network simulators implemented in software are valuable tools for researchers to develop, test,
and diagnose network protocols. Simulation is economical because it can carry out experiments
without the actual hardware. It is flexible because it can, for example, simulate a link with any
bandwidth and propagation delay. Simulation results are easier to analyze than experimental
results because important information at critical points can be easily logged to help researchers
diagnose network protocols.
Network simulators, however, have their limitations. A complete network simulator needs to
simulate networking devices (e.g., hosts and routers) and application programs that generate
network traffic. It also needs to provide network utility programs to configure, monitor, and
gather statistics about a simulated network. Therefore, developing a complete network simulator
is a large effort. Due to limited development resources, traditional network simulators usually
have the following drawbacks:
• Simulation results are not as convincing as those produced by real hardware and software
equipment. In order to constrain their complexity and development cost, most network simulators
usually can only simulate real-life network protocol implementations with limited details, and this
may lead to incorrect results.
• These simulators are not extensible in the sense that they lack the standard UNIX POSIX
application programming interface (API). As such, existing or to-be-developed real-life
application programs cannot run normally to generate traffic for a simulated network.
Instead, they must be rewritten to use the internal API provided by the simulator (if there is any)
and be compiled with the simulator to form a single, big, and complex program.
To overcome these problems, Wang invented a kernel re-entering simulation methodology and
used it to implement the Harvard network simulator. Later on, Wang further improved the
methodology and used it to design and implement the NCTUns network simulator and emulator.
Different types of simulators
Some of the different types of simulators are as follows:-
 MIT's NETSIM
 NIST
 CPSIM
 INSANE
 NEST
 REAL
 NS
 OPNET
 NCTUns
 P
 GNS3
 WireShark
1. Implement three nodes point – to – point network with duplex links between them
for different topologies. 1 Set the queue size, vary the bandwidth and find the
number of packets dropped for various iterations.

Source Code :
pa1.tcl
set ns [new Simulator]
set nf [open pa1.nam w]
$ns namtrace-all $nf
set tf [open pa1.tr w]
$ns trace-all $tf

proc finish {} {
global ns nf tf
$ns flush-trace
close $nf
close $tf
exec nam pa1.nam &
exit 0
}
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]

#$ns color 1 "red"


#$ns color 2 "blue"

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


$ns duplex-link $n1 $n2 50Mb 5ms DropTail
$ns duplex-link $n2 $n3 10Mb 1000ms DropTail
#$ns duplex-link $n0 $n2 color "green"

$ns queue-limit $n0 $n2 10


$ns queue-limit $n1 $n2 10

set udp0 [new Agent/UDP]


$ns attach-agent $n0 $udp0

set cbr0 [new Application/Traffic/CBR]


$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0
set udp1 [new Agent/UDP]
$ns attach-agent $n1 $udp1

set cbr1 [new Application/Traffic/CBR]


$cbr1 attach-agent $udp1
set udp2 [new Agent/UDP]
$ns attach-agent $n2 $udp2

set cbr2 [new Application/Traffic/CBR]


$cbr2 attach-agent $udp2

set null0 [new Agent/Null]


$ns attach-agent $n3 $null0
$ns connect $udp0 $null0
$ns connect $udp1 $null0
$ns at 0.1 "$cbr0 start"
$ns at 0.2 "$cbr1 start"
$ns at 1.0 "finish"
$ns run

Source Code:

pa1.awk
BEGIN {
c=0;
}
{
if ($1=="d")
{
c++;
printf("%s\t%s\n",$5,$11);
}
}
END {
printf("The number of packet dropped= %d\n",c);
}
Output:
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 in
the network.

Source Code
pa4.tcl
set ns [ new Simulator ]
set nf [ open pa2.nam w ]

$ns namtrace-all $nf


set tf [ open pa2.tr w ]
$ns trace-all $tf

set n0 [$ns node]


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

$n4 shape box


$ns duplex-link $n0 $n4 1005Mb 1ms DropTail
$ns duplex-link $n1 $n4 50Mb 1ms DropTail
$ns duplex-link $n2 $n4 2000Mb 1ms DropTail
$ns duplex-link $n3 $n4 200Mb 1ms DropTail
$ns duplex-link $n4 $n5 1Mb 1ms DropTail

set p1 [new Agent/Ping]


$ns attach-agent $n0 $p1
$p1 set packetSize_ 500000
$p1 set interval_ 0.0001

set p2 [new Agent/Ping]


$ns attach-agent $n1 $p2

set p3 [new Agent/Ping]


$ns attach-agent $n2 $p3
$p3 set packetSize_ 30000
$p3 set interval_ 0.00001

set p4 [new Agent/Ping]


$ns attach-agent $n3 $p4

set p5 [new Agent/Ping]


$ns attach-agent $n5 $p5
$ns queue-limit $n0 $n4 5
$ns queue-limit $n2 $n4 3
$ns queue-limit $n4 $n5 2

Agent/Ping instproc recv {from rtt} {


$self instvar node_
puts "node [$node_ id] received answer from $from with round trip time $rtt msec"
}

$ns connect $p1 $p5


$ns connect $p3 $p4

proc finish { } {
global ns nf tf
$ns flush-trace
close $nf
close $tf
exec nam pa2.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"
$ns at 1.1 "$p1 send"
$ns at 1.2 "$p1 send"
$ns at 1.3 "$p1 send"
$ns at 1.4 "$p1 send"
$ns at 1.5 "$p1 send"
$ns at 1.6 "$p1 send"
$ns at 1.7 "$p1 send"
$ns at 1.8 "$p1 send"
$ns at 1.9 "$p1 send"
$ns at 2.0 "$p1 send"
$ns at 2.1 "$p1 send"
$ns at 2.2 "$p1 send"
$ns at 2.3 "$p1 send"
$ns at 2.4 "$p1 send"
$ns at 2.5 "$p1 send"
$ns at 2.6 "$p1 send"
$ns at 2.7 "$p1 send"
$ns at 2.8 "$p1 send"
$ns at 2.9 "$p1 send"
$ns at 0.1 "$p3 send"
$ns at 0.2 "$p3 send"
$ns at 0.3 "$p3 send"
$ns at 0.4 "$p3 send"
$ns at 0.5 "$p3 send"
$ns at 0.6 "$p3 send"
$ns at 0.7 "$p3 send"
$ns at 0.8 "$p3 send"
$ns at 0.9 "$p3 send"
$ns at 1.0 "$p3 send"
$ns at 1.1 "$p3 send"
$ns at 1.2 "$p3 send"
$ns at 1.3 "$p3 send"
$ns at 1.4 "$p3 send"
$ns at 1.5 "$p3 send"
$ns at 1.6 "$p3 send"
$ns at 1.7 "$p3 send"
$ns at 1.8 "$p3 send"
$ns at 1.9 "$p3 send"
$ns at 2.0 "$p3 send"
$ns at 2.1 "$p3 send"
$ns at 2.2 "$p3 send"
$ns at 2.3 "$p3 send"
$ns at 2.4 "$p3 send"
$ns at 2.5 "$p3 send"
$ns at 2.6 "$p3 send"
$ns at 2.7 "$p3 send"
$ns at 2.8 "$p3 send"
$ns at 2.9 "$p3 send"
$ns at 3.0 "finish"
$ns run

Source Code :
pa4.awk

BEGIN{
drop=0;
}

{
if($1=="d")
{
drop++;
}
}
END{
printf("Total number of %s packets dropped due to congestion=%d\n",$5,drop);
}
Output
3. Implement an Ethernet LAN using n nodes and set multiple traffic nodes and plot
congestion window for different source / destination.
Source Code:
pa6.tcl

set ns [new Simulator]


set tf [open pa3.tr w]
$ns trace-all $tf

set nf [open pa3.nam w]


$ns namtrace-all $nf
set n0 [$ns node]
$n0 color "magenta"
$n0 label "src1"
set n1 [$ns node]
set n2 [$ns node]
$n2 color "magenta"
$n2 label "src2"
set n3 [$ns node]
$n3 color "blue"
$n3 label "dest2"
set n4 [$ns node]
set n5 [$ns node]
$n5 color "blue"
$n5 label "dest1"

$ns make-lan "$n0 $n1 $n2 $n3 $n4" 100Mb 100ms LL Queue/DropTail Mac/802_3
$ns duplex-link $n4 $n5 1Mb 1ms DropTail

set tcp0 [new Agent/TCP]


$ns attach-agent $n0 $tcp0

set ftp0 [new Application/FTP]


$ftp0 attach-agent $tcp0
$ftp0 set packetSize_ 500
$ftp0 set interval_ 0.0001

set sink5 [new Agent/TCPSink]


$ns attach-agent $n5 $sink5
$ns connect $tcp0 $sink5

set tcp2 [new Agent/TCP]


$ns attach-agent $n2 $tcp2

set ftp2 [new Application/FTP]


$ftp2 attach-agent $tcp2
$ftp2 set packetSize_ 600
$ftp2 set interval_ 0.0001

set sink3 [new Agent/TCPSink]


$ns attach-agent $n3 $sink3
$ns connect $tcp2 $sink3
set file1 [open file1.tr w]
$tcp0 attach $file1
set file2 [open file2.tr w]
$tcp2 attach $file2
$tcp0 trace cwnd_
$tcp2 trace cwnd_

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

$ns at 0.1 "$ftp0 start"


$ns at 5 "$ftp0 stop"
$ns at 7 "$ftp0 start"
$ns at 0.2 "$ftp2 start"
$ns at 8 "$ftp2 stop"
$ns at 14 "$ftp0 stop"
$ns at 10 "$ftp2 start"
$ns at 15 "$ftp2 stop"
$ns at 16 "finish"
$ns run

Source Code:

pa6.awk

BEGIN {
}
{
if($6=="cwnd_")
printf("%f\t%f\t\n",$1,$7);
}
END{
}
Output:
4. Write a program for error detecting code using CRC-CCITT (16- bits).
Cyclic Redundancy Check Code for Error – Detection
The cyclic Redundancy Check (CRC) id a technique for detecting errors in data transmission,
but not for correcting errors when they are detected.
CCITT- Consultative Committee for International Telegraphy and Telephone.

Algorithm:
A) For Computing CRC:
 The CRC Algorithm is based on polynomial arithmetic.
 Let the message that we have to send has k bits (denoted by M(x) in polynomial form
having degree (k-1)) the sender and the receiver are agreed upon a generator polynomial
having r bits (denoted by G(x) in polynomial form having degree (r-1)). The generator
polynomial is also called “Divisor”.
 Now, append (r-1) zero bits to the LSB side of the message M(x) so it will now contain
(k+r- 1) bits and corresponds to the polynomial x(r-1) M (x).
 Divide the polynomial x(r-1) M (x) by Divisor, using modulo-2 subtraction (bit by bit XOR
operation). Add the remainder R(x) (called frame check sequence) to x (r-1) M (x), using
modulo -2 additions (bit by bit XOR operation). This is the message that will be
transmitted by the transmitter denoted by T(x).
B) For Error Detection:
 Suppose that a transmission error occurs, so that the received message at the receiver is
T(x) +E(x), instead of T(x). Each 1 bit in E(x) corresponds to a bit that has been inverted.
 The received message at the receiver end is divided by G(x), i.e. [T(x) + E(x) / G(x) ].
Since T(x)/G(x) is 0, so the result is simply E(x)/G(x).
 If E(x)/G(x) =0 than there is no error in the received message, otherwise there is an error.
 The following type of errors can be detected using CRC:
If G(x) has more than one bit and the coefficient of x0 is 1, then all single bit errors are
detected.
If G(x) is not divisible by x ( the coefficient of x0 is 1) , and t is the least positive
integer (0<t<n-1) such that G(x) divides x1 + 1, then all isolated double errors are
detected.
If G(x) has a factor (x+1), then all odd numbered errors are detected.
Source code:
import java.io.*;
class crc
{
public static void main(String[] args)
{
InputStreamReader isr=new InputStreamReader (System.in);
BufferedReader br=new BufferedReader(isr);
int[] message;
int[] gen;
int[] app_message;
int[] rem;
int[] trans_message;
int message_bits,gen_bits,total_bits;
System.out.println("\n Enter the no of bits in the message");
message_bits=Integer.parseInt(br.readLine());
message=new int[message_bits];
System.out.println("\n Enter the message bits");
for(int i=o;i<message_bits;i++)
message[i]=Integer.parseInt(br.readLine());
System.out.println("\n Enter the no of bits generated ");
gen_bits=Integer.parseInt(br.readLine());
gen=new int[gen_bits];
System.out.println("\n Enter the generated bits");
for(int i=o;i<gen_bits;i++);
{
gen[i]=Integer.parseInt(br.readLine());
}
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.print("\n Message bits :");
for(int i=o;i<message_bits;i++)
{
System.out.print(message[i]);
}
System.out.print("\n Generated bits :");
for(int i=0;i<gen_bits;i++)
{
System.out.print(gen[i]);
}
System.out.print("\n Appended message :");
for(int i=0;i<app_message.length;i++)
{
System.out.print(app_message[i]);
}
for(int j=0;j<app_message.length;j++)
{
rem[j]=app_message[j];
}
rem=computecrc(app_message.length;i++)
for(int i=0;i<app_message.length;i++)
{
trans_mesage[i]=(app_message[i]^rem[i]);
}
System.out.println("\n Transmitted message from the transmitter :");
for(int i=0;i<trans_message.length;i++)
{
System.out.print(trans_message[i]);
}
System.out.println("\n Message of"+total_bits+"bits received");
for(int i=0;i<trans_message.length;i++)
{
trans_messge[i]=Inter.parseInt(br.readLine());
}
System.out.println("\n Recevied message is :");
for(int i=0;i<trans_message.length;i++)
{
System.out.print(trans_message[i]);
}
for(int j=0;j<trans_message.length;j++)
{
rem[j]=trans_message[j];
}
rem=computercrc(trans_message,gen,rem);
for (int i=0;i<rem.length;i++)
{
if(rem[i]!=0)
{
System.out.println("\n There is error");
break;
}
if(i==rem.length-1)
{
System.out.println("\n There is no error");
}
}
static int[] computecrc(int app_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;
}
}
}

Output:
Enter the no of bits in the message : 4
Enter the message bits : 1 0 0 1
Enter the no of bits generated : 17
Enter the generated bits :
10001000000100001
Message bits: 1 0 0 1
Generated bits : 1 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 1
Appended message : 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Transmitted message from transmitter : 1 0 0 1 1 0 0 1 0 0 0 1 0 0 1 0 1 0 0 1
Message of 20 bits received :
10011001000100101001
There is no error

Enter the no of bits in the message : 4


Enter the message bits : 1 0 0 1
Enter the no of bits generated : 17
Enter the generated bits :
10001000000100001
Message bits: 1 0 0 1
Generated bits : 1 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 1
Appended message : 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Transmitted message from transmitter : 1 0 0 1 1 0 0 1 0 0 0 1 0 0 0 1 0 1 0 0 1
Message of 20 bits received :
10011001010100101010
There is an error
5. Develop a program to implement a sliding window protocol in the data link layer.
Source code
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
import java.util.Scanner;

class Frame {
int id;

public Frame(int id) {


this.id = id;
}

public int getId() {


return id;
}
}

class Sender {
private Queue<Frame> window;
private int windowSize;
private int nextFrameToSend;
private int lastAckReceived;

public Sender(int windowSize) {


this.window = new LinkedList<>();
this.windowSize = windowSize;
this.nextFrameToSend = 0;
this.lastAckReceived = -1;
}

public void sendFrames(int totalFrames) {


System.out.println("Starting transmission of " + totalFrames + " frames...");

while (lastAckReceived < totalFrames - 1) {


// Send frames within the window
while (window.size() < windowSize && nextFrameToSend < totalFrames) {
Frame frame = new Frame(nextFrameToSend);
window.offer(frame);
System.out.println("Sender: Sending frame " + frame.getId());
nextFrameToSend++;
}
// Simulate acknowledgment receipt
receiveAck();
}
}
public void receiveAck() {
Random random = new Random();
if (!window.isEmpty()) {
Frame frame = window.peek();
int frameId = frame.getId();

// Simulating 80% chance of successful acknowledgment


if (random.nextInt(100) < 80) {
System.out.println("Receiver: Acknowledgment received for frame " + frameId);
lastAckReceived = frameId;
window.poll(); // Remove frame from the window
} else {
System.out.println("Receiver: Frame " + frameId + " lost, resending...");
resendFrames();
}
}
}

public void resendFrames() {


for (Frame frame : window) {
System.out.println("Sender: Resending frame " + frame.getId());
}
}
}

public class SlidingWindowProtocol {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter total number of frames to send: ");


int totalFrames = scanner.nextInt();

System.out.print("Enter the size of the sliding window: ");


int windowSize = scanner.nextInt();

Sender sender = new Sender(windowSize);


sender.sendFrames(totalFrames);

scanner.close();
}
}
Sample Output

# Navigate to the directory


cd C:\JavaPrograms

# Compile the Java program


javac SlidingWindowProtocol.java

# Run the Java program


java SlidingWindowProtocol

Enter total number of frames to send: 5


Enter the size of the sliding window: 3
Starting transmission of 5 frames...
Sender: Sending frame 0
Sender: Sending frame 1
Sender: Sending frame 2
Receiver: Acknowledgment received for frame 0
Sender: Sending frame 3
Receiver: Acknowledgment received for frame 1
Receiver: Frame 2 lost, resending...
Sender: Resending frame 2
Receiver: Acknowledgment received for frame 2
Sender: Sending frame 4
Receiver: Acknowledgment received for frame 3
Receiver: Acknowledgment received for frame 4
6. Develop a program to find the shortest path between
vertices using the Bellman-Ford and path vector routing
algorithm.

Bell man ford algorithm is a procedure used to find all shortest path in a graph from one
source to all other nodes. The algorithm was introduced by American mathematicians
Richard Bellman and Lester ford. Computes shortest from a single source vertex to all of
the other vertices in a weighted diagraph.

Source Code:

import java.io.*;
import java.util.*;
import java.io.DataInputStream;
class Edge
{
int source;
int dest;
int weight;
}

class Bellman
{
public static void BellmanFord(Edge edges[], int edgecount, int nodecount, int
source)
{
int infinity=50000;
int i, j;
int distance[]=new int[nodecount];
for(i=0; i&lt;nodecount; i++)
distance[i]=infinity;
distance[source]=0;
for(i=0; i&lt;nodecount; i++)
{
boolean somethingchanged=false;
for(j=0; j&lt;edgecount; j++)
{
if(distance[edges[j].source]!=infinity)
{
int new_distance=distance[edges[j].source]+edges[j].weight;
if(new_distance&lt;distance[edges[j].dest])
{
distance[edges[j].dest]=new_distance;
somethingchanged=true;
}
}
}
if(!somethingchanged)
break;
}
for(i=0; i&lt;edgecount; ++i)
{
if(distance[edges[i].dest]&gt;distance[edges[i].source]+edges[i].weight)
System.out.println(&quot;Negative edge weightcycles detected!!!&quot;);
}
for(i=0; i&lt;nodecount; ++i)
System.out.println(&quot;The shortest distance between nodes &quot;
+source+&quot; &amp; &quot;+i+&quot; is &quot;+distance[i]);
}
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
Edge edges[]=new Edge[10];
for( int i=0; i&lt;10; i++)
{
edges[i]=new Edge();
System.out.print(&quot;Enter source number [&quot;+i+&quot;] :
&quot;);
edges[i].source=in.nextInt();
System.out.print(&quot;Enter destination number [&quot;+i+&quot;] :
&quot;);
edges[i].dest=in.nextInt();
System.out.print(&quot;Enter weight number [&quot;+i+&quot;] :
&quot;);
edges[i].weight=in.nextInt();
System.out.println();
}
BellmanFord(edges, 10, 5, 4);
}
}
Output:
Enter the number of vertices : 4
Enter the adjacency matrix:
0 5 999 999
5024
999 2 0 1
999 4 1 0

Enter source of vertex: 1


Distance of source 1 to 1 is 0
Distance of source 1 to 2 is 5
Distance of source 1 to 3 is 7
Distance of source 1 to 4 is 8

Enter the number of vertices : 6


Enter the adjacency matrix:
0 10 3 999 999 999
999 0 999 -3 2 999
999 999 0 3 999 999
999 999 999 0 4 1
999 -1 999 999 0 999
999 999 999 999 4 0

Enter source of vertex: 1


Distance of source 1 to 1 is 0
Distance of source 1 to 2 is 9
Distance of source 1 to 3 is 3
Distance of source 1 to 4 is 6
Distance of source 1 to 5 is 10
Distance of source 1 to 6 is 7
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 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.

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();
System.out.println("Receving file: "+filename);
filename="client"+filename;
System.out.println("Saving as file: "+filename);
long sz=Long.parseLong(din.readUTF());
System.out.println ("File Size: "+(sz/(1024*1024))+" MB");
byte b[]=new byte [1024]; System.out.println("Receving file..");

FileOutputStream fos=new FileOutputStream(new File(filename),true); long bytesRead;


do {
bytesRead = din.read(b, 0, b.length);
fos.write(b,0,b.length); }
while(!(bytesRead<1024));
System.out.println("Comleted");
fos.close();
dout.close();
s.close();
}
catch(EOFException e)
{
//do nothing } } }

TCP Server
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
class Server
{
public static void main(String args[])throws Exception
{
String filename; System.out.println("Enter File Name: ");
Scanner sc=new Scanner(System.in);
filename=sc.nextLine();
sc.close();
while(true)
{
//create server socket on port 5000
ServerSocket ss=new ServerSocket(5000);
System.out.println ("Waiting for request");
Socket s=ss.accept();
System.out.println ("Connected With "+s.getInetAddress().toString());
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
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
Note:
Create two different files Client.java and Server.java. Follow the steps given:
1. Open a terminal run the server program and provide the filename to send
2. Open one more terminal run the client program and provide the IP address of the
server. We can give localhost address “127.0.0.1” as it is running on same machine
or give the IP address of the machine.
3. Send any start bit to start sending file.

At server side:
At Client side:
8. Develop a program on a 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.

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
1. Open a terminal run the server program.
2. Open one more terminal run the client program, the sent
message will be received.
Create two different files
UDPC.java and UDPS.java
Follow the following steps:

At Server side:

At Client side:
9. Develop a program for a simple RSA algorithm to encrypt
and decrypt the data.

1. Key Generation
2. Encryption
3. Decryption

1. Key Generation
In the RSA scheme, the key length is typically 512 bits, which requires an enormous
computational power. A plaintext is encrypted in blocks, with each block having a binary
value less than some number n. Encryption and decryption are done as follows,
beginning with the generation of a public key and a private key.

Begin Key Generation Algorithm


1. Choose two roughly 256-bit prime numbers, p and q, and device n = pq. (A number is
prime if it has factors of 1 and itself.)
2. Find x. Select encryption key x and (p - 1) (q - 1) are relatively prime. (Two numbers are
relatively prime if they have no common factor greater than 1.)
3. Find y. Calculate decryption key y:
x y mod (p - 1) (q - 1) = 1
4. At this point, p and q can be discarded.
5. The public key = { x, n }
6. The private key = { y, n }
In this algorithm, x and n are known to both sender and receiver, but only the receiver
must know y. Also, p and q must be large and about the same size and both greater than
1,024 bits. The larger these two values, the more secure the encryption.

2. Encryption
c=mx mod n.

3. Decryption
m=cy mod n.

/* RSA Key Generation*/


import java.util.*;
import java.math.BigInteger; import java.lang.*;
class RSAkeygen
{
public static void main(String[] args)
{
Random rand1=new Random(System.currentTimeMillis());
Random rand2=new Random(System.currentTimeMillis()*10);
int pubkey=Integer.parseInt(args[0]);
BigInteger bigB_p=BigInteger.probablePrime(32, rand1);
BigInteger bigB_q=BigInteger.probablePrime(32, rand2);
BigInteger bigB_n=bigB_p.multiply(bigB_q);
BigInteger bigB_p_1=bigB_p.subtract(new BigInteger("1"));
BigInteger bigB_q_1=bigB_q.subtract(new BigInteger("1"));
BigInteger bigB_p_1_q_1=bigB_p_1.multiply(bigB_q_1);
while(true)
{
BigInteger BigB_GCD=bigB_p_1_q_1.gcd(new BigInteger(""+pubkey));
if(BigB_GCD.equals(BigInteger.ONE))
{
break;
}
pubkey++;
}
BigInteger bigB_pubkey=new BigInteger(""+pubkey);
BigInteger bigB_prvkey=bigB_pubkey.modInverse(bigB_p_1_q_1);
System.out.println("public key : "+bigB_pubkey+","+bigB_n);
System.out.println("private key : "+bigB_prvkey+","+bigB_n);
}
}

/*RSA Encryption and Decryption*/


import java.math.BigInteger; import java.util.*;
class RSAEncDec
{
public static void main(String[] args)
{
BigInteger bigB_pubkey = new BigInteger(args[0]); BigInteger bigB_prvkey = new
BigInteger(args[1]); BigInteger bigB_n = new BigInteger(args[2]);
int asciiVal=Integer.parseInt(args[3]);
BigInteger bigB_val=new BigInteger(""+asciiVal);
BigInteger bigB_cipherVal=bigB_val.modPow(bigB_pubkey,bigB_n);
System.out.println("Cipher text: " + bigB_cipherVal);
BigInteger bigB_plainVal=bigB_cipherVal.modPow(bigB_prvkey,bigB_n);
int plainVal=bigB_plainVal.intValue();
System.out.println("Plain text:" + plainVal);
}
}
Output:
Key Generation

Encryption and Decryption


10. Write a program for congestion control using leaky bucket algorithm.
What is congestion?
A state occurring in network layer when the message traffic is so heavy that it slows down
network response time.
Effects of Congestion
 As delay increases, performance decreases.
 If delay increases, retransmission occurs, making situation worse.

Traffic shaping or policing: To control the amount and rate of traffic is called Traffic
shaping or policing. Traffic shaping term is used when the traffic leaves a network.
Policing term is used when the data enters the network. Two techniques can shape or police
the traffic leaky bucket and token bucket.

Congestion control algorithms


Leaky Bucket Algorithm

Let us consider an example to understand


Imagine a bucket with a small hole in the bottom. No matter at what rate water enters the
bucket, the outflow is at constant rate. When the bucket is full with water additional water
entering spills over the sides and is lost.
Similarly, each network interface contains a leaky bucket and the following steps are
involved in leaky bucket algorithm:
1. When host wants to send packet, packet is thrown into the bucket.
2. The bucket leaks at a constant rate, meaning the network interface transmits packets at a
constant rate.
3. Bursty traffic is converted to a uniform traffic by the leaky bucket.
4. In practice the bucket is a finite queue that outputs at a finite rate.
Source Code:

importjava.util.*;
public class leaky
{
public static void main(String[] args)
{
Scanner my = new Scanner(System.in);
intno_groups,bucket_size;
System.out.print("\n Enter the bucket size : \t");
bucket_size = my.nextInt();
System.out.print("\n Enter the no of groups : \t");
no_groups = my.nextInt();
intno_packets[] = new int[no_groups];
intin_bw[] = new int[no_groups];
intout_bw,reqd_bw=0,tot_packets=0;
for(inti=0;i<no_groups;i++)
{
System.out.print("\n Enter the no of packets for group " + (i+1) + "\t");
no_packets[i] = my.nextInt();
System.out.print("\n Enter the input bandwidth for the group " + (i+1) + "\t");
in_bw[i] = my.nextInt();
if((tot_packets+no_packets[i])<=bucket_size)
{
tot_packets += no_packets[i];
}
else
{
do
{
System.out.println(" Bucket Overflow ");
System.out.println(" Enter value less than " + (bucket_size-
tot_packets));
no_packets[i] = my.nextInt();
}while((tot_packets+no_packets[i])>bucket_size);
tot_packets += no_packets[i];
}
reqd_bw += (no_packets[i]*in_bw[i]);
}

System.out.println("\nThe total required bandwidth is " + reqd_bw);


System.out.println("Enter the output bandwidth ");
out_bw = my.nextInt();
int temp=reqd_bw;
intrem_pkts = tot_packets;

while((out_bw<=temp)&&(rem_pkts>0))
{
System.out.println("Data Sent \n" + (--rem_pkts) + " packets remaining");
System.out.println("Remaining Bandwidth " + (temp -= out_bw));
if((out_bw>temp)&&(rem_pkts>0))
System.out.println(rem_pkts + " packet(s) discarded due to insufficient
bandwidth");
}
}
}

Out Put:
Enter bucket size : 20
Enter number of groups :2
Enter number of packets of group 1:2
Enter input bandwidth for group 1:2
Enter number of packets of group 2 :3
Enter input bandwidth for group 2 : 3
Total required bandwidth :13
Enter the output bandwidth:2

Data sent
4 packets remaining
Remaining bandwidth:11
Data sent
3 packets remaining
Remaining bandwidth : 9
Data sent
2 packets remaining
Remaining bandwidth :7
Data sent
1 packets remaining
Remaining bandwidth :5
Data sent
0 packets remaining
Remaining bandwidth :3

You might also like