Assignment Java Programs
Assignment Java Programs
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.
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.
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 {
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]);
}
}
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");
}
}
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;
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;
}
Input graph:
5
A B
3
4
C D
2
Output:
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:
import java.net.*;
import java.io.*;
import java.net.*;
import java.io.*;
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
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:
import java.io.*;
import java.net.*;
import java.net.*;
class udpser {
public static void main(String args[]) throws Exception
{
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();
}
}
OUTPUT
Compile and execute server side program
Aim: To write a program for simple RSA algorithm to encrypt and decrypt the data.
Theory
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).
The message is encrypted using public key and decrypted using private key.
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){
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:
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:
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;
}
}
Output: