0% found this document useful (0 votes)
97 views

CNLAb Commands - Updated

The document provides instructions for installing and running ns-2 and nam network simulator software on Ubuntu. It includes steps to download nam software, remove any existing nam installation, run tcl simulation scripts, view output files in nam and awk, and run sample programs to simulate TCP, routing and wireless networks.

Uploaded by

Diwakar Karna
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
97 views

CNLAb Commands - Updated

The document provides instructions for installing and running ns-2 and nam network simulator software on Ubuntu. It includes steps to download nam software, remove any existing nam installation, run tcl simulation scripts, view output files in nam and awk, and run sample programs to simulate TCP, routing and wireless networks.

Uploaded by

Diwakar Karna
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 40

To install nam

knsit@dell-optiplex-3060:~$ ns lab11.tcl
knsit@dell-optiplex-3060:~$ nam out.nam
Segmentation fault (core dumped)

if this error comes then remove

sudo apt-get remove nam

then download the nam software from the below link

you tube :how to install ns2 and nam on ubuntu 16.04


chanel name :
knowledge kit

https://drive.google.com/file/d/1dkNPNN23Vy6o_zT0uIRBgUAo1VCXcVOY/view

copy that folder which you have downloaded to the desktop from downloads

nam_1.14_amd64.deb

open the folder and click on install button


once it is installed run the tcl file

Step 1:To create a tcl file

gedit lab11.tcl

Step 2:Run the TCL file

ns lab11.tcl

Step 3:To create awk file

gedit lab11.awk

Step 4:To run awk file

awk -f lab11.awk lab11.tr


program 1

gedit one.tcl

set ns [new Simulator]


set nf [open one.nam w]
set tf [open one.tr w]
$ns namtrace-all $nf
$ns trace-all $tf
proc finish {} {
global ns nf tf
$ns flush-trace
exec nam one.nam &
close $nf
close $tf
exit 0
}
set n0 [$ns node]
set n1 [$ns node]
set n [$ns node]
$ns duplex-link $n0 $n1 500Mb 10ms DropTail
$ns duplex-link $n1 $n 100Mb 5ms DropTail
$ns queue-limit $n0 $n1 10
$n0 label "UDP"
$n label "NULL"
set udp0 [new Agent/UDP]
$ns attach-agent $n0 $udp0
set null0 [new Agent/Null]
$ns attach-agent $n $null0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0
$ns connect $udp0 $null0
$ns at 0.1 "$cbr0 start"
$ns at 1.0 "finish"
$ns run

awk file

BEGIN{ c=0; }
{
If ($1== "d")
{
c++;
printf("%s\t%s\n",$5,$11);
}
}
END{printf("the total number of packets dropped due to congestion %d\n",c);
}

program 2

gedit lab12.tcl

set ns [new Simulator]


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

set nf [open lab12.nam w]


$ns namtrace-all $nf

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

set n0 [$ns node]


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

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


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

$ns queue-limit $n0 $n2 5


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

set ping0 [new Agent/Ping]


$ns attach-agent $n0 $ping0
set ping4 [new Agent/Ping]
$ns attach-agent $n4 $ping4

set ping5 [new Agent/Ping]


$ns attach-agent $n5 $ping5

set ping6 [new Agent/Ping]


$ns attach-agent $n6 $ping6

$ping0 set packetSize_ 50000Mb


$ping0 set interval_ 0.0001

$ping5 set packetSize_ 60000Mb


$ping5 set interval_ 0.00001

$ns connect $ping0 $ping4


$ns connect $ping5 $ping6

Agent/Ping instproc recv {from rtt} {


$self instvar node_
puts "The node [$node_ id] received a reply from $from with a roundtrip time of $rtt"
}

$ns rtmodel-at 0.9 down $n2 $n6


$ns rtmodel-at 1.5 up $n2 $n6

$ns at 0.1 "$ping0 send"


$ns at 0.2 "$ping0 send"
$ns at 0.3 "$ping0 send"
$ns at 0.4 "$ping0 send"
$ns at 0.5 "$ping0 send"
$ns at 0.6 "$ping0 send"
$ns at 0.7 "$ping0 send"
$ns at 0.8 "$ping0 send"
$ns at 0.9 "$ping0 send"
$ns at 1.0 "$ping0 send"
$ns at 1.1 "$ping0 send"
$ns at 1.2 "$ping0 send"
$ns at 1.3 "$ping0 send"
$ns at 1.4 "$ping0 send"
$ns at 1.5 "$ping0 send"
$ns at 1.6 "$ping0 send"
$ns at 1.7 "$ping0 send"
$ns at 1.8 "$ping0 send"
$ns at 0.1 "$ping5 send"
$ns at 0.2 "$ping5 send"
$ns at 0.3 "$ping5 send"
$ns at 0.4 "$ping5 send"
$ns at 0.5 "$ping5 send"
$ns at 0.6 "$ping5 send"
$ns at 0.7 "$ping5 send"
$ns at 0.8 "$ping5 send"
$ns at 0.9 "$ping5 send"
$ns at 1.0 "$ping5 send"
$ns at 1.1 "$ping5 send"
$ns at 1.2 "$ping5 send"
$ns at 1.3 "$ping5 send"
$ns at 1.4 "$ping5 send"
$ns at 1.5 "$ping5 send"
$ns at 1.6 "$ping5 send"
$ns at 1.7 "$ping5 send"
$ns at 1.8 "$ping5 send"

$ns at 5.0 "finish"

$ns run

awk file: gedit lab12.awk

BEGIN {
#include<stdio.h>
COUNT=0
}
{
if($1=="d")
count++
}
END {
printf("\nthe total number of packet dropped due to conjution %d\n",count);
}

Run
ns lab12.tcl
awk -f lab12.awk lab12.tr
output:

ns lab12.tcl

The node 0 received a reply from 4 with a roundtrip time of 1604.5


The node 0 received a reply from 4 with a roundtrip time of 1904.5
The node 0 received a reply from 4 with a roundtrip time of 2204.5
The node 5 received a reply from 6 with a roundtrip time of 1685.3
The node 0 received a reply from 4 with a roundtrip time of 2404.5
The node 0 received a reply from 4 with a roundtrip time of 2304.5
The node 5 received a reply from 6 with a roundtrip time of 2065.3
The node 0 received a reply from 4 with a roundtrip time of 2404.5
The node 5 received a reply from 6 with a roundtrip time of 2145.3
The node 0 received a reply from 4 with a roundtrip time of 2404.5
knsit@dell-optiplex-3060:~$ Nam syntax has changed: v -t 0.90000000000000002 link-down
0.90000000000000002 6 2
Please use this format in the future.
v -t <time> -e <tcl expression>

Nam syntax has changed: v -t 0.90000000000000002 link-down 0.90000000000000002 6 2


Please use this format in the future.
v -t <time> -e <tcl expression>

Nam syntax has changed: v -t 0.90000000000000002 link-down 0.90000000000000002 2 6


Please use this format in the future.
v -t <time> -e <tcl expression>

Nam syntax has changed: v -t 0.90000000000000002 link-down 0.90000000000000002 2 6


Please use this format in the future.
v -t <time> -e <tcl expression>

Nam syntax has changed: v -t 1.5 link-up 1.5 6 2


Please use this format in the future.
v -t <time> -e <tcl expression>

Nam syntax has changed: v -t 1.5 link-up 1.5 6 2


Please use this format in the future.
v -t <time> -e <tcl expression>

Nam syntax has changed: v -t 1.5 link-up 1.5 2 6


Please use this format in the future.
v -t <time> -e <tcl expression>

Nam syntax has changed: v -t 1.5 link-up 1.5 2 6


Please use this format in the future.
v -t <time> -e <tcl expression>

knsit@dell-optiplex-3060:~$ awk -f lab12.awk lab12.tr

the total number of packet dropped due to conjution 20


program3

set ns [new Simulator]


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

set nf [open lab13.nam w]


$ns namtrace-all $nf

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

set n0 [$ns node]


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

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

set tcp0 [new Agent/TCP]


$ns attach-agent $n0 $tcp0

set ftp0 [new Application/FTP]


$ftp0 attach-agent $tcp0

set sink3 [new Agent/TCPSink]


$ns attach-agent $n3 $sink3

$ns connect $tcp0 $sink3

