1. 1. Implement
three nodes point – to – point network with duplex links between them. Set the
queue size, vary the bandwidth, and find the number of packets dropped. #Create
Simulator
set ns [new Simulator]
#Open Trace file and NAM file
set ntrace [open prog1.tr w]
$ns trace-all $ntrace
set namfile [open prog1.nam w]
$ns namtrace-all $namfile
#Finish Procedure
proc Finish {} {
global ns ntrace namfile
#Dump all the trace data and close the
files
$ns flush-trace
close $ntrace
close $namfile
#Execute the nam animation file
exec nam prog1.nam &
#Show the number of packets dropped
exec echo “The number of packet drops
is ” &
exec grep -c “^d” prog1.tr &
exit 0
}
#Create 3 nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
#Label the nodes
$n0 label “TCP Source”
$n2 label “Sink”
#Set the color
$ns color 1 blue
#Create Links between nodes
#You need to modify the bandwidth to
observe the variation in packet drop
$ns duplex-link $n0 $n1 1Mb 10ms DropTail
$ns duplex-link $n1 $n2 1Mb 10ms DropTail
#Make the Link Orientation
$ns duplex-link-op $n0 $n1 orient right
$ns duplex-link-op $n1 $n2 orient right
#Set Queue Size
#You can modify the queue length as well
to observe the variation in packet drop
$ns queue-limit $n0 $n1 10
$ns queue-limit $n1 $n2 10
#Set up a Transport layer connection.
set tcp0 [new Agent/TCP]
$ns attach-agent $n0 $tcp0
set sink0 [new Agent/TCPSink]
$ns attach-agent $n2 $sink0
$ns connect $tcp0 $sink0
#Set up an Application layer Traffic
set cbr0 [new Application/Traffic/CBR]
$cbr0 set type_ CBR
$cbr0 set packetSize_ 100
$cbr0 set rate_ 1Mb
$cbr0 set random_ false
$cbr0 attach-agent $tcp0
$tcp0 set class_ 1
#Schedule Events
$ns at 0.0 “$cbr0 start”
$ns at 5.0 “Finish”
#Run the Simulation
$ns run
1. 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.
#Create Simulator
set ns [new Simulator]
#Use colors to differentiate the traffic
$ns color 1 Blue
$ns color 2 Red
#Open trace and NAM trace file
set ntrace [open prog3.tr w]
$ns trace-all $ntrace
set namfile [open prog3.nam w]
$ns namtrace-all $namfile
#Finish Procedure
proc Finish {} {
global ns ntrace namfile
#Dump all trace data and close the file
$ns flush-trace
close $ntrace
close $namfile
#Execute the nam animation file
exec nam prog3.nam &
#Find the number of ping packets dropped
puts “The number of ping packets
dropped are “
exec grep “^d” prog3.tr | cut -d
” ” -f 5 | grep -c “ping” &
exit 0
}
#Create six nodes
for {set i 0} {$i < 6} {incr i} {
set n($i) [$ns node]
}
#Connect the nodes
for {set j 0} {$j < 5} {incr j} {
$ns duplex-link $n($j) $n([expr ($j+1)])
0.1Mb 10ms DropTail
}
#Define the recv function for the class
‘Agent/Ping’
Agent/Ping instproc recv {from rtt} {
$self instvar node_
puts “node [$node_ id] received ping
answer from $from with round trip time $rtt
ms”
}
#Create two ping agents and attach them to
n(0) and n(5)
set p0 [new Agent/Ping]
$p0 set class_ 1
$ns attach-agent $n(0) $p0
set p1 [new Agent/Ping]
$p1 set class_ 1
$ns attach-agent $n(5) $p1
$ns connect $p0 $p1
#Set queue size and monitor the queue
#Queue size is set to 2 to observe the
drop in ping packets
$ns queue-limit $n(2) $n(3) 2
$ns duplex-link-op $n(2) $n(3) queuePos
0.5
#Create Congestion
#Generate a Huge CBR traffic between n(2)
and n(4)
set tcp0 [new Agent/TCP]
$tcp0 set class_ 2
$ns attach-agent $n(2) $tcp0
set sink0 [new Agent/TCPSink]
$ns attach-agent $n(4) $sink0
$ns connect $tcp0 $sink0
#Apply CBR traffic over TCP
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set rate_ 1Mb
$cbr0 attach-agent $tcp0
#Schedule events
$ns at 0.2 “$p0 send”
$ns at 0.4 “$p1 send”
$ns at 0.4 “$cbr0 start”
$ns at 0.8 “$p0 send”
$ns at 1.0 “$p1 send”
$ns at 1.2 “$cbr0 stop”
$ns at 1.4 “$p0 send”
$ns at 1.6 “$p1 send”
$ns at 1.8 “Finish”
#Run the Simulation
$ns run
1. 3. Implement
an Ethernet LAN using n nodes and set multiple traffic nodes and plot
congestion window for different source / destination.
set ns [new Simulator]
$ns color 1 Red
$ns color 2 Blue
set na [open Lab3.nam w]
$ns namtrace-all $na
set nt [open Lab3.tr w]
$ns trace-all $nt
set ng1 [open tcp1.xg w]
set ng2 [open tcp2.xg w]
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
$ns make-lan “$n0 $n1 $n2” 1Mb
10ms LL Queue/DropTail Mac/802_3
$ns make-lan “$n3 $n4 $n5” 2Mb
10ms LL Queue/DropTail Mac/802_3
$ns duplex-link $n0 $n3 1Mb 10ms DropTail
set tcp1 [new Agent/TCP]
set tcp2 [new Agent/TCP]
set cbr1 [new Application/Traffic/CBR]
set cbr2 [new Application/Traffic/CBR]
$ns attach-agent $n4 $tcp1
$cbr1 attach-agent $tcp1
$ns attach-agent $n1 $tcp2
$cbr2 attach-agent $tcp2
set sink1 [new Agent/TCPSink]
set sink2 [new Agent/TCPSink]
$ns attach-agent $n2 $sink1
$ns attach-agent $n5 $sink2
$ns connect $tcp1 $sink1
$ns connect $tcp2 $sink2
proc End {} {
global ns na nt
$ns flush-trace
close $na
close $nt
exec nam Lab3.nam &
exec xgraph tcp1.xg tcp2.xg &
exit 0
}
proc Draw {Agent File} {
global ns
set Cong [$Agent set cwnd_]
set Time [$ns now]
puts $File “$Time $Cong”
$ns at [expr $Time+0.01] “Draw $Agent
$File”
}
$ns at 0.0 “$cbr1 start”
$ns at 0.7 “$cbr2 start”
$ns at 0.0 “Draw $tcp1 $ng1”
$ns at 0.0 “Draw $tcp2 $ng2”
$ns at 10.0 “End”
$ns run
1. 4 Develop a program for
error detecting code using CRC-CCITT (16- bits).
import java.util.*;
class crc {
public static void
main(String args[]) {
Scanner scan = new
Scanner(System.in);
int n;
System.out.println(“Enter
the size of the data:”);
n = scan.nextInt();
int data[] = new int[n];
System.out.println(“Enter
the data, bit by bit:”);
for(int i=0 ; i < n ;
i++) {
data[i] = scan.nextInt();
}
System.out.println(“Enter
the size of the divisor:”);
n = scan.nextInt();
int divisor[] = new
int[n];
System.out.println(“Enter
the divisor, bit by bit:”);
for(int i=0 ; i < n ;
i++) {
divisor[i] =
scan.nextInt();
}
int remainder[] =
divide(data, divisor);
for(int i=0 ; i <
remainder.length-1 ; i++) {
System.out.print(remainder[i]);
}
System.out.println(“\nThe
CRC code generated is:”);
for(int i=0 ; i <
data.length ; i++) {
System.out.print(data[i]);
}
for(int i=0 ; i <
remainder.length-1 ; i++) {
System.out.print(remainder[i]);
}
System.out.println();
int sent_data[] = new
int[data.length + remainder.length – 1];
System.out.println(“Enter
the data to be sent:”);
for(int i=0 ; i <
sent_data.length ; i++) {
System.out.println(“Enter
bit number ” + (sent_data.length-i)
+ “:”);
sent_data[i] =
scan.nextInt();
}
receive(sent_data,
divisor);
}
static int[] divide(int
old_data[], int divisor[]) {
int remainder[] , i;
int data[] = new
int[old_data.length + divisor.length];
System.arraycopy(old_data,
0, data, 0, old_data.length);
remainder = new
int[divisor.length];
System.arraycopy(data, 0,
remainder, 0, divisor.length);
for(i=0 ; i < old_data.length
; i++) {
System.out.println((i+1)
+ “.) First data bit is : ” + remainder[0]);
System.out.print(“Remainder
: “);
if(remainder[0] == 1) {
for(int j=1 ; j <
divisor.length ; j++) {
remainder[j-1] =
exor(remainder[j], divisor[j]);
System.out.print(remainder[j-1]);
}
}
else {
for(int j=1 ; j <
divisor.length ; j++) {
remainder[j-1] =
exor(remainder[j], 0);
System.out.print(remainder[j-1]);
}
}
remainder[divisor.length-1]
= data[i+divisor.length];
System.out.println(remainder[divisor.length-1]);
}
return remainder;
}
static int exor(int a,
int b) {
if(a == b) {
return 0;
}
return 1;
}
static void receive(int
data[], int divisor[]) {
int remainder[] =
divide(data, divisor);
for(int i=0 ; i <
remainder.length ; i++) {
if(remainder[i] != 0) {
System.out.println(“There
is an error in received data…”);
return;
}
}
System.out.println(“Data
was received without any error.”);
}
}
1. 5 Develop a program to
implement a sliding window protocol in the data link layer.
import java.util.Scanner;
import java.util.Random;
import
java.util.concurrent.TimeUnit;
public class
SlidingWindowProtocol {
private int windowSize;
private int totalFrames;
private int senderWindowStart;
private boolean[] acknowledgments;
public SlidingWindowProtocol(int
windowSize, int totalFrames) {
this.windowSize = windowSize;
this.totalFrames = totalFrames;
this.senderWindowStart = 0;
this.acknowledgments = new
boolean[totalFrames]; // Track received
ACKs
}
private void sendFrame(int frame) {
System.out.println(“Sending frame:
” + frame);
try {
TimeUnit.MILLISECONDS.sleep(500);
// Simulate network delay
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
private void receiveAck(int frame) {
System.out.println(“Received ACK
for frame: ” + frame);
acknowledgments[frame] = true;
}
public void sender() {
while (senderWindowStart <
totalFrames) {
// Send frames in the current
window
int end =
Math.min(senderWindowStart + windowSize, totalFrames);
for (int frame = senderWindowStart;
frame < end; frame++) {
sendFrame(frame);
}
// Simulate receiving ACKs
for (int frame = senderWindowStart;
frame < end; frame++) {
if (new Random().nextBoolean())
{ // Simulate ACK reception with
randomness
receiveAck(frame);
} else {
System.out.println(“Frame ” + frame + ” lost, waiting for
retransmission”);
}
}
// Slide window
while (senderWindowStart < end
&& acknowledgments[senderWindowStart]) {
senderWindowStart++;
}
try {
TimeUnit.SECONDS.sleep(1); // Wait before sending next window of frames
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
public static void main(String[] args) {
Scanner scanner = new
Scanner(System.in);
try {
// Ask user for window size and
total number of frames
System.out.print(“Enter the
window size: “);
int windowSize = scanner.nextInt();
System.out.print(“Enter the
total number of frames: “);
int totalFrames =
scanner.nextInt();
// Validate input
if (windowSize <= 0 ||
totalFrames <= 0 || windowSize > totalFrames) {
System.out.println(“Invalid input. Ensure window size and total
number of frames are positive integers, and window size is less than or equal
to total frames.”);
return;
}
// Create the protocol simulation
SlidingWindowProtocol protocol =
new SlidingWindowProtocol(windowSize, totalFrames);
// Start sender
System.out.println(“Starting
Sliding Window Protocol Simulation”);
protocol.sender();
System.out.println(“Simulation
complete”);
} catch (Exception e) {
System.out.println(“Invalid
input. Please enter integer values for window size and total number of
frames.”);
} finally {
scanner.close();
}
}
}
1. 6 Develop
a program to find the shortest path between vertices using the Bellman-Ford and
path vector routing algorithm.
import java.util.Scanner;
public class BellmanFord
{
private int D[];
private int num_ver;
public static final int
MAX_VALUE = 999;
public BellmanFord(int
num_ver)
{
this.num_ver = num_ver;
D = new int[num_ver + 1];
}
public void
BellmanFordEvaluation(int source, int A[][])
{
for (int node = 1; node
<= num_ver; node++)
{
D[node] = MAX_VALUE;
}
D[source] = 0;
for (int node = 1; node
<= num_ver – 1; node++)
{
for (int sn = 1; sn <=
num_ver; sn++)
{
for (int dn = 1; dn <=
num_ver; dn++)
{
if (A[sn][dn] != MAX_VALUE)
{
if (D[dn] > D[sn]+
A[sn][dn])
D[dn] = D[sn] +
A[sn][dn];
}
}
}
}
for (int sn = 1; sn <=
num_ver; sn++)
{
for (int dn = 1; dn <=
num_ver; dn++)
{
if (A[sn][dn] !=
MAX_VALUE)
{
if (D[dn] > D[sn]+
A[sn][dn])
System.out.println(“The
Graph contains negative egde cycle”);
}
}
}
for (int vertex = 1;
vertex <= num_ver; vertex++)
{
System.out.println(“distance
of source ” + source + ” to ” + vertex + ” is ” +
D[vertex]);
}
}
public static void
main(String[ ] args)
{
int num_ver = 0;
int source;
Scanner scanner = new
Scanner(System.in);
System.out.println(“Enter
the number of vertices”);
num_ver =
scanner.nextInt();
int A[][] = new
int[num_ver + 1][num_ver + 1];
System.out.println(“Enter
the adjacency matrix”);
for (int sn = 1; sn <=
num_ver; sn++)
{
for (int dn = 1; dn <=
num_ver; dn++)
{
A[sn][dn] =
scanner.nextInt();
if (sn == dn)
{
A[sn][dn] = 0;
continue;
}
if (A[sn][dn] == 0)
{
A[sn][dn] = MAX_VALUE;
}
}
}
System.out.println(“Enter
the source vertex”);
source =
scanner.nextInt();
BellmanFord b = new
BellmanFord (num_ver);
b.BellmanFordEvaluation(source,
A);
scanner.close();
}
}
1. 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.
//tcp program server side
import java.net.*;
import java.io.*;
public class server1
{
public static void
main(String args[]) throws Exception
{
// establishing the connection
with the server
ServerSocket sersock =
new ServerSocket(4000);
System.out.println(“Server
ready for connection”);
Socket sock =
sersock.accept();
// binding with port:
4000
System.out.println(“Connection
is successful”);
// reading the file name
from client
InputStream istream =
sock.getInputStream( );
BufferedReader fileRead
=new BufferedReader(new InputStreamReader(istream));
String fname =
fileRead.readLine( );
// reading file contents
BufferedReader
contentRead = new BufferedReader(new FileReader(fname) );
// keeping output stream
ready to send the contents
OutputStream ostream =
sock.getOutputStream( );
PrintWriter pwrite = new
PrintWriter(ostream, true);
String str;
while((str =
contentRead.readLine()) != null) // reading line-by-line from file
{
pwrite.println(str);
// sending each line to
client
}
sock.close();
sersock.close();
// closing network
sockets
pwrite.close();
fileRead.close(); contentRead.close();
}
}
//tcp program client side
import java.net.*;
import java.io.*;
public class client1
{
public static void main(
String args[ ] ) throws Exception
{
Socket sock = new Socket(
“127.0.0.1”, 4000);
// reading the file name
from keyboard. Uses input stream
System.out.print(“Enter
the file name: ” );
BufferedReader keyRead =
new BufferedReader(new InputStreamReader(System.in));
String fname =
keyRead.readLine();
// sending the file name
to server. Uses PrintWriter
OutputStream ostream = sock.getOutputStream(
);
PrintWriter pwrite = new
PrintWriter(ostream, true);
pwrite.println(fname);
// receiving the contents
from server. Uses input stream
InputStream istream =
sock.getInputStream();
BufferedReader socketRead
= new BufferedReader(new InputStreamReader(istream));
String str;
while((str =
socketRead.readLine()) != null) // reading line-by-line
{
System.out.println(str);
}
pwrite.close();
socketRead.close(); keyRead.close();
}
}
//have to create new file
called exmaple.txt
1. 8 Develop
a program on a datagram socket for client/server to display the messages on
client side, typed at the server side.
//udp server side
import java.net.*;
class UdpServer {
public static void main(String[] args)
throws Exception {
DatagramSocket socket = new
DatagramSocket(3333);
byte[] receiveData = new byte[1024];
byte[] sendData;
System.out.println(“UDP Server is
running…”);
DatagramPacket receivePacket = new
DatagramPacket(receiveData, receiveData.length);
DatagramPacket sendPacket;
DatagramSocket clientSocket;
while (true) {
// Receive data from client
socket.receive(receivePacket);
String receivedMessage = new
String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println(“Client
says: ” + receivedMessage);
// Prepare response message
String responseMessage =
System.console().readLine();
sendData =
responseMessage.getBytes();
// Send data to client
InetAddress clientAddress =
receivePacket.getAddress();
int clientPort =
receivePacket.getPort();
sendPacket = new
DatagramPacket(sendData, sendData.length, clientAddress, clientPort);
socket.send(sendPacket);
if
(responseMessage.equals(“stop”)) {
break;
}
}
socket.close();
}
}
//udp client side
import java.net.*;
import java.io.*;
class UdpClient {
public static void main(String[] args)
throws Exception {
DatagramSocket socket = new
DatagramSocket();
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
InetAddress serverAddress =
InetAddress.getByName(“localhost”);
byte[] sendData;
byte[] receiveData = new byte[1024];
while (true) {
// Send message to server
String message = br.readLine();
sendData = message.getBytes();
DatagramPacket sendPacket = new
DatagramPacket(sendData, sendData.length, serverAddress, 3333);
socket.send(sendPacket);
if
(message.equals(“stop”)) {
break;
}
// Receive response from server
DatagramPacket receivePacket = new
DatagramPacket(receiveData, receiveData.length);
socket.receive(receivePacket);
String response = new
String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println(“Server
says: ” + response);
}
socket.close();
}
}
1. 9 Develop
a program for a simple RSA algorithm to encrypt and decrypt the data.
import
java.math.BigInteger;
import
java.security.SecureRandom;
import java.util.Scanner;
public class RSA {
private BigInteger p, q, N, phi, e, d;
private int bitLength = 1024;
private SecureRandom random = new
SecureRandom();
// Constructor to generate RSA keys
public RSA() {
// Generate two large primes p and q
p = BigInteger.probablePrime(bitLength
/ 2, random);
q = BigInteger.probablePrime(bitLength
/ 2, random);
// Compute N = p * q
N = p.multiply(q);
// Compute φ(N) = (p-1) * (q-1)
phi =
p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
// Choose e such that 1 < e <
φ(N) and gcd(e, φ(N)) = 1
e = BigInteger.probablePrime(bitLength
/ 4, random);
while
(phi.gcd(e).compareTo(BigInteger.ONE) > 0 && e.compareTo(phi) <
0) {
e = e.add(BigInteger.ONE);
}
// Compute d, the modular
multiplicative inverse of e mod φ(N)
d = e.modInverse(phi);
}
// Constructor to initialize RSA with given
keys
public RSA(BigInteger e, BigInteger d,
BigInteger N) {
this.e = e;
this.d = d;
this.N = N;
}
// Encrypt message
public byte[] encrypt(byte[] message) {
return (new
BigInteger(message)).modPow(e, N).toByteArray();
}
// Decrypt message
public byte[] decrypt(byte[]
encryptedMessage) {
return (new
BigInteger(encryptedMessage)).modPow(d, N).toByteArray();
}
// Convert byte array to a string
private static String bytesToString(byte[]
bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format(“%02X”, b));
}
return sb.toString();
}
// Main method for testing
public static void main(String[] args) {
try {
// Initialize RSA with key
generation
RSA rsa = new RSA();
// Input handling using Scanner
Scanner scanner = new
Scanner(System.in);
System.out.println(“Enter the
plain text:”);
String plainText =
scanner.nextLine();
System.out.println(“Original
Message: ” + plainText);
// Encrypt the message
byte[] encryptedMessage =
rsa.encrypt(plainText.getBytes());
System.out.println(“Encrypted
Message (in bytes): ” + bytesToString(encryptedMessage));
// Decrypt the message
byte[] decryptedMessage =
rsa.decrypt(encryptedMessage);
System.out.println(“Decrypted
Message: ” + new String(decryptedMessage));
} catch (Exception e) {
e.printStackTrace();
}
}
}
1. 10 Develop
a program for congestion control using a leaky bucket algorithm.
import java.util.Scanner;
public class LeakyBucket
{
public static void main(String[] args) {
// Create an instance of the Queue
(bucket)
Queue q = new Queue();
Scanner src = new Scanner(System.in);
System.out.println(“Enter the
number of packets to be sent:”);
int size = src.nextInt();
// Insert packets into the queue
q.insert(size);
// Simulate leaking/draining the queue
q.delete();
src.close();
}
}
// The Queue class
simulates the bucket behavior
class Queue {
private int[] q;
private int f = 0, r = 0, size = 10;
// Constructor to initialize the queue
(bucket)
public Queue() {
q = new int[size];
}
// Method to insert packets into the queue
public void insert(int n) {
Scanner in = new Scanner(System.in);
for (int i = 0; i < n; i++) {
System.out.print(“Enter
element ” + (i + 1) + “: “);
int ele = in.nextInt();
if (r >= size) {
System.out.println(“Queue
is full. Lost Packet: ” + ele);
} else {
q[r++] = ele;
}
}
in.close(); // Close scanner inside
insert method to avoid resource leak
}
// Method to drain (leak) packets from the
queue
public void delete() {
if (r == 0) {
System.out.println(“Queue
empty.”);
} else {
while (f < r) {
try {
Thread.sleep(1000); //
Simulate the constant leak rate
} catch (InterruptedException
e) {
e.printStackTrace();
}
System.out.println(“Leaked
Packet: ” + q[f++]);
}
// Reset after processing
f = r = 0;
}
}
}