0% found this document useful (0 votes)
5 views20 pages

Assignment Java Programs

The document outlines various experiments conducted in a Computer Networks Laboratory, including programs for error detection using CRC-CCITT, shortest path calculation using the Bellman-Ford algorithm, and client-server communication using TCP/IP and datagram sockets. Each experiment includes theoretical background, algorithms, and sample Java code for implementation. The document serves as a practical guide for students to understand and apply networking concepts through programming.

Uploaded by

eng22cs0424
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views20 pages

Assignment Java Programs

The document outlines various experiments conducted in a Computer Networks Laboratory, including programs for error detection using CRC-CCITT, shortest path calculation using the Bellman-Ford algorithm, and client-server communication using TCP/IP and datagram sockets. Each experiment includes theoretical background, algorithms, and sample Java code for implementation. The document serves as a practical guide for students to understand and apply networking concepts through programming.

Uploaded by

eng22cs0424
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

15CSL57 COMPUTER NETWORKS LABORATORY 2017-18

Experiment 7: CRC-CCITT

Aim: To write a program for error detecting code using CRC-CCITT (16 bits).

Theory

CRC(Cyclic Redundancy Check) is an error detecting technique used in digital networks and storage
devices to detect the accidental changes to raw data. It cannot be used for correcting errors.

If an error is detected in the received message, a „Negative acknowledgement‟ is sent to the


sender. The sender and the receiver agree upon a fixed polynomial called generator polynomial. The
standard agreed generator polynomial is x16+x12+x5+x0 (any polynomial can be considered, of degree
16).

The CRC does error checking via polynomial division. The generated polynomial g(x) =
x +x +x5+x0
16 12

16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
1 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 1 17 bits.

So the g(x) value is 10001000000100001

Algorithm:

1. Given a bit string (message to be sent), append 16 0S to the end of it (the number of 0s is the
same as the degree of the generator polynomial) let this string + 0S be called as modified string
B
2. Divide B by agreed on polynomial g(x) and determine the remainder R(x). The 16-bit
remainder received is called as checksum.
3. The message string is appended with checksum and sent to the receiver.
4. At the receiver side, the received message is divided by generator polynomial g(x).
5. If the remainder is 0, the receiver concludes that there is no error occurred otherwise, the
receiver concludes an error occurred and requires a retransmission.
Program:

import java.util.*;
public class crc {

public static void main(String args[]){


Scanner s=new Scanner(System.in);

Dept of ISE MIT, Mysore Page 43


15CSL57 COMPUTER NETWORKS LABORATORY 2017-18

int n;
System.out.println("enter the size of the data:");
n=s.nextInt();
int data[]=new int[n];
System.out.println("enter the data ,bit by bit:");
for(int i=0; i < n; i++){
data[i]=s.nextInt();
}
System.out.println("enter ther size of the divisor:");
n=s.nextInt();
int divisor[]=new int[n];
System.out.println("enter the divisor,bit by bit:");
for(int i=0; i < n; i++)
divisor[i]=s.nextInt();
int remainder[]=divide(data,divisor);
System.out.println("\n the 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++)
sent_data[i]=s.nextInt();
recieve(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);
System.out.println("message bits after appending divisor_length-1 0's:");
for(i=0; i<data.length-1; i++)
System.out.println(data[i]);
remainder=new int[divisor.length];
System.arraycopy(data, 0, remainder, 0, divisor.length);
for(i=0; i < old_data.length; i++){
if(remainder[0]==1){
for(int j=1; j<divisor.length; j++){
remainder[j-1]=exor(remainder[j],divisor[j]);

Dept of ISE MIT, Mysore Page 44


15CSL57 COMPUTER NETWORKS LABORATORY 2017-18

}
}
else{
for(int j=1; j < divisor.length; j++)
remainder[j-1]=exor(remainder[j],0);
}

remainder[divisor.length-1]=data[i+divisor.length];
}
return remainder;
}
static int exor(int a,int b){
if(a==b)
return 0;
return 1;
}
static void recieve(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 recieved data...");
return;
}
}
System.out.println("data was recieved without any error");

}
}

Dept of ISE MIT, Mysore Page 45


15CSL57 COMPUTER NETWORKS LABORATORY 2017-18

Dept of ISE MIT, Mysore Page 46


