CN Lab Manual PDF
CN Lab Manual PDF
PART-B
Java is a general-purpose computer programming language that is simple, concurrent,
class-based, object-oriented language. The compiled Java code can run on all platforms that
support Java without the need for recompilation hence Java is called as "write once, run
anywhere" (WORA). The Java compile::d intermediate output called "byte-code" that can run on
any Java virtual machine (JVM) regardless of computer architecture. The language derives
much of its syntax from C and C++, but it has fewer low-level facilities than either of them.
In Linux operating system Java libraries are preinstalled. It's very easy and convenient
to compile and run Java programs in Linux environment. To compile and run Java Program
is a two-step process:
The Java compiler (Javac) compiles java program and generates a byte-code
with the same file name and .class extension.
The java interpreter (Java) runs the byte-code and gives the respective output. It is
important to note that in above command we have omitted the .class suffix of the byte-
code (Filename.class).
The CRC does error checking via polynomial division. The generated polynomial g(x) =
X16-t-x lz+xS+xO
16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 I 0
I 0 0 0 l 0 0 0 0 0 0 1 0 0 0 0 I -+ 17 bits.
Algorithm:
1. Given a bit string (message to be sent), append 16 os to the end of it (th•~ number of OS is
the same as the d egree Of the generator polynomial) let this string + os be called as
modified string B .
· I g(x)
2. Divide B by agre~d on poIynom1a • and dt·termine
' the remainder R(x). The 16-btt
SOURCE CODE:
-
l8CSL57
class Crc
int[] data;
int[ ]div;
int[ ]divisor;
in t[ Jrem;
int[ ] ere;
int data_bits, divisor_bits, tot_length;
System.out.println("Enter number of data bits : ");
data_bits=lnteger.parselnt(br.readLine( ));
data=new int[data_bits];
System.out.println("Enter data bits:");
for(int i=0; i<data_bits; i++)
data[i]= Integer.parselnt(br.readLine( ) );
System.out.println("Enter number of bits in divisor : ");
divisor bits=Integer.parseh1t(br.readLine( ));
divisor=new int[ divisor_bits];
System.out.println("Enter Divisor bits : ");
for(int i=0; i<divisor_bits; i++)
divisor[ i]= Integer .parselnt(br.readLine());
tot_length=data_bits+divisor_ bits- l;
div=new int[tot_length];
rem=new int[tot_length];
crc=new int[tot_length];
ror(int i==0;i<data.length;i++)
18CSLS7
div[i]==data[i];
System.out.print("Dividend (after appending O's) are "); for(int i=0; i< div.length; i++)
· System.out.print(div[i]);
System.out.printlnO;
for(int j'=O; j<div .length; j++) {
remOJ == div[j];
}
System.out.println();
System.out.println("CRC code : ");
for(int i=0;i<crc.length;i++)
System.out.print(crc[i ]);
System.out.printlnO;
System.out.println("Enter CRC code of "+tot_length+" bits: ");
for(int i=0; i<crc.length; i++)
crc[iJ=Integer.parse/nt(br.readLineO);
for(int j=0; j<crc.length; j++){
remU] = crc[j];
}
if(rem[i]!=O)
System.out.println("Error'');
-
l8CSL57
break;
}
ifO = rem.length- I)
System.out.println(''No Error");
}
}
static int[] divide(int div[ ],int divisor[], int rem[])
{
int cur=O;
wbile(true)
for(int i=O;i<divisor.length;i++)
rem[cur+i]=(rem[cur+i]"divisor[i]);
cur++;
if((rem.length-cur)<divisor.length)
break;
return rem;
OUTPUT:
Enter number of data bits:
7
Enter data bits:
I
0
0
0
,I
Enter number of bits in divisor:
3
Enter divisor bits:
1
0
1
Divided (after appending O's) are: 101100100
CRC code:
101100111
Enter CRC code of 9 bits:
I
0
I
I
0
0
Error
COMPUTER NETWORK LABORATORY
-
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 up date by exchanging
information with the neighboring nod1~s.
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.
package bellmanford;
·jrnport java.util. *;
public class Bellmanford
{
static final int MAX=20;
static int A[ ][ ];
static int n;
public static void main(String[ J args) {
A=new int [MAX][MAX];
read_matrix( );
shortest( );
write();
}
static void shortest( )
{
for(int k= I ;k<=n;k++)
for(int i=l ;i<=n;i++)
for(int j= I ;j<=n;j++) {
if(A[i]U]> A[i] [k]+A[k][j])
A[i][j]=A[i][k]+A[k](j];
}
}
static void write( ){
System.out.println("\n the output matrix is: ");
for(int i= I ;i<=n;i++){
for(int j= I ;j<=n;j++) {
System.out.print(" "+A[i]U]);
}
System.out.println( );
COMPUTER NETWORK LABORATORY l8Cs1.5 7
' r~r:-,r:-"0.;~"
~-e~·,
:.:...:.x.,.re:.£ ,,..
[root@localhost ~}# javac BellmanFord.java
[root@localhost ~}# java BellmanFord
En t er the number of vertices
4
Enter the adjacency matrix
es ae
5 8 3 4
0 3 8 2
,e 4 2 e
·Enter the source vertex
2
distance of source 2 to 1 is S
·distance of source 2 to 2 is 8
distance of source 2 to 3 is 3
distance of source 2 to 4 is 4
[root@localhost ~]# 0
--
rHE CLIENT SEND THE FILE NAME AND TO MAKE THE SERVER SEND BACK
THE CONTENTS OF THE REQUESTED FILE IF PRESENT. IMPLEMENT THE
AHOVE PROGRAl\tl USING AS MESSAGE QUEUES OR FIFOS AS IPC
-
cHANNELS.
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 creatt:s 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.DatalnputStream;
impol'.t 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 DatalnputStream(s.getlnput:StreamO); ())·
DataOutputStream dout=new DataOutputStream(s.getOutputS~eam(S ' . ))·
BufferedReader br=new BufferedReader(new lnputStreamRea er ystem.m '
System.out.println("Send Get to start ... ");
String str="",filename="";
try
Page 51
18CSLS7
_c__MP
0
_UT_E:R~N;.:E~
TW~O:RK~LA~B:;o:RA~T~O:RY~ --iiiiiiiiiiiliiili-----·-·---·--·
{
while(!str.equals("start"))
str=br.readLine();
<lout. writeUTF(str);
'<lout.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: "+(s7/(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(h,0,h.length);
}while(!(bytesRead<l 024));
System.out.println("Comleted");
fos.closeQ;
<lout.close();
s.close();
}
catch(EOFException e)
{
//do nothing
}
}
}
TCP Server
import java.io.DatalnputStream; import java.io.DataOutputStream; import java.io.File;
import java.io.FilelnputStream; import java.net.ServerSocket; import java.n,et.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.closeQ; while(true)
{
//create server socket on port 5000 ServerSocket ss=new ServerSocket(S00O); System.out.println
("Waiting for request");
Socket s=ss.accept();
II&&;
Dept. ofISE, DSATM 2020-21
Page 52
col\lr vTER NETWORK LABORATORY 18CSL57
_ __
trY
{ tr-='" "·
strin~s - dUTF();
str:::d10 ·rea · In ("SendGet ....Ok")·,
out.pnnt
tJ:: equals("stop")){ System.out.println("Sending File: "+filename); dout.writeUTF(filename);
dout.flushO;
ile r-new File(filename);
;ileJnPutStream fin=new FilelnputStream(f);
ng sz:==(int) f.length{);
1
b~e bQ===new byte [ I 024];
int read; .
dout.writeUTF(Long.toStrmg(sz));
dout.flush();
System.out.pnn· ti n ("s·1ze: "+sz) ;
System.out.println ("Buf size: "+ss.getReceiveBufferSize());
while((read = fin.read(b)) != -1)
{
dout.write(b, 0, read);
dout.flushO;
}
fin.closeQ;
System.oiit.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.closeQ;
s.closeo;
ss.closeQ·
} ,
}
}
Note: Create two different files Client.java and Server.Java. Follow the steps given:
I. Open a terminal run the server program and provide the filename to send
z?>MPtrrQ NETWORK LABoRATORY
s l8Cst57
2. °"."n
one more terminal run the client program and provide the add~s of the serve,. W
can give localhost address " 127.o.o. I" as it is running on same maclune or give the JP address ,'
the machine. f
3. Send any start bit to start sending file.
4. Refer https://www.tutorialspointcom/java/java_ networking.htm for all the Panun«eo
methods description in socket communication. '
Output:
At server side:
, ii\'l.' '". '_'·i'.~·l;_'i\' •
:cl-~ ' '
(root@localhost
Enter File Naflle:
-J•
lroot@localhoat ~ J • J avac server.Java
java server
. 2-tempte. jpg
Waiting for request
·Connected With /127.e.e.1
SendGet •••• Ok
Sending File: 2-temp\e.jpg
Size: 19868
But s:1.2e: 431599
. , ok
Send Complete
o•1ting for request
At client side:
:r root @l·o
.(root@localhost -J# java client
Enter .S erver Address:
'127 .8.8.1
send Get to start ...
start
Receving file: 2-temple.jpg
Saving as file: client2•temple.jpg
File Size:
:Receving file..
Completed
8 MB
-t
[root@localhost -J• D
-~
package udps;
import java.uti I.Scanner;
import j ava.net. *;
. *·,
import java.10.
skt=new DatagramSocket(6788);
byte[] buffer=new byte[I000];
while(true)
catch(Exception ex)
{ }
}
}
UDP CLIENT
package udpc;
import java.util.Scanner;
import java.net. *;
import java.io. *;
public class UDPC
{
skt=new DatagrarnSocket( );
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[I 000];
Datagram Packet reply=new DatagramPacket(buffer,buffer.length);
skt.receive( reply);
System.out.println("Client receiv(:d: "+ new String(reply.getData( )));
skt.close( );
}
catch(Exception ex)
{ }
}
---
}
.
•ie and execute server side program
CoJJ1 P1
bhljtth@abhljlt~-HP-Pavtl~o~-.6-Notebook-PC:~$ ja
c DPSer er~java
bhljlth@abhljlth-HP-Pavtl~on- 6-Note ook-PC: - $ ja I. PServ r
ECEIVED: Hello ~erver ,
nter the Messagfl . . . .
ello Cl~e~t.. i .• . . .
Jbhljith@aoh~Jit~-HP-Pavtllon-~&-NotcbookHPC: SI
I /I
. '
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-fotward 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:
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 (q>) phi(n) = (p-l)(q-1).
Choose an integer e, l < e < phi, such that gcd(e, phi) = l.
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:
public RSA( )
{
r == new Random( );
P == Biglnteger.probablePrime(bitlength, r);
q === Biglnteger.probablePrime(bitlength, r);
N === p.multiply(q);
-
Phi == p.subtract(Biglnteger.ONE).multiply(q.subtract(Biglnteger.ONE));
e ::: Biglnteger.probablePrime(bitlength / 2, r);
t~
i ·pt, of ISE, DSATM - 2020-21 Page 59
1CO
~ MP
~ UT
~ E:R~N:E~TW
= O=RK
~ L~A~B~O;:
RA_:T
~O~R
:_Y
~_.iiiiiiaiiiiliiiiiiiiiaiiiiiiiiiiiiiiliiii_ _ _ _ _ _l._
8C~Sts
7
Ii '
d = e.modlnverse(phi);
}
test+== Byte.toString(b);
}
return test;
// Encrypt message
public byte[ Jencrypt(byte[ ] message)
{
return (new Biglnteger(message)).modPow(e, N).toByteArray( );
// Decrypt message
public byte[ ] decrypt(byte[ ] message)
{
return (new Biglnteger(message)).modPow(d, N).toByteArray( );
OUTPUT:
C:\Users\abhijith\Desktop>javac RSA.java
C:\Users\abhijith\Desktop>java RSA
Enter the plain text:
hi bangalore
Encrypting String: hi bangalore
5t ri ng in Bytes: 10410532989711010397108111114101
Decrypt i ng Bytes: 10410532989711010397108111114101
Decrypted String: hi bangalore
Page 61
COMPUTER NETWORK LABORATORY l8CSt57
be
1
I I In a . similar way if the bucket is empty the output will
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)).
~,
Hon
.C omput.er
• . . .Packet ·
Unregulated Flow '
a.
,..,.....,__..___--'--
.
Bucket Holds
~ c e .Containln(I
the leal<y bu~
·o · •-, .· pac'--s
{
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.
package leaky;
import java.io. *;
import java.util. *;
{
Queue q==new Queue( );
scanner src=new Scanner(System.in);
System.out.println("\nEnter the packets to be sent:"); _
int size==src.nextlnt( );
q.insert(size);
q.delete( );
}
}
class Queue
{
int q[ J,f=0,r=0,size;
void insert(int n)
int ele=in.nextlnt( );
if(r+l> IO)
COMPUTER NETWORK LABORATORY l8CSt57
break;
}
else
{
r++·
'
q[i]=ele; .J { l'O
}
}
}
L-- :
L__ J
>"'
System.out.println( );
}
}
-
OUTPUT:
Ente r 6 element: 4
Enter 7 element: 5
Enter- 8 element: 6
Enter 9 element: 2
Enter 1 0 element: 3
o ueue is full
Lost Pack et: 3
Leaked Packet: 2
Leaked Packet: 3
Leaked Packet: 5
Leaked Packet: 6
Leaked Pac ket: 8
) Leaked Packet: 9
i Leaked Packet: 4
I
'
18CSL57
COMPUTER NETWORK LABORATORY
Additional Programs
l. Simulate a four node point-to-point network and connect the links as follows: nO -n2, n I
- n2 and n2 - n3. Apply TCP agent between n0 - n3 and UDP~ I - n3. Apply relevant
applications over TCP and UDP agents changing the parameter and detertnine the
number of packets sent by TCP/ UDP.
2. Simulate an Ethernet LAN using N nodes (6-10). Change error rate and data rate and
compare throughput.
3. Implementation of creating links between the source and destination using both ftp and -.
tcp.
4. Write a java program for distance vector algorithm to find suitable path for transmission.
5. Implement the above program using as message queues or FIFOs as IPC channels using
java.
6. Write ajava program to demonstrate AES algorithm.
7. Write a java program to demonstrate different types of ciphers.
8. Write ajava program to demonstrate 32-bit CRC-CCIT algorithm.
9. Write ajava program to demonstrate Bellman ford algorithm with negative weights.
10. Write ajava program to demonstrate the Dijkstra's algorithm.
11. Write ajava program to demonstrate Diffie-Hellman algorithm.
12. Write a java program to demonstrate BGP protocol.