set tcp2 [new Agent/TCP]


$ns attach-agent $n2 $tcp2
set ftp2 [new Application/FTP]
$ftp2 attach-agent $tcp2

set sink2 [new Agent/TCPSink]


$ns attach-agent $n1 $sink2

$ns connect $tcp2 $sink2

set file1 [open file1.tr w]


$tcp0 attach $file1

$tcp0 trace cwnd_


$tcp0 set maxcwnd_ 10

set file2 [open file2.tr w]


$tcp2 attach $file2

$tcp2 trace cwnd_

$ns at 0.1 "$ftp0 start"


$ns at 1.5 "$ftp0 stop"

$ns at 2 "$ftp0 start"


$ns at 1.5 "$ftp0 stop"

$ns at 0.2 "$ftp2 start"


$ns at 2 "$ftp2 stop"

$ns at 2.5 "$ftp2 start"


$ns at 4 "$ftp2 stop"

$ns at 5.0 "finish"

$ns color 1 "red"


$ns color 2 "blue"

$ns run

AWK file

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

commands to Run

gedit lab13.awk
knsit@dell-optiplex-3060:~$ ns lab13.tcl
warning: no class variable LanRouter::debug_

see tcl-object.tcl in tclcl for info about this warning.

knsit@dell-optiplex-3060:~$ awk -f lab13.awk file1.tr>tcp1


knsit@dell-optiplex-3060:~$ awk -f lab13.awk file2.tr>tcp2
knsit@dell-optiplex-3060:~$ xgraph tcp1 tcp2
Parameter LabelFont: can't translate `helvetica-10' into a font (defaulting to `fixed')
Parameter TitleFont: can't translate `helvetica-18' into a font (defaulting to `fixed')
graph without congestion

remove this line from tcl file and note the graph without congestion

$tcp0 set maxcwnd_ 10


program 4

set ns [new Simulator]


set tf [open lab4.tr w]
$ns trace-all $tf
set topo [new Topography]
$topo load_flatgrid 1000 1000
set nf [open lab4.nam w]
$ns namtrace-all-wireless $nf 1000 1000

$ns node-config -adhocRouting DSDV \


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

create-god 3
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]

$n0 label "tcp0"


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

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

$n1 set X_ 100


$n1 set Y_ 100
$n1 set Z_ 0

$n2 set X_ 600


$n2 set Y_ 600
$n2 set Z_ 0

$ns at 0.1 "$n0 setdest 50 50 15"


$ns at 0.1 "$n1 setdest 100 100 25"
$ns at 0.1 "$n2 setdest 600 600 25"

set tcp0 [new Agent/TCP]


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

set tcp1 [new Agent/TCP]


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

$ns at 5 "$ftp0 start"


$ns at 5 "$ftp1 start"

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


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

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

$ns at 250 "finish"


$ns run

awk file

BEGIN {
c1 = 0;
c2 = 0;
p1 = 0;
p2 = 0;
t1 = 0;
t2 = 0;
}

{
if ($1 == "r" && $3 == "_1_" && $4 == "AGT") {
c1++;
p1 += $8;
t1 = $2;
}

if ($1 == "r" && $3 == "_2_" && $4 == "AGT") {


c2++;
p2 += $8;
t2 = $2;
}
}

END {
printf("The throughput from n0 to n1 is %f Mbps\n", (c1 * p1 * 8) / (t1 * 1000000));
printf("The throughput from n1 to n2 is %f Mbps\n", (c2 * p2 * 8) / (t2 * 1000000));
}
outpur

knsit@dell-optiplex-3060:~$ ns lab4.tcl
warning: Please use -channel as shown in tcl/ex/wireless-mitf.tcl
num_nodes is set 3
INITIALIZE THE LIST xListHead
channel.cc:sendUp - Calc highestAntennaZ_ and distCST_
highestAntennaZ_ = 1.5, distCST_ = 550.0
SORTING LISTS ...DONE!
knsit@dell-optiplex-3060:~$ gedit lab4.awk
knsit@dell-optiplex-3060:~$ awk -f lab4.awk lab4.tr
The throughput from n0 to n1 is 5863.442245 Mbps
The throughput from n1 to n2 is 1307.611834 Mbps
knsit@dell-optiplex-3060:~$ gedit lab4.tcl
PART B
12.Write a program for congestion control using leaky bucket algorithm.