15CSL57 COMPUTER NETWORKS LABORATORY 2017-18

Experiment 8: BELLMAN-FORD

Aim:To write a program to find the shortest path between vertices using bellman-ford algorithm.

Theory
Routing algorithm is a part of network layer software which is responsible for deciding which output line an
incoming packet should be transmitted on. If the subnet uses datagram internally, this decision must be made
anew for every arriving data packet since the best route may have changed since last time. If the subnet uses
virtual circuits (connection Oriented), routing decisions are made only when a new established route is being set
up.

Routing algorithms can be grouped into two major classes: adaptive and nonadaptive. Nonadaptive
algorithms do not base their routing decisions on measurement or estimates of current traffic and topology.
Instead, the choice of route to use to get from I to J (for all I and J) is compute in advance, offline, and
downloaded to the routers when the network ids booted. This procedure is sometime called static routing.

Adaptive algorithms, in contrast, change their routing decisions to reflect changes in the topology, and
usually the traffic as well. Adaptive algorithms differ in where they get information (e.g., locally, from adjacent
routers, or from all routers), when they change the routes (e.g., every ∆T sec, when the load changes, or when
the topology changes), and what metric is used for optimization (e.g., distance, number of hops, or estimated
transit time).

Two algorithms in particular, distance vector routing and link state routing are the most popular. Distance
vector routing algorithms operate by having each router maintain a table (i.e., vector) giving the best known
distance to each destination and which line to get there. These tables are updated by exchanging information
with the neighbors.

The distance vector routing algorithm uses Bellman-Ford routing algorithm and Ford-Fulkerson algorithm.
In distance vector routing, each router maintains a routing table that contains two parts: the preferred out going
line to use for that destination, and an estimate of the time or distance to that destination. The metric used might
be number of hops, time delay in milliseconds, total number of packets queued along the path, or something
similar.

The Routing tables are shared among the neighbors, and the tables at the router are updated, such that the
router will know the shortest path to the destination.

Program:

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;

Dept of ISE MIT, Mysore Page 47