The main concept of the leaky bucket algorithm is that the output data flow remains constant
despite the variant input traffic, such as the water flow in a bucket with a small hole at the bottom.
In case the bucket contains water (or packets) then the output flow follows a constant rate, while if
the bucket is full any additional load will be lost because of spillover. In a similar way if the bucket
is empty the output will be zero. From network perspective, leaky bucket consists of a finite queue
(bucket) where all the incoming packets are stored in case there is space in the queue, otherwise
the packets are discarded. In order to regulate the output flow, leaky bucket transmits one packet
from the queue in a fixed time (e.g. at every clock tick). In the following figure we can notice the
main rationale of leaky bucket algorithm, for both the two approaches (e.g. leaky bucket with
water (a) and with packets (b)).

While leaky bucket eliminates completely bursty traffic by regulating the incoming data flow its
main drawback is that it drops packets if the bucket is full. Also, it doesn’t take into account the
idle process of the sender which means that if the host doesn’t transmit data for some time the
bucket becomes empty without permitting the transmission of any packet.

import java.util.*;

public class Bucket {

static void solution(int pktsize, int output) {

int buketsize = 512;

if (pktsize > buketsize) {

System.out.println("Bucket overflow");

} else {

while (pktsize > output) {

System.out.println(output + "bytes outputed");

pktsize = pktsize - output;


}

if (pktsize > 0) {

System.out.println(pktsize + "bytes outputed");

public static void main(String[] args) {

int output, pktsize, n;

Scanner read = new Scanner(System.in);

Random rand = new Random();

System.out.println("Enter output rate");

output = read.nextInt();

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

n = read.nextInt();

for (int i = 1; i <= n; i++) {

pktsize = rand.nextInt(1000);

System.out.println("packetno: " + i + " packetsize=" + pktsize);

solution(pktsize, output);

}
commands to Run

knsit@dell-optiplex-3060:~$ gedit Bucket.java


knsit@dell-optiplex-3060:~$ javac Bucket.java
knsit@dell-optiplex-3060:~$ java Bucket

java Bucket
Enter output rate
100
Enter the number of packets
5
packetno: 1 packetsize=735
Bucket overflow
packetno: 2 packetsize=39
39bytes outputed
packetno: 3 packetsize=772
Bucket overflow
packetno: 4 packetsize=965
Bucket overflow
packetno: 5 packetsize=102
100bytes outputed
2bytes outputed
program 11

11.WRITE A PROGRAM FOR SIMPLE RSA ALGORITHM TO ENCRYPT AND DECRYPT THE
DATA.

RSA is an example of public key cryptography. It was developed by Rivest, Shamir and Adelman.
The RSA algorithm can be used for both public key encryption and digital signatures. Its security
is based on the difficulty of factoring large integers.
The RSA algorithm's efficiency requires a fast method for performing the modular exponentiation
operation. A less efficient, conventional method includes raising a number (the input) to a power
(the secret or public key of the algorithm, denoted e and d, respectively) and taking the remainder
of the division with N. A straight-forward implementation performs these two steps of the operation
sequentially: first, raise it to the power and second, apply modulo. The RSA algorithm comprises
of three steps, which are depicted below:
Key Generation Algorithm:
Ø Generate two large random primes, p and q, of approximately equal size such that their product
n = p*q
Ø Compute n = p*q and Euler‟s totient function (φ) phi(n) = (p-1)(q-1).
Ø Choose an integer e, 1 < e < phi, such that gcd(e, phi) = 1.
Ø Compute the secret exponent d, 1 < d < phi, such that e*d ≡ 1 (mod phi).
Ø The public key is (e, n) and the private key is (d, n). The values of p, q, and phi should also be
kept secret.

Encryption:
Sender A does the following:
Ø Using the public key (e,n)
Ø Represents the plaintext message as a positive integer M
Ø Computes the cipher text C = M^e mod n.
Ø Sends the cipher text C to B (Receiver).

Decryption:
Recipient B does the following:
Ø Uses his private key (d, n) to compute M = C^d mod n.
Ø Extracts the plaintext from the integer representative m.

import java.math.BigInteger;

import java.util.Random;

import java.util.Scanner;
public class RSA {

public static void main(String[] args) {

// Each public and private key consists of an exponent and a modulus

BigInteger n; // n is the modulus for both the private and public keys

BigInteger e; // e is the exponent of the public key

BigInteger d; // d is the exponent of the private key

int bitlength = 512;

Random r = new Random();

// Step 1: Generate two large random primes.

// We use 512 bits here, but best practice for security is 2048 bits.

// Change 512 to 2048, recompile, and run the program again and you will

// notice it takes much longer to do the math with that many bits.

BigInteger p = BigInteger.probablePrime(bitlength, r);

BigInteger q = BigInteger.probablePrime(bitlength, r);


// Step 2: Compute n by the equation n = p * q.

n = p.multiply(q);

// Step 3: Compute phi(n) = (p-1) * (q-1)

BigInteger phi = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));

// Step 4: Select a small odd integer e that is relatively prime to phi(n).

// By convention the prime 65537 is used as the public exponent.

e = new BigInteger("65537");

// Step 5: Compute d as the multiplicative inverse of e modulo phi(n).

d = e.modInverse(phi);

Scanner in = new Scanner(System.in);

String s;

// Enter a simple message to be Encrypted

System.out.println("Enter the plain text:");

s = in.nextLine();
//m is the byte representation of the message to be encrypted

BigInteger m = new BigInteger(s.getBytes());

// Step 8: To encrypt a message m compute c = m^e (mod n)

BigInteger c = m.modPow(e, n);

// Step 9: To decrypt a message c compute m = c^d (mod n)

BigInteger decrypt = c.modPow(d, n);

String decryptedText = new String(decrypt.toByteArray()); // Decode to a string

//Display encrypted and Decrypted Text

System.out.println("Encrypted text = " + c);

System.out.println("Decrypted text = " + decryptedText);

commands to run

knsit@dell-optiplex-3060:~$ gedit RSA.java


knsit@dell-optiplex-3060:~$ javac RSA.java
knsit@dell-optiplex-3060:~$ java RSA
output:

knsit@dell-optiplex-3060:~$ gedit RSA.java


knsit@dell-optiplex-3060:~$ java RSA
Enter the plain text:
india
Encrypted text =
90765458091061618858107123014993377091074765725522294476746629635459030903301696696
25676287080375585393634784879215386481620246645340956501102606907494818054389372909
39387962912352445153014660963533216735181673922050217799076733435976806475540110446
39443354526111706852610422116848972713852393708188665910489
Decrypted text = india

Program 8: 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, t
he 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 up date by exchanging  information with the neighborin
g nodes. The number of data in the table equals to that of all  nodes  in  networks  (excluded  itself).  Th
e  columns  of  table  represent  the  directly  attached  neighbors whereas the rows represent all destinati
ons 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 algorith
m 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 th
e same problem, but more versatile, as it is capable of handling graphs in which  some of the edge weig
hts are negative numbers. Negative edge weights are found in various  applications of graphs, hence th
e 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.
import java.util.Scanner;

public class BellmanFord {

public static void main(String[] args) {


int MAX_VALUE = 999;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of vertices");
int num_ver = scan.nextInt();
int A[][] = new int[num_ver + 1][num_ver + 1];
System.out.println("Enter the cost adjacency matrix, 0 for self loop, 999 for no edge");
for (int sn = 1; sn <= num_ver; sn++) {
for (int dn = 1; dn <= num_ver; dn++) {
A[sn][dn] = scan.nextInt();
}
}
System.out.println("Enter the source vertex");
int source = scan.nextInt();

/*Create Distance Matrix D and initialize it*/


int D[] = new int[num_ver + 1];
for (int node = 1; node <= num_ver; node++) {
D[node] = MAX_VALUE;
}
D[source] = 0;
/*Relaxation of edges n-1 times*/
for (int i = 1; i < num_ver; i++) {
for (int sn = 1; sn <= num_ver; sn++) {
for (int dn = 1; dn <= num_ver; dn++) {
if (D[dn] > D[sn] + A[sn][dn]) {
D[dn] = D[sn] + A[sn][dn];
}
}
}
}
/*To check for negative weight cycle*/
for (int sn = 1; sn <= num_ver; sn++) {
for (int dn = 1; dn <= num_ver; dn++) {

if (D[dn] > D[sn] + A[sn][dn]) {


System.out.println("The Graph contains negative edge cycle");
return;
}

}
}
for (int vertex = 1; vertex <= num_ver; vertex++) {
System.out.println("distance of source " + source + " to " + vertex + " is " + D[vertex]);
}
}

commands to Run:
knsit@dell-optiplex-3060:~$ gedit BellmanFord.java
knsit@dell-optiplex-3060:~$ javac BellmanFord.java
knsit@dell-optiplex-3060:~$ java BellmanFord
OUTPUT 1:
Enter the number of vertices
4
Enter the cost adjacency matrix, 0 for self loop, 999 for no edge
0 4 999 5
999 0 999 5
999 -10 0 999
999 999 3 0
Enter the source vertex
1
The Graph contains negative edge cycle

output 2:
knsit@dell-optiplex-3060:~$ java BellmanFord
Enter the number of vertices
4
Enter the cost adjacency matrix, 0 for self loop, 999 for no edge
0 4 999 5
999 0 999 999
999 -10 0 999
999 999 3 0
Enter the source vertex
1
distance of source 1 to 1 is 0
distance of source 1 to 2 is -2
distance of source 1 to 3 is 8
distance of source 1 to 4 is 5
OUTPUT 3:

knsit@dell-optiplex-3060:~$ java BellmanFord


Enter the number of vertices
6
Enter the cost adjacency matrix, 0 for self loop, 999 for no edge
0 2 999 999 4 999

2 0 3 999 1 5

999 3 0 4 999 2

999 999 4 0 999 3

4 1 999 999 0 1

999 5 2 3 1 0
Enter the source vertex
1
distance of source 1 to 1 is 0
distance of source 1 to 2 is 2
distance of source 1 to 3 is 5
distance of source 1 to 4 is 7Distance 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 algorithm
distance of source 1 to 5 is 3
distance of source 1 to 6 is 4

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

Server file

import java.util.Scanner;

import java.net.*;

import java.io.*;

public class Udps {

public static void main(String[] args) {

DatagramSocket skt = null;

String ch;

Scanner input = new Scanner(System.in);

try {

skt = new DatagramSocket(2222);

System.out.println("Server Started!!");

byte[] buffer = new byte[1000];


while (true) {

DatagramPacket request = new DatagramPacket(buffer, buffer.length);

skt.receive(request);

System.out.print("enter the Message: ");

ch = input.nextLine();

byte[] sendMsg = (ch + " -> server processed").getBytes();


DatagramPacket reply = new DatagramPacket(sendMsg, sendMsg.length,
request.getAddress(), request.getPort());

skt.send(reply);
skt.close();

} catch (Exception ex) {

Client file

import java.util.Scanner;

import java.net.*;

import java.io.*;

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 = 2222;

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) {

Commands to run

open two terminala

first terminal

Step 1:javac Udps.java

second terminal

Step 2:javac Udpc.java

first terminal

java Udps

second terminal

java Udpc

output will be displayed as in first terminal:


Server Started!!
enter the Message:
Step 4: enter your message in server terminal

and the message will be displayed in client terminal


9. Using TCP/IP sockets, write a client – server program to make the client send the file
name to make the server send back the contents of the requested file if present.
Implement the above program using as message queues or FIFOs as IPC channels.

Server file

import java.net.*;

import java.io.*;

public class Server {

public static void main(String[] args)throws IOException {

try

//The server creates a ServerSocket object, denoting which port number


communication is to occur on.

ServerSocket sersock=new ServerSocket(3000);

System.out.println("server ready for connection");

/*The server invokes the accept() method of the ServerSocket class. This method
waits until a client connects to the server on the given port.*/

Socket sock=sersock.accept();

System.out.println("connection established waiting for chatting");

// 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

// closing network sockets

sock.close();

sersock.close();

pwrite.close();

fileRead.close();

catch(Exception e)

System.out.println("an error occured while opening");

}
Client Server:

import java.net.*;

import java.io.*;

public class Client {

public static void main(String[] args)throws Exception {

//client creates a Socket object, specifying the server name and the port number to
connect to.

Socket sock=new Socket("127.0.0.1",3000);

System.out.println("enter file name");

/*reading from keyboard (keyRead object)using input stream connecting the


BufferedReader stream with the InputStreamReader stream for reading the line by line data
from the keyboard.*/

//or as commented below use scanner object

BufferedReader keyread=new BufferedReader(new InputStreamReader(System.in));

String fname=keyread.readLine();

try{

// sending the file name to server. Uses PrintWriter

/*getOutputStream(). This method returns an OutputStream where the data can be


written and throws the appropriate exception if it cannot do so.*/

OutputStream ostream=sock.getOutputStream();

PrintWriter pwrite=new PrintWriter(ostream,true);

pwrite.println(fname);

// receiving the contents from server. Uses input stream


/*This method returns an InputStream representing the data and throws the
appropriate exception if it cannot do so.*/

InputStream istream=sock.getInputStream();

BufferedReader socketRead=new BufferedReader(new InputStreamReader(istream));

String str;

// reading line-by-line

while((str=socketRead.readLine())!=null)

System.out.println(str);

// closing network sockets

pwrite.close(); socketRead.close(); keyread.close();

catch(Exception e)

System.out.println("an error occured while opening");

Output:

open 2 terminal

first terminal: javac Server.java


second terminal : javac Client.java
first terminal: java Server
second terminal: java Client

type any file name which is in that directory /.java or text file etc
client will display the content of the file
1. Write a program for error detecting code using CRC-CCITT (16-bits).

import java.io.*;
class Crc
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int[ ] data;
int[ ]div;
int[ ]divisor;
int[ ]rem;
int[ ] crc;
int data_bits, divisor_bits, tot_length;
System.out.println("Enter number of data bits : ");
data_bits=Integer.parseInt(br.readLine());
data=new int[data_bits];
System.out.println("Enter data bits : ");
for(int i=0; i<data_bits; i++)
data[i]=Integer.parseInt(br.readLine());
System.out.println("Enter number of bits in divisor : ");
divisor_bits=Integer.parseInt(br.readLine());
divisor=new int[divisor_bits];
System.out.println("Enter Divisor bits : ");
for(int i=0; i<divisor_bits; i++)
divisor[i]=Integer.parseInt(br.readLine());
tot_length=data_bits+divisor_bits-1;
div=new int[tot_length];
rem=new int[tot_length];
crc=new int[tot_length];
/*------------------ CRC GENERATION-----------------------*/
for(int i=0;i<data.length;i++)
div[i]=data[i];
System.out.print("Dividend (after appending 0's) are : ");
for(int i=0; i< div.length; i++) System.out.print(div[i]);
System.out.println();
for(int j=0; j<div.length; j++)
{
rem[j] = div[j];
}
rem=divide(div, divisor, rem);
for(int i=0;i<div.length;i++) //append dividend and ramainder
{
crc[i]=(div[i]^rem[i]);
}
System.out.println();
System.out.println("CRC code : ");
for(int i=0;i<crc.length;i++)
System.out.print(crc[i]);
/*-------------------ERROR DETECTION---------------------*/
System.out.println();
System.out.println("Enter CRC code of "+tot_length+" bits : ");
for(int i=0; i<crc.length; i++)
crc[i]=Integer.parseInt(br.readLine());

for(int j=0; j<crc.length; j++)


{
rem[j] = crc[j];
}
rem=divide(crc, divisor, rem);
for(int i=0; i< rem.length; i++)
{
if(rem[i]!=0)
{
System.out.println("Error");
break;
}
if(i==rem.length-1)
System.out.println("No Error");
}
System.out.println("THANK YOU.... :)");
}
static int[] divide(int div[],int divisor[], int rem[])
{
int cur=0;
while(true)
{
for(int i=0;i<divisor.length;i++)
rem[cur+i]=(rem[cur+i]^divisor[i]);
while(rem[cur]==0 && cur!=rem.length-1)
cur++;
if((rem.length-cur)<divisor.length)
break;
}
return rem;
}
}

output:

You might also like