15CSL57 COMPUTER NETWORKS LABORATORY 2017-18

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; node++){
for(int sn=1; sn <= num_ver; sn++){
for(int dn=1; dn <= num_ver; dn++){
if(a[sn][dn] < 0)
D[dn]=0;
else{
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 edge
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,source;

Dept of ISE MIT, Mysore Page 48


15CSL57 COMPUTER NETWORKS LABORATORY 2017-18

Scanner s=new Scanner(System.in);


System.out.println("enter the number of vertex");
num_ver=s.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]=s.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=s.nextInt();
BellmanFord b = new BellmanFord(num_ver);
b.BellmanFordEvaluation(source, a);
s.close();

}
Input graph:

5
A B

3
4

C D
2

Output:

Dept of ISE MIT, Mysore Page 49


15CSL57 COMPUTER NETWORKS LABORATORY 2017-18

[root@localhost ~]# vi BellmanFord.java

Experiment 9: TCP/IP SOCKET FOR CLIENT-SERVER COMMUNICATION

Dept of ISE MIT, Mysore Page 50


15CSL57 COMPUTER NETWORKS LABORATORY 2017-18

Aim: 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. Implement the above
program using as message queues or FIFOs as IPC channels.

Theory:

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,
theservercreatesasocketobjectonitsendofthecommunication.Theclientandthe server can now
communicate by writing to and reading from the socket.

Procedure:

/*TCP Server program*/

Dept of ISE MIT, Mysore Page 51


15CSL57 COMPUTER NETWORKS LABORATORY 2017-18

import java.net.*;
import java.io.*;

public class tcpser {


public static void main(String args[])throws Exception
{
ServerSocket sersock= new ServerSocket(4000);
System.out.println("sever ready for connection");
Socket sock=sersock.accept();
System.out.println("connection is successfull and waiting to serve");
InputStream istream=sock.getInputStream();
BufferedReader fileRead=new BufferedReader(newInputStreamReader(istream));
String fname=fileRead.readLine();
BufferedReader contentRead=new BufferedReader(new FileReader(fname));
OutputStream ostream=sock.getOutputStream();
PrintWriter pwrite=new PrintWriter(ostream,true);
String str;
while((str=contentRead.readLine())!=null)
{
pwrite.println(str);
}
}

/*TCP Client program*/

import java.net.*;
import java.io.*;

public class tcpcln {


public static void main(String args[])throws Exception
{
Socket sock=new Socket("127.0.0.1",4000);
System.out.println("enter the file name");
BufferedReader keyRead=new BufferedReader(new InputStreamReader(System.in));
String fname=keyRead.readLine();
OutputStream ostream=sock.getOutputStream();
PrintWriter pwrite=new PrintWriter(ostream,true);
pwrite.println(fname);
InputStream istream=sock.getInputStream();
BufferedReader SocketRead=new BufferedReader(new InputStreamReader(istream));
String str;
while((str=SocketRead.readLine())!=null)
{

Dept of ISE MIT, Mysore Page 52


15CSL57 COMPUTER NETWORKS LABORATORY 2017-18

System.out.println(str);
pwrite.close();
SocketRead.close();
keyRead.close();
}
}
}

OUTPUT:
Create a text file say abc.txt and type some content in it.
Compile and execute server side program

Open new terminal, compile and execute client side program

Experiment 10: DATAGRAM SOCKET FOR CLIENT SERVER COMMUNICATION

Dept of ISE MIT, Mysore Page 53


15CSL57 COMPUTER NETWORKS LABORATORY 2017-18

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

Theory

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.

Procedure:

/*UDP Server program*/

import java.io.*;
import java.net.*;
import java.net.*;
class udpser {
public static void main(String args[]) throws Exception
{

Dept of ISE MIT, Mysore Page 54


15CSL57 COMPUTER NETWORKS LABORATORY 2017-18

DatagramSocket serversocket=new DatagramSocket(9876);


BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
byte[] receiveData=new byte[1024];
byte[] sendData=new byte[1024];
DatagramPacket receivePacket=new DatagramPacket(receiveData,receiveData.length);
serversocket.receive(receivePacket);
String sentence=new String(receivePacket.getData());
System.out.println("RECEIVED:"+sentence);
InetAddress IPaddress=receivePacket.getAddress();
int port=receivePacket.getPort();
System.out.println("enter the message");
String data=br.readLine();
sendData=data.getBytes();
DatagramPacket sendPacket=new DatagramPacket(sendData,sendData.length,IPaddress,port);
serversocket.send(sendPacket);
serversocket.close();

/*UDP Client program*/

import java.io.*;
import java.net.*;
class udpcl {
public static void main(String[]args) throws Exception
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientsocket=new DatagramSocket();
InetAddress IPaddress=InetAddress.getByName("localhost");
byte[] sendData=new byte[1024];
byte[] receiveData=new byte[1024];
String sentence="hello server";
sendData=sentence.getBytes();
DatagramPacket sendPacket=new DatagramPacket(sendData,sendData.length,IPaddress,9876);
clientsocket.send(sendPacket);
DatagramPacket receivePacket=new DatagramPacket(receiveData,receiveData.length);
clientsocket.receive(receivePacket);
String modifiedsentence=new String(receivePacket.getData());
System.out.println("FROM SERVER:" +modifiedsentence);
clientsocket.close();
}
}

Dept of ISE MIT, Mysore Page 55


15CSL57 COMPUTER NETWORKS LABORATORY 2017-18

OUTPUT
Compile and execute server side program

Open new terminal, compile and execute client side program

Experiment 11: RSA

Aim: To write a program for simple RSA algorithm to encrypt and decrypt the data.

Theory

Dept of ISE MIT, Mysore Page 56


15CSL57 COMPUTER NETWORKS LABORATORY 2017-18

Cryptography is the study of creating ciphers(cipher text) and breaking them (cryptanalysis). The message to
be encrypted, known as the plaintext, are transformed by a function that is parameterized by a key. The output
of the encryption process, known as the ciphertext, is then transmitted. often by messenger or radio. The hacker,
or intruder, hears and accurately copies down the complete ciphertext. However, unlike the intended recipient,
he does not know the decryption key and so cannot decrypt the ciphertext easily.

There are several ways of classifying cryptographic algorithms. They are generally categorized based on the
number of keys that are employed for encryption and decryption, and further defined by their application and
use. The three types of algorithms are as follows:
1. Secret Key Cryptography (SKC): Uses a single key for both encryption and decryption. It is also known as
symmetric cryptography.
2. Public Key Cryptography (PKC): Uses one key for encryption and another for decryption. It is also known
as asymmetric cryptography.
3. Hash Functions: Uses a mathematical transformation to irreversibly "encrypt" information

Public-key cryptography has been said to be the most significant new development in cryptography. Modern
PKC was first described publicly by Stanford University professor Martin Hellman and graduate student
Whitfield Diffie in 1976. In public key cryptography, one key is used to encrypt the plaintext and the other key
is used to decrypt the ciphertext.

In PKC, one of the keys is designated the public key and may be advertised as widely as the owner wants.
The other key is designated the private key and is never revealed to another party. It is straight forward to send
messages under this scheme. Public key of the receiver is used for encryption, so that only the receiver can
decrypt the message (using his private key).

The RSA algorithm is named after Ron Rivest, Adi Shamir and Len Adleman, who invented it in 1977. The
RSA algorithm can be used for both public key encryption and digital signatures.

Algorithm
1. Generate two large random primes, P and Q, of approximately equal size.
2. Compute N = P x Q
3. Compute Z = (P-1) x (Q-1).
4. Choose an integer E, 1 < E < Z, such that GCD (E, Z) = 1
5. Compute the secret exponent D, 1 < D < Z, such that E x D ≡ 1 (mod Z)
6. The public key is (N, E) and the private key is (N, D).

Note: The values of P, Q, and Z should also be kept secret.

The message is encrypted using public key and decrypted using private key.

An example of RSA encryption


1. Select primes P=11, Q=3.
2. N = P x Q = 11 x 3 = 33
Z = (P-1) x (Q-1) = 10 x 2 = 20
3. Lets choose E=3
Check GCD(E, P-1) = GCD(3, 10) = 1 (i.e. 3 and 10 have no common factors except 1),

Dept of ISE MIT, Mysore Page 57


15CSL57 COMPUTER NETWORKS LABORATORY 2017-18

and check GCD(E, Q-1) = GCD(3, 2) = 1


therefore GCD(E, Z) = GCD(3, 20) = 1
4. Compute D such that E x D ≡ 1 (mod Z)
compute D = E^-1 mod Z = 3^-1 mod 20
find a value for D such that Z divides ((E x D)-1)
find D such that 20 divides 3D-1.
Simple testing (D = 1, 2, ...) gives D = 7
Check: (E x D)-1 = 3.7 - 1 = 20, which is divisible by Z.
5. Public key = (N, E) = (33, 3)
Private key = (N, D) = (33, 7).

Now say we want to encrypt the message m = 7,


Cipher code = M^E mod N
= 7^3 mod 33
= 343 mod 33
= 13.
Hence the ciphertext c = 13.
To check decryption we compute Message‟ = C^D mod N
= 13^7 mod 33
= 7.

Note that we don't have to calculate the full value of 13 to the power 7 here. We can make use of the fact that
a = bc mod n = (b mod n).(c mod n) mod n so we can break down a potentially large number into its
components and combine the results of easier, smaller calculations to calculate the final value.
Program:
import java.io.DataInputStream;
import java.io.IOException;
import java.math.*;
import java.util.Random;
public class rsa {
private BigInteger p,q,n,phi,e,d;
private int bitlength=1024;
private Random r;
public rsa(){
r =new Random();
p=BigInteger.probablePrime(bitlength,r);
q=BigInteger.probablePrime(bitlength,r);
n=p.multiply(q);
phi=p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
e=BigInteger.probablePrime(bitlength,r);
while(phi.gcd(e).compareTo(BigInteger.ONE)>0 && e.compareTo(phi)<0){
e.add(BigInteger.ONE);
}
d=e.modInverse(phi);
}
public rsa(BigInteger e,BigInteger d,BigInteger n){

Dept of ISE MIT, Mysore Page 58


15CSL57 COMPUTER NETWORKS LABORATORY 2017-18

this.e=e;
this.d=d;
this.n=n;
}
public static void main(String[] args)throws IOException {
rsa rsa=new rsa();
DataInputStream in=new DataInputStream(System.in);
String teststring;
System.out.println("enter the plain text:");
teststring=in.readLine();
System.out.println("encrypting string:"+teststring);
System.out.println("string in bytes:"+bytestostring(teststring.getBytes()));
byte[]encrypted=rsa.encrypt(teststring.getBytes());
byte[]decrypted=rsa.decrypt(encrypted);
System.out.println("decrypting bytes:"+bytestostring(decrypted));
System.out.println("decrypting string:"+new String(decrypted));
}
private static String bytestostring(byte[]encrypted){
String test=" ";
for(byte b:encrypted){
test+=Byte.toString(b);
}
return test;
}
public byte[]encrypt(byte[]message){
return(new BigInteger(message)).modPow(e,n).toByteArray();
}
public byte[]decrypt(byte[]message){
return(new BigInteger(message)).modPow(d,n).toByteArray();
}
}
Output:

Dept of ISE MIT, Mysore Page 59


15CSL57 COMPUTER NETWORKS LABORATORY 2017-18

Experiment 12: LEAKY BUCKET

Aim: To write a program for congestion control using leaky bucket algorithm.

Theory
The congesting control algorithms are basically divided into two groups: open loop and closed loop. Open
loop solutions attempt to solve the problem by good design, in essence, to make sure it does not occur in the
first place. Once the system is up and running, midcourse corrections are not made. Open loop algorithms are
further divided into ones that act at source versus ones that act at the destination.

In contrast, closed loop solutions are based on the concept of a feedback loop if there is any congestion.
Closed loop algorithms are also divided into two sub categories: explicit feedback and implicit feedback. In
explicit feedback algorithms, packets are sent back from the point of congestion to warn the source. In implicit
algorithm, the source deduces the existence of congestion by making local observation, such as the time needed
for acknowledgment to come back.

The presence of congestion means that the load is (temporarily) greater than the resources (in part of the
system) can handle. For subnets that use virtual circuits internally, these methods can be used at the network
layer.

Another open loop method to help manage congestion is forcing the packet to be transmitted at a more
predictable rate. This approach to congestion management is widely used in ATM networks and is called traffic
shaping.

The other method is the leaky bucket algorithm. Each host is connected to the network by an interface
containing a leaky bucket, that is, a finite internal queue. If a packet arrives at the queue when it is full, the
packet is discarded. In other words, if one or more process are already queued, the new packet is
unceremoniously discarded. This arrangement can be built into the hardware interface or simulate d by the host
operating system. In fact it is nothing other than a single server queuing system with constant service time.

The host is allowed to put one packet per clock tick onto the network. This mechanism turns an uneven flow
of packet from the user process inside the host into an even flow of packet onto the network, smoothing out
bursts and greatly reducing the chances of congestion.

Program:

Dept of ISE MIT, Mysore Page 60


15CSL57 COMPUTER NETWORKS LABORATORY 2017-18

import java.math.*;
import java.util.*;
import java.util.Random;
import java.io.*;
import java.lang.*;
public class leaky{
public static void main(String[]args){
int drop=0,mini,i,o_rate,b_size,nsec,p_remain=0;
int packet[]=new int[100];
Scanner in=new Scanner(System.in);
System.out.print("enter the bucket size");
b_size=in.nextInt();
System.out.print("enter output rate");
o_rate=in.nextInt();
System.out.print("enter the number of seconds to simulate");
nsec=in.nextInt();
Random rand=new Random();
for(i=0;i<nsec;i++)
packet[i]=(rand.nextInt(1000));
System.out.println("seconds packet received packet sent packets left packets dropped");
System.out.println("----------------------");
for(i=0;i<nsec;i++){
p_remain+=packet[i];
if(p_remain>b_size){
drop=p_remain-b_size;
p_remain=b_size;
System.out.print(i+1 +" ");
System.out.print(packet[i] +" ");
mini=Math.min(p_remain,o_rate);
System.out.print(mini +" ");
p_remain=p_remain-mini;
System.out.print(p_remain +" ");
System.out.println(drop +" ");
System.out.print(" " );
drop=0;
}
}
while(p_remain!=0){
if(p_remain>b_size){
drop=p_remain-b_size;
}
mini=Math.min(p_remain,o_rate);
System.out.print(" "+p_remain +" " +mini);
p_remain=p_remain-mini;
System.out.println(" "+p_remain +" " +drop);
drop=0;

Dept of ISE MIT, Mysore Page 61


15CSL57 COMPUTER NETWORKS LABORATORY 2017-18

}
}

Output:

VIVA QUESTIONS WITH ANSWERS

Dept of ISE MIT, Mysore Page 62

You might also like