R 2017 ECE Lab Manual New
R 2017 ECE Lab Manual New
NO : 1
Implementation of Error Detection / Error Correction
Techniques.
DATE :
AIM:
To write a C program to perform for detection and correction of errors in
hamming code.
ALGORITHM:
1. Start the program
2. Get the number of data bits D.
3. Choose the number of additional error correction bits R.
4. Choose generator bits such that generator bits are R+1.
5. Get the data and Generator bit input from user.
6. Append R additional bits to D such that D is exactly divisible by G using
modulo2 arithmetic.
7. Get the data bits at receiver end.
8. The receiver divides the D+R bit by G.
9. If the remainder is non zero, Then No error in transmission
10. If remainder is zero, No error has occurred.
11. End the Program.
PROGRAM:
#include<stdlio.h>
#include<stdio.h>
#include<conio.h>
void main()
{
int h[3][7]={1,0,1,1,1,0,0,
1,1,0,1,0,1,0,
0,1,1,1,0,0,1};
int r[7]; /* Holds input information */
int s[3]; /* The syndrome matrix */
int index; /* Holds the error bit position */
int i,j,sum;
printf("Enter the 7bit information(0's and 1's) with blank spaces between each
bit\n");
for (i=0;i<7;i++)
1
scanf("%d",&r[i]);
for(j=0;j<3;j++)
{
sum=0;
for(i=0;i<7;i++)
sum+=h[j][i]*r[i];
sum=sum%2;
s[j]=sum;
}
/* Now we check if the syndrome matrix s[] is a null vector or
not. If it is, then the accepted info is errorfree. Or else
we need to detect and correct the error */
if(s[0]==0 && s[1]==0 && s[2]==0)
{
printf("\nErrorfree information\n");
printf("The data bits are\n");
for(i=0;i<4;i++)
printf("%d",r[i]);
printf("\n");
exit(0);
}
/* Error bit position detection and correction
/* We compare the syndrome s[] matrix with each column of the
h[][] matrix until a match is found. The matching column
determines the index of the error bit and we can compliment
the bit at that position to get the corrected data */
for(j=0;j<7;j++)
{
if(s[0]==h[0][j] && s[1]==h[1][j] && s[2]==h[2][j])
{
index=j;
break;
}
}
printf("\nThe error is in the bit no %d\n",index+1);
/* compliment the error bit */
if(r[index]==0)
r[index]=1;
else
r[index]=0;
printf("The corrected information is\n");
for(i=0;i<7;i++)
printf("%d",r[i]);
printf("\nThe data bits are\n");
2
for(i=0;i<4;i++)
printf("%d",r[i]);
getch();
}
OUTPUT:
Enter the 7bit information (0's and 1's) with blank spaces between each bit
1 0 1 0 0 1 1
Errorfree information
The data bits are
1010
Enter the 7bit information (0's and 1's) with blank spaces between each bit
1 0 1 0 0 0 1
The error is in the bit no 6
The corrected information is
1010011
The data bits are
1010
3
RESULT:
Thus the implementation of the Error Detection / Error Correction
Techniques was completed successfully.
EX. NO : 2a
Implementation of Stop and Wait Protocol
DATE :
AIM:
To implement the stop and wait protocol using C.
ALGORITHM:
1. Start the Program
2. Get user input on type of medium (reliable forward or reliable reverse),
number of frames to send.
3. Send the frame to server and wait for acknowledgement.
4. If the packet is lost, resend the packets.
5. If ACK is lost, resend the packet.
6. On receiving the acknowledgement for sent frame, send the next frame.
7. Stop the program.
PROGRAM:
#include<stdio.h>
#define MAXSIZE 100
typedef struct
{
unsigned char data[MAXSIZE];
}packet;
typedef enum{data,ack}frame_kind;
typedef struct
4
{
frame_kind kind;
int sq_no;
int ack;
packet info;
}frame;
typedef enum{frame_arrival}event_type;
typedef enum{true_false}boolean;
void frame_network_layer(packet *p)
{
printf("\n from network arrival");
}
void to_physical_layer(frame *f)
{
printf("\n to physical layer");
}
void wait_for_event(event_type *e)
{
printf("\n waiting for event n");
}
void sender(void)
{
frame s;
packet buffer;
event_type event;
printf("\n ***SENDER***");
frame_network_layer(&buffer);
s.info=buffer;
to_physical_layer(&s);
wait_for_event(&event);
}
void from_physical_layer(frame *f)
{
printf("from physical layer");
}
void to_network_layer(packet *p)
{
printf("\n to network layer");
}
void receiver(void)
{
frame r,s;
event_type event;
printf("\n ***RECEIVER***");
wait_for_event(&event);
5
from_physical_layer(&r);
to_network_layer(&r.info);
to_physical_layer(&s);
}
main()
{
sender();
receiver();
}
SAMPLE OUTPUT:
6
RESULT:
Thus the implementation of the Stop and Wait Protocol was completed
successfully.
EX. NO : 2b
Implementation of Sliding Window
DATE :
AIM:
To implement the sliding window using C.
ALGORITHM:
Step 1: Start the program.
Step 2: Open the input file in read mode.
Step 3: Read the size of the window
Step 4: Select randomly the number of packets is to be transferred.
Step 5: Read the content of the input file.
Step 6: Transfer the packet until it reaches the maximum defined size.
7
Step 7: Resume the window size and repeat the above two steps until packets in.
Step 8: Close the file.
Step 9: Stop the program.
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
main()
int i,m,n,j,w,1;
char c;
FILE*f;
f=fopen("text.txt","r");
printf("window size");
scanf("%d",&n);
m=n;
while(!fof(f))
{
i=rand()%n+1;
j=i;
1=i;
if(m>i)
{
m=mi;
if(m>0)
{
printf("\n");
while(i>0 & !feof(f))
{
c=getc(f);
printf("%c",c);
i;
}
printf("\n%d transferred"j);
if(j>3)
printf("\n 1 acknowledgement received");
else
printf("\n acknowledgement received",j+1);
}
}
m=m+j1;
}
8
}
SAMPLE INPUT OUTPUT:
[csea56host csea56] cc slide07.c
[csea56host csea56]./a.out
window size3
we
2 transferred
ack received
1
1 transferred
ack received
co
2 transferred
ack received
me
3 transferred
ack received
1 transferred
ack received
RESULT:
EX. NO : 3
Implementation and Study of Goback – N and Selective
Repeat Protocol
DATE :
AIM:
To implement and Study the go back N and selective repeat protocol using Java
ALGORITHM:
SERVER SIDE:
1. Start the program.
2. Accept client connection and receive frame.
9
3. If an incoming frame is lost, discard further incoming frames, send
acknowledgement for received frame and wait for lost frame.
4. Once you receive the lost frame, send acknowledgement.
5. Stop the program.
CLIENT SIDE:
1. Start the Program
2. Get user input on type of medium (reliable forward or reliable reverse),
number of frames to send.
3. Send the frames to server and wait for acknowledgement.
4. If the packet is lost, resend the packets.
5. If ACK is lost, check for cumulative acknowledgements and proceed.
6. Stop the program.
PROGRAM:
SERVER SIDE
import java.io.*;
import java.net.*;
import java.lang.*;
import java.util.LinkedList;
public class srserver {
public static void main(String args[]){
try {
ServerSocket s=new ServerSocket(95);
Socket cs =s.accept();
BufferedReader fromclient = new BufferedReader(new
InputStreamReader(cs.getInputStream()));
DataOutputStream toclient= new DataOutputStream(cs.getOutputStream());
OutputStream output = cs.getOutputStream();
LinkedList<String> list = new LinkedList<String>();
String med = fromclient.readLine();
int choice = Integer.parseInt(med);
System.out.println("Selected medium is "+choice);
String f = fromclient.readLine();
int nf=Integer.parseInt(f);
System.out.println("Number of frames = "+nf);
int ack=0,rndnum=1,kill=0;
if (choice==1) {
String rndm=fromclient.readLine();
rndnum= Integer.parseInt(rndm);
10
}
for(int i=0;i<nf;i++) {
if ((choice==1) &&(i==rndnum)) {
list.add(i,"killed");
kill=i;
continue;
}
String n=fromclient.readLine();
int num=Integer.parseInt(n);
String frame=fromclient.readLine();
list.add(num,frame);
if ((choice==1) && (list.contains("killed"))) {
ack= list.indexOf("killed");
toclient.writeBytes(ack+"\n");
num=ack;
}
try
{
Socket con =new Socket("localhost",95);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
DataOutputStream toserver= new DataOutputStream(con.getOutputStream());
DataInputStream fromserver = new DataInputStream(con.getInputStream());
LinkedList<String> list = new LinkedList<String>();
Random rndNumbers = new Random();
int rndNumber = 0;
System.out.println("\n1.Unreliable forward medium\n2.unreliable reverse medium
\n");
System.out.println("Your choice(1,2):");
String tmpch=in.readLine();
int choice=Integer.parseInt(tmpch);
toserver.writeBytes(choice+"\n");
System.out.println("Enter number of frames to be transmitted");
String n=in.readLine();
int nf=Integer.parseInt(n);
toserver.writeBytes(nf+"\n");
rndNumber = rndNumbers.nextInt(nf);
for(int i=0;i<nf;i++) {
System.out.println("Enter frame"+i+"to be transmitted");
String frame=in.readLine();
list.add(frame);
}
System.out.println(list);
int discard=0;
int ack=0,kill=0;
for(int i=0;i<nf;i++)
11
{
if ((i==1)&& (choice ==1))
{
discard=1;
continue;
} else {
String str=list.get(i);
if (discard==1) str="Discarded";
toserver.writeBytes(i+"\n");
toserver.writeBytes(str+"\n");
}
if ((choice==2) && (i==1))
{
ack++
continue;
}
String ak = fromserver.readLine();
ack = Integer.parseInt(ak);
System.out.println(" ack received for "+ack);
}
if (choice ==1) {
for(int r=ack;r<nf;r++)
{
System.out.println("Resending frame"+r);
String str=list.get(r);
toserver.writeBytes(r+"\n");
toserver.writeBytes(str+"\n");
}
}
fromserver.close();
toserver.close();
con.close();
}catch (Exception e)
{
System.out.println("\n\n ERRO"+e);
}
}
}
CLIENT SIDE:
import java.io.*;
import java.net.*;
import java.lang.*;
12
import java.util.LinkedList;
import java.util.*;
public class gbnclient{
public static void main(String args[]){
toclient.writeBytes(ack+"\n");
num=ack;
}
if ((i==1) && (choice==2)) {
continue;
}
System.out.println("sending ack"+num);
toclient.flush();
toclient.writeBytes(num+"\n");
toclient.flush();
}
System.out.println(list);
if (choice==1) {
for(int r=ack;r<nf;r++)
{
String n=fromclient.readLine();
int num=Integer.parseInt(n);
String frame=fromclient.readLine();
System.out.println("received frame"+num+" = "+frame);
list.add(num,frame);
}
}
fromclient.close();
output.close();
cs.close();
}
catch (Exception e)
{
System.out.println("\n\n ERROR"+e);
}
}
}
SAMPLE OUTPUT
13
RESULT:
Thus the given implementation and study of Goback N protocols and
Selective repeat protocol was completed successfully.
Ex no : 4 Implementation of High level Data link control
14
Date:
Aim : To implement the High level Data link control using c program.
Algorithm
1.Start the program
2.open the input file in read mode.
3.Read the size of the window
4.select randomly the number of packet to be transferred
5.Read the content of input file.
6.Transfere the packet until it reaches the maximum defined size.
7.close the file.
8. stop the program
Program
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int i,j,count=0,n1;
char str[100];
clrscr();
printf("Enter the bit string");
gets(str);
for(i=0;i<strlen(str); i++)
{
count=0;
for(j=1;j<=(i+5); j++)
{
if(str[i]=='1')
{
count ++;
}
}
if(count==6)
{
n1=strlen(str)+2;
for(n1>=(i+5);n1)
{
str[n1]=str[n11];
}
str[i+5]='0';
15
i=i+7;
}
}
puts(str);
getch();
}
SAMPLE INPUT OUTPUT:
Enter the bit String
11111101001
11111001001
RESULT:
16
Thus the given implementation and study of Goback N protocols and
Selective repeat protocol was completed successfully.
EX. NO : 5 Study of Socket Programming and Client – Server
DATE : Model
AIM:
To study about the Client – Server architecture and basics required for socket
programming.
THEORY
Network applications are everywhere. Any time somebody browses the Web,
sends an email message, they are using a network application. Interestingly,
all network applications are based on the same basic programming model,
have similar overall logical structures, and rely on the same programming
interface. Network applications rely on many of the concepts like processes,
signals, byte ordering, memory map ping, and dynamic storage allocation
etc., the clientserver programming model serves as the basic model for any
network application. The clientserver programs use the services provided by
the Internet.
The ClientServer Programming Model:
Every network application is based on the clientserver model. With this
model, an application consists of a server process and one or more client
processes. A server manages some resource, and it provides some service for
its clients by manipulating that resource. For example, a Web server
manages a set of disk files that it retrieves and executes on behalf of clients.
An FTP server manages a set of disk files that it stores and retrieves for
clients. Similarly, an email server manages a spool file that it reads and
updates for clients. The fundamental operation in the clientserver model is
the transaction.
Client –Server Programming Model:
17
A clientserver transaction consists of four steps:
1. When a client needs service, it initiates a transaction by sending a request to the
server. For example, when a Web browser needs a file, it sends a request to a Web
server.
2. The server receives the request, interprets it, and manipulates its resources in
the appropriate way. For example, when a Web server receives a request from a
browser, it reads a disk file.
3. The server sends a response to the client, and then waits for the next request. For
example, a Web server sends the file back to a client.
4. The client receives the response and manipulates it. For example, after a Web
browser receives a page from the server, it displays it on the screen.
Sockets:
It is important to realize that clients and servers are processes and not machines, or
hosts as they are often called in this context. A single host can run many different
clients and servers concurrently, and a client and server transaction can be on the
same or different hosts. The clientserver model is the same, regardless of the
mapping of clients and servers to hosts.
Clients and servers often run on separate hosts and communicate using the
hardware and software resources of a computer network. Networks are
sophisticated systems. To a host, a network is just another I/O device that serves as
a source and sinks for data. An adapter plugged into an expansion slot on the I/O
bus provides the physical interface to the network. Data received from the network
is copied from the adapter across the I/O and memory buses into memory, typically
by a DMA transfer. Similarly, data can also be copied from memory to the network.
Physically, a network is a hierarchical system that is organized by geographical
proximity. At the lowest level is a LAN (Local Area Network) that spans a building
or a campus. The most popular LAN technology by far is Ethernet, which was
developed in the mid1970s at Xerox PARC. Ethernet has proven to be remarkably
resilient, evolving from 3 Mb/s to 10 Gb/s.
18
Connected Mode:
The connected mode is the most natural way of handling network communications.
It corresponds closely to how people are used to communicate say over a phone line.
In this mode the two parties share a (virtual) connection that they send data over.
The connection first needs to be opened, then data can be sent and eventually the
connection is closed. Data sent in such a way has a low chance of getting lost and
will always arrive in the order it was sent. Both the traditional telephone network
and the TCP for the Internet work in this way.
Disconnected Mode:
The disconnected mode is a way of communication in which no connection needs to
be established between the parties communicating. In this mode information is
broadcast. Since there is no notion of connection it cannot be detected if information
has not been picked up by a receiver or information might arrive out of order. Radio
and television as well as the UDP for the Internet work in this mode.
Sockets:
A socket forms the interface between the protocol and client for communication. It is
an abstraction that is provided to an application programmer to send or receive
data to another process. Data can be sent to or received from another process
running on the same machine or a different machine. Sockets are endpoint of an
connection which exists on either side of the connection. A Socket is identified by an
IP Address and a port number. IP (internet protocol) breaks communication into
packets. Packets are routed and delivered separately. IP does not guarantee
delivery of packets. Sockets enable two machines to communicate via IP. Other
protocols layered on top of IP are TCP (Transmission Control Protocol) and UDP
(User Datagram Protocol). Ports are a means to distinguish various services on a
machine. Ports are divided into the following groups:
ports 01023 System ports (admin rights on Unix) or wellknown ports.
ports 102449151 registered ports can be used explicitly
ports 4915265535 dynamic ports or private ports
JAVA Sockets
The java.net package contains the classes and interfaces required for networking.
Some important classes are MulticastSocket, ContentHandler, URLServerSocket,
19
Socket, InetAddress, URLConnection, DatagramSocket, and DatagramPacket.
Some important interfaces in the java.net package are ContentHandlerFactory,
SocketImplFactory, FileNameMap, URLStreamHandlerFactory, and
SocketOptions.
InetAddress
This class encapsulates the numerical IP address and the domain name for the
address. Factory methods of a class allow you to call the method without referencing
the object.
The factory methods of this class are:
getLocalHost() method Returns the name of the local computer
getByName() method Returns the address by the Domain name
getAllByName() method Returns all the addresses by their domain name
The instance methods of a class are methods that can be called from an object only.
The instance methods for the class are:
getAddress() method Returns a fourelement byte array that represents the
objects IP address in network byte order
getHostAddress() method Returns the host address
getHostName() method Returns the hostname that is associated with the host
address.
The TCP/IP Client Socket
A TCP/IP client socket is used to create a reliable, bidirectional, streambased
connection between two computers on a network. The client socket is implemented
by creating an instance of the Socket class. It is designed to connect to the server
and initialize protocol exchanges. An object of the Socket class can be created by
these methods:
1. By specifying the hostname and port number as follows:
Socket (String hostname1, int port1)
Where, hostname1 is a string type variable that refers to the destination address
and port1 refers to the port number of the destination address. This method can
throw the exceptions, UnknownHostException or IOException, in case of errors.
TCP ClientServer Interaction:
20
2. By specifying an object of InetAddress and the port number as follows:
Socket(InetAddress ipaddr1, int port1)
Where, ipaddr1 is object of the InetAddress class and port1 refers to the port
number of the destination. This method can throw the exception IOException, in
case of errors.
Methods of the Socket Class are
InetAddress getInetAddress() Returns the InetAddress that is associated with
the socket object.
int getPort() Returns the port number on which the socket is connected
int getLocalPort() Returns the local port number on which the socket is created
InputStream getInputStream() Returns the InputStream associated with the
calling object.
OutputStream getOutputStream() Returns the OutputStream associated with
the calling object.
void close() Closes the InputStream() and OutputStream() of the socket.
The TCP/IP Server Socket
21
The TCP/IP server socket creates a socket that listens for incoming connections. The
server socket is implemented by creating an instance of the ServerSocket class. The
server socket creates a server on the system to detect client connections.An instance
of the ServerSocket class can create a server that accepts incoming requests. An
object of the ServerSocket class can be created using any one of these methods:
1. Specify the port number in the int type.
ServerSocket(int port1)
Where, port1 is an integer, which can have any value between 0 and 65,536.
2. Specify the port number and maxQueue. maxQueue refers to the number of
connections the socket can leave pending before refusing more connections.
ServerSocket(int port1, int maxQ)
Where, maxQ refers to an int value that specifies the number of connections it can
leave pending before refusing any more connections.
3. Specify the port number, maxQueue, and the local address.
ServerSocket(int port1, int maxQ, InetAddress address1)
Where, address1 refers to the IP address of the server on which the socket is
created.
Methods of the ServerSocket Class:
socket accept() Accepts an incoming connection.
int getLocalPort() Returns the port number on which the server socket is
listening.
void close() Closes the server socket.
Character Streams:
22
UDP Sockets
UDP is an `unreliable'' protocol that does not include software mechanisms for
retrying on transmission failures or data corruption (unlike TCP), and has
restrictions on message length (a little under 65536 bytes). It is needed for
applications that use broadcasting or multicasting, and it underlies such important
applications as NFS (the Network File System), DNS (the Domain Name System),
SNMP (the Simple Network Management Protocol), and various others. UDP is
packetoriented and information is sent in packet format as needed. Every packet
requires address information. It is Lightweight and does not require connection.
But there exists an overhead of adding destination address with each packet. By
default, UDP sockets are made using Datagram Socket
Methods of the DatagramSocket Class:
DatagramSocket() constructs a datagram socket and binds it to any available
port on the local host
DatagramSocket(int lport) constructs a datagram socket and binds it to the
specified port on the local host machine.
23
DatagramSocket(int lport, InetAddress laddr) creates a datagram socket
and binds to the specified local port and laddress.
DatagramSocket(SocketAddress bindaddr) creates a datagram socket and
binds to the specified local socket address.
DatagramPacket(byte[] buf, int length) constructs a DatagramPacket for
receiving packets of length length.
DatagramPacket(byte[] buf, int length, InetAddress address, int port)
constructs a datagram packet for sending packets of length length to the specified
port number on the specified host.
receive(DatagramPacket p) receives a datagram packet from this socket.
send(DatagramPacket p) sends a datagram packet from this socket.
close() closes this datagram socket..
Byte Streams:
RESULT:
24
Thus the given study of Socket Programming and Client Server Model was
completed successfully.
EX. NO : 6
Socket Program for Echo / Ping / Talk Commands
DATE :
AIM:
To demonstrate the implementation of Ping using Java.
ALGORITHM:
1. Start the Program
2. Get the Hostname or IP address for which connectivity has to be checked.
3. If the input is a host name, use InetAddress.getByName() to find the
corresponding IP address.
4. Start a process to execute the Ping command.
5. Use inputStream.readLine() to read the response.
6. Print the response in the command window.
7. End the Program
Program
import java.net.*;
import java.io.*;
import java.util.*;
public class Ping{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter IP/hostname to ping");
String ip=sc.next();
try {
InetAddress IPA=InetAddress.getByName(ip);
String command="Ping "+IPA.getHostAddress();
25
System.out.println("Sending ping request to " +IPA);
Process p = Runtime.getRuntime().exec(command);
BufferedReader inputStream = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String s = "";
// reading output stream of the command
while ((s = inputStream.readLine()) != null) {
System.out.println(s);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
SAMPLE OUTPUT
C:\Users\dhivya\Documents>java Ping
Enter IP/hostname to ping
www.google.com
Sending ping request to www.google.com/216.58.220.36
Pinging 216.58.220.36 with 32 bytes of data:
Reply from 216.58.220.36: bytes=32 time=400ms TTL=57
Reply from 216.58.220.36: bytes=32 time=399ms TTL=57
Reply from 216.58.220.36: bytes=32 time=400ms TTL=57
Request timed out.
Ping statistics for 216.58.220.36:
Packets: Sent = 4, Received = 3, Lost = 1 (25% loss),
Approximate round trip times in milliseconds:
Minimum = 399ms, Maximum = 400ms, Average = 399ms
C:\Users\dhivya\Documents>java Ping
26
RESULT:
Thus the given implementation of Ping using Java program was completed
successfully.
EX. NO : 7a
To create scenario and study the performance of network
DATE :
with CSMA / CA protocol
AIM:
To demonstrate the operation of Wireless LAN using CSMA\CA and analyze the
performance of the network.
PROCEDURE:
Create a New Project
1. From the File menu, choose New, Select Project and click OK.
2. Name the project <your initials_star> and the scenario <your initials_e.no>. (Include
your initials in the project name to distinguish it from other students.) Click OK.
3. Click Next in the Startup Wizard.
4. In the Startup Wizard: Initial Topology dialog box, make sure that Create Empty
Scenario is selected ∙ Click Next ∙ Choose Office for the Network scale ∙ Click Next three
times ∙ Click Finish.
Create the Network
1. Open the Object Palette dialog box. Make sure that the wireless_lan is selected from the
pulldown menu on the object palette.
2. Add to the project workspace the nine wlan_station_adv (fi x) from the palette.
3. Close the Object Palette dialog box .Save your project.
Configure the wireless nodes
1. Repeat the following for each of the nine nodes:
2. Rightclick on the node ∙ Edit Attributes ∙ Assign to the Wireless LAN MAC Address
attribute a value equals to the node number (e.g., address 1 is assigned to node_1).
3. Assign to the Destination Address attribute the corresponding value shown in the
following table ∙ Click OK .
Node Name Destination Address
node_0 Random
node_1 5
node_2 8
27
node_3 6
node_4 7
node_5 1
node_6 3
node_6 4
4. Select all nodes in the network simultaneously except node_0. Rightclick on
any of the selected nodes ∙ Edit Attributes. Check the Apply Changes to
Selected Objects check box.
5. Expand the Traffi c Generation Parameters and the Packet Generation
Arguments hierarchies
1. Edit the attributes to match the following fi gure.Click OK .
7. Select all nodes in the network simultaneously, including node_0 ∙ Rightclick on any
of the selected nodes.Edit Attributes.Check the Apply Changes to Selected Objects
check box.
8. Expand the hierarchy of the Wireless LAN Parameters attribute ∙ Assign the value
4608000 to the Buffer Size(bits) attribute ∙ Click OK .
9. Rightclick on node_0 ∙ Edit Attributes ∙ Expand the Wireless LAN Parameters
hierarchy and set the Access Point Functionality to Enabled ∙ Click OK.
10. Save the project.
Collecting Statistics
1. Rightclick anywhere in the project workspace and select Choose Individual Statistics
from the popup menu.
2. In the Choose Results dialog box, expand the Global Statistics and Node Statistics
hierarchies ∙ Choose Delay(sec), Load(bits/Sec), Throughput(bits/sec), Retransmission
attempts(Packets).
3. Click OK.
Duplicate the Scenario
1. Select Duplicate Scenario from the Scenarios menu and give it the name DCF_PCF ∙
Click OK ∙ Save your project.
2. Select node_0 , node_1 , node_3 , node_5 , and node_7 in the DCF_PCF scenario
simultaneously (click on these nodes while holding the Shift key) ∙ Rightclick on any one of
the selected nodes ∙ Edit Attributes .
3. Check Apply Changes to Selected Objects ∙ Expand the hierarchy of the Wireless LAN
Parameters attribute ∙ Expand the hierarchy of the PCF Parameters attribute ∙ Enable the
PCF Functionality attribute ∙ Click OK .
4. Rightclick on node_0 ∙ Edit Attributes ∙ Expand the Wireless LAN Parameters hierarchy
and set the Access Point Functionality to Enabled ∙ Click OK .
Running the Simulation
1. From the DES menu, choose Configure/Run DES Simulation.
2. Type 10 min in the Duration.
3. Go to the Scenarios menu ∙ Select Manage Scenarios .
28
4. Click on the row of each scenario and click the Collect Results button. This should change
the values under the Results column to <collect> as shown.
5. Click OK to run the four simulations,
6. When the simulation is finished, click the Close.
Viewing Results
1. Rightclick on the workspace. choose View Results popup menu.
2. Expand global statistics, Ethernet, click the check box to view the Global statistics.
3. Expand object statistics, Office network, select required node and statistic to view the
resulst.
4. Click on show button to open the graph in separate window.
RESULT:
Thus the given scenario creation and study of the performance analysis of network with CSMA /
CA protocol was completed successfully
EX. NO : 7b
To create scenario and study the performance of network
DATE :
with CSMA / CD protocol
AIM:
To Implement and study of CSMACD protocol using trainer kit.
EQUIPMENTS:
1. LTS01 trainer kit
2. 3 Computers with win2K/XP and Ethernet port available on them
3. RJ45 to RJ45 LAN connecting cables
4. LSIM LAN protocol analyzer and simulator software
PROCEDURE:
1. Connect 3 or more computer LAN ports using RJ45 to RJ45 LAN connecting
cables provided with the system to LTS01 star topology ports.
2. Switch on the LTS01 & Computers.
3. Run LSIM software on all the computers, one should be server and others should
be clients.
4. On the server computer select type of network as LAN.
5. On the server computer select the topology as STAR, select protocol as CSMACA
click on create network button.
29
6. Remote computer details will appear on the computers connected in network,
server will be able to see all clients and all clients will be able to see only server.
7. Click on the send RTS button to get your computer into transmitter mode.
8. Select the server computer to whom data file is to be transferred , from the load
button, previously stored/selected file information can be loaded or you can select
any file, which is to be transmitted.
9. File size will appear in the software window, select the packet size, interpacket
delay and click OK.
MODEL GRAPH:
30
10. Total packets formed for that file will be indicated on computers, same details of
file will appear on remote computer to which file is to be transmitted.
11. Click on file transfer button to transfer file.
12. During file transfer process try to send file to server from another client computer,
file transfer from second transmitter will also gets initiated.
13. When packet from second sender collides with first sender it will be indicated as
collision packet on server & Client1.
File from first sender will resume after some time and second sender file will be kept on
hold till first file transfer gets completed.
31
14. Once the first sender file reached to server its display is refreshed and server will show
packet status for second sender.
15. Second sender file transfer will also get completed and thus collision of two packets
transmitted simultaneously from two senders is detected and cleared.
16. Multiple file transfer between various serverclient combinations should be performed to
observe throughput v/s packet size graph on transmitter computer.
17. Close file transfer window and click on protocol analyzer and Network analyzer buttons
on transmitter computer to view details of the log created.
18. Under Network analyzer window click on Graph analyzer button.
19. Calculate throughput and click on Plot graph button.
20. Detailed graph of throughput v/s packet size for the total file transfer activity will
appear on graph window.
21. This plot can be printed by clicking on print button.
BLOCK DIAGRAM:
RESULT:
32
Thus the implementation of CSMACD using star topology was completed successfully
EX. NO : 8
Network Topology – Star, Bus and Ring
DATE :
AIM
To demonstrate the implementation of a network using Bus, Star and Ring Topologies and
analyze their performance.
PROCEDURE:
Create a New Project
1. From the File menu, choose New, Select Project and click OK.
2. Name the project <your initials_star> and the scenario <your initials_star>. (Include
your initials in the project name to distinguish it from other sJtudents.) Click OK.
3. Click Next in the Startup Wizard.
4. In the Startup Wizard: Initial Topology dialog box, make sure that Create Empty
Scenario is selected ∙ Click Next ∙ Choose Office for the Network scale ∙ Click Next
three times ∙ Click Finish.
Create the Network
1. Select Topology >Rapid Configuration . From the dropdown menu, choose Star and
click OK. ( Change the topology to Ring, Bus for simulation ring and bus topology)
2. Click the Select Models button in the Rapid Configuration dialog box. From the
Model List dropdown menu, choose Ethernet, and click OK .
3. In the Rapid Configuration dialog box, set the six values as shown, and click OK.
Center Node Model Ethernet_16_hub
Periphery Node Model Ethernet_wkstn
Link Model 10BaseT
Number 5
Center X=25, Y=25
Radius 20
Adding components to the Network
1. Open the object palette by clicking the Object Palette action button (5 button from left)
2. Find Ethernet server object and drag it into the workspace.
3. Right click to turn off node creation.
4. Find 10BaseT link object in palette and click and drag it to the workspace.
33
Sample Results
34
5. Click on the server object, then on the hub object in centre of star. A link is drawn,
Connecting the two objects.
6. Rightclick to turn off link creation.
7. Find the Application Config object in the palette and drag it into the workspace.
8. Rightclick to indicate you are finished placing this kind of object.
9. Find the Profile Config object in the palette and drag it into the workspace.
10. Close the object palette.
Configure the Network Nodes
1. Right click on the object you want to edit and Choose Edit attributes.
2. In order to add traffic in the network edit the following objects:
a. Application Definition Set the application definition attribute to Default.
3. Edit the Profile Configuration. Edit the Profile Configuration in the new window
a. Put number 2 in rows.
b. Set the values as shown
c. Click on applications for each Profile name, and choose edit.
d. Enter the values for Software Development as shown
35
e. Repeat the same for Telecom Profile with the below values.
4. Rightclick on any of the 5 nodes and Select Similar Nodes . Now all nodes in the
network are selected.
5. Rightclick on any of the 5 nodes, choose Edit Attributes and Check the Apply
Changes to Selected Objects check box.
6. Expand Applications, expand Application Supported profiles, Enter 2 for the number
of rows.
7. Double click on Application Supported profiles, and Enter the two profiles
softdevelopment and telecom profile.
8. Right click on the server then choose edit attributes. On the attribute field look for
Application: Supported Service and click “ALL” for the value field.
Collecting Statistics
36
1. Rightclick on the server node and select Choose Individual Statistics from the
server’s Object popup menu.
2. Click the plus sign next to Ethernet in the Choose Results dialog box. Click the check
box next to Load (bits/sec) to turn collection on for that statistic. Click OK to dismiss
the dialog box.
3. Rightclick on the hub node and select Choose Individual Statistics from the hub’s
Object popup menu.
4. Click the plus sign next to Node Statistic in the Choose Results dialog box.
5. Then click the plus sign next to Ethernet in the Choose Results dialog box. Click the
check box next to Collision count and Utilization. Click OK to dismiss the dialog box.
Running the Simulation
1. From the DES menu, choose Configure/Run DES Simulation.
2. Type 10 min in the Duration.
3. Click the Run button to begin the simulation. While the simulation runs, a window
appears showing the simulation’s progress.
4. When the simulation is finished, click the Close.
Viewing Results
1. Rightclick on the workspace. choose View Results popup menu.
2. Expand global statistics, Ethernet, click the check box to view the Global statistics.
3. Expand object statistics, Office network, select required node and statistic to view the
Results.
4. Click on show button to open the graph in separate window.
Sample network
37
Program – Star Topology
CLIENT 1
import java.io.*;
import java.net.*;
// message to client 3
Socket con13 = new Socket("localhost",123);
System.out.println("Connected with Client 3 - IP: "+
con13.getInetAddress().getHostAddress());
CLIENT 2
import java.io.*;
import java.net.*;
public class client2
{
public static void main(String args[])
{
try
{
System.out.println("========== Client 2 ==========");
39
in2.close();
con2.close();
ss2.close();
}
catch(Exception e)
{
System.out.println("error:"+e);
}
}
}
CLIENT 3
import java.io.*;
import java.net.*;
40
//5. Close all objects
in3.close();
con3.close();
ss3.close();
}
catch(Exception e)
{
System.out.println("error:"+e);
}
}
}
CLIENT 1
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
CLIENT 2
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
Thread.sleep(4000);
try
{
System.out.println(" \n==== Passing Token to next client ====");
Socket con2 = new Socket("192.168.5.3",140);
System.out.print("Token sent to Client 3 :"+
con2.getInetAddress().getHostAddress());
con2.close();
42
}
catch(IOException e)
{
System.out.println("Client 3 is disconnected from LAN");
}
}
catch (IOException e)
{
System.out.println("socket error:" +e);
}
catch (InterruptedException e)
{
System.out.println("socket error:" +e);
}
}
}
CLIENT 3
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
43
}
}
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
CLIENT 2
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class cl2
{
public static void main (String args [])
{
44
try
{
System.out.println("========== Client 2 =========");
ServerSocket providersocket = new ServerSocket(140);
System.out.println("waiting for connection");
Socket con = providersocket.accept();
System.out.print("Token received from Client 1 : "+
con.getInetAddress().getHostAddress());
providersocket.close();
Thread.sleep(4000);
try
{
System.out.println(" \n==== Passing Token to next client ======");
Socket con2 = new Socket("192.168.5.3",140);
System.out.print("Token sent to Client 3 :"+
con2.getInetAddress().getHostAddress());
con2.close();
}
catch(IOException e)
{
System.out.println("Client 3 is disconnected from LAN");
System.out.println("\n Token Ring breaks");
}
}
catch (IOException e)
{
System.out.println("socket error:" +e);
}
catch (InterruptedException e)
{
System.out.println("socket error:" +e);
}
}
}
CLIENT 3
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
45
{
public static void main (String args [])
{
try
{
System.out.println("========== Client 3 =========");
ServerSocket providersocket = new ServerSocket(140);
System.out.println("waiting for connection");
Socket con = providersocket.accept();
System.out.print("Token received from Client 2 : "+
con.getInetAddress().getHostAddress());
providersocket.close();
}
catch (IOException e)
{
System.out.println("socket error:" +e);
}
}
}
OUTPUT
Client 1:
========== Client 1 =========
Token Sent to Client 2 : 192.168.5.2
Client 2:
========== Client 2 =========
waiting for connection
Token received from Client 1 : 192.168.5.1
===== Passing Token to next client ====
Token sent to Client 3 :192.168.5.3
Client 3 :
========== Client 3 =========
waiting for connection
Token received from Client 2 : 192.168.5.2
Client 1:
========== Client 1 =========
Clinet 2 is disconnected from LAN
Token Ring breaks
46
Client 2:
(Don’t run program in client2, it is assumed like client 2 disconnected from LAN)
Client 3:
========== Client 3 =========
waiting for connection
Client 1:
========== Client 1 =========
Token Sent to Client 2 : 192.168.5.2
Client 2:
========== Client 2 =========
waiting for connection
Token received from Client 1 : 192.168.5.1
===== Passing Token to next client ====
Client 3 is disconnected from LAN
Token Ring breaks
Client 3:
(Don’t run program in client 3 it is assumed like client 3 disconnected from LAN)
Client 1:
========== Client 1 =========
Clinet 2 is disconnected from LAN
Client 2:
(Don’t run program in client 2 it is assumed like client 2 disconnected from LAN)
Client 3:
(Don’t run program in client 3 it is assumed like client 3 disconnected from LAN)
47
RESULT:
Thus the demonstration and the implementation of a network using Bus, Star and Ring
Topologies and analyze their performance was completed successfully
EX. NO : 9
Implementation of Distance Vector Routing (DVR)
DATE :
Algorithm
Aim:
Write a C program to implement the Distance Vector Routing algorithm
Program:
#include<stdlib.h>
#define nul 1000
#define nodes 10
int no;
struct node
{
int a[nodes][4];
}router[nodes];
48
void init(int r)
{
int i;
for(i=1;i<=no;i++)
{
router[r].a[i][1]=i;
router[r].a[i][2]=999;
router[r].a[i][3]=nul;
}
router[r].a[r][2]=0;
router[r].a[r][3]=r;
}
void inp(int r)
{
int i;
printf("\nEnter dist from the node %d to other nodes",r);
printf("\nPls enter 999 if there is no direct route\n",r);
for(i=1;i<=no;i++)
{
if(i!=r)
{
printf("\nEnter dist to the node %d:",i);
scanf("%d",&router[r].a[i][2]);
router[r].a[i][3]=i;
}
}
}
void display(int r)
{
int i,j;
printf("\n\nThe routing table for node %d is as follows:",r);
for(i=1;i<=no;i++)
{
if(router[r].a[i][2]>=999)
printf("\n\t\t\t %d \t no link \t no hop",router[r].a[i][1]);
else
printf("\n\t\t\t %d \t %d \t\t d",router[r].a[i][1],router[r].a[i][2],router[r].a[i][3]);
}
}
void dv_algo(int r)
{
{
int i,j,z;
for(i=1;i<=no;i++)
49
{
if(router[r].a[i][2]!=999 && router[r].a[i][2]!=0)
{
for(j=1;j<=no;j++)
{
z=router[r].a[i][2]+router[i].a[j][2];
if(router[r].a[j][2]>z)
{
router[r].a[j][2]=z;
router[r].a[j][3]=i;
}
}
}
}
}
int main()
{
int i,j,x,y;
char choice;
printf("Enter the no. of nodes required (less than 10 pls):");
scanf("%d",&no);
for(i=1;i<=no;i++)
{
init(i);
inp(i);
}
printf("\nThe configuration of the nodes after initialization is as follows:");
for(i=1;i<=no;i++)
display(i);
for(i=1;i<=no;i++)
dv_algo(i);
printf("\nThe configuration of the nodes after computation of paths is as follows:");
for(i=1;i<=no;i++)
display(i);
while(1)
{
printf("\n\nWanna continue (y/n):");
scanf("%c",&choice);
if(choice=='n')
break;
printf("\nEnter the nodes btn which shortest path is to be found:\n");
scanf("%d %d",&x,&y);
printf("\nThe length of the shortest path is %d",router[x].a[y][2]);
}
}
Output:
Enter the no. of nodes required (less than 10 pls):4
50
Enter dist from the node 1 to other nodes
Pls enter 999 if there is no direct route
Enter dist to the node 2:5
Enter dist to the node 3:3
Enter dist to the node 4:7
Enter dist from the node 2 to other nodes
Pls enter 999 if there is no direct route
Enter dist to the node 1:5
Enter dist to the node 3:999
Enter dist to the node 4:6
Enter dist from the node 3 to other nodes
Pls enter 999 if there is no direct route
Enter dist to the node 1:3\
Enter dist to the node 2:
Enter dist to the node 4:
Enter dist from the node 4 to other nodes
Pls enter 999 if there is no direct route
Enter dist to the node 1:
Enter dist to the node 2:
Enter dist to the node 3:
The configuration of the nodes after initialization is as follows:
The routing table for node 1 is as follows:
1 0 1
2 5 2
3 3 3
4 7 4
The routing table for node 2 is as follows:
1 5 1
2 0 2
3 no link no hop
4 6 4
The routing table for node 3 is as follows:
1 3 1
2 no link no hop
3 0 3
4 no link no hop
The routing table for node 4 is as follows:
1 no link no hop
2 no link no hop
3 no link no hop
4 0 4
The configuration of the nodes after computation of paths is as follows:
The routing table for node 1 is as follows:
1 0 1
2 5 2
3 3 3
4 7 4
The routing table for node 2 is as follows:
1 5 1
51
2 0 2
3 8 1
4 6 4
The routing table for node 3 is as follows:
1 3 1
2 8 1
3 0 3
4 10 1
The routing table for node 4 is as follows:
1 no link no hop
2 no link no hop
3 no link no hop
4 0 4
Wanna continue (y/n):
Enter the nodes btn which shortest path is to be found:
^C
[root@localhost ~]# clear
[root@localhost ~]# ./a.out
Enter the no. of nodes required (less than 10 pls):4
Enter dist from the node 1 to other nodes
Pls enter 999 if there is no direct route
Enter dist to the node 2:5
Enter dist to the node 3:3
Enter dist to the node 4:7
Enter dist from the node 2 to other nodes
Pls enter 999 if there is no direct route
Enter dist to the node 1:5
Enter dist to the node 3:999
Enter dist to the node 4:6
Enter dist from the node 3 to other nodes
Pls enter 999 if there is no direct route
Enter dist to the node 1:3
Enter dist to the node 2:999
Enter dist to the node 4:2
Enter dist from the node 4 to other nodes
Pls enter 999 if there is no direct route
Enter dist to the node 1:7
Enter dist to the node 2:6
Enter dist to the node 3:2
The configuration of the nodes after initialization is as follows:
The routing table for node 1 is as follows:
1 0 1
2 5 2
3 3 3
4 7 4
The routing table for node 2 is as follows:
1 5 1
2 0 2
52
3 no link no hop
4 6 4
The routing table for node 3 is as follows:
1 3 1
2 no link no hop
3 0 3
4 2 4
The routing table for node 4 is as follows:
1 7 1
2 6 2
3 2 3
4 0 4
The configuration of the nodes after computation of paths is as follows:
The routing table for node 1 is as follows:
1 0 1
2 5 2
3 3 3
4 5 3
The routing table for node 2 is as follows:
1 5 1
2 0 2
3 8 1
4 6 4
The routing table for node 3 is as follows:
1 3 1
2 8 1
3 0 3
4 2 4
The routing table for node 4 is as follows:
1 5 3
2 6 2
3 2 3
4 0 4
Wanna continue (y/n):
Enter the nodes btn which shortest path is to be found:
1 4
The length of the shortest path is 7
Wanna continue (y/n):
Enter the nodes btn which shortest path is to be found:
RESULT:
Thus the given C program has been executed and verified successfully
EX. NO : 10
Implementation of Link State Routing (LSR) Algorithm
DATE :
AIM:
53
To write a C program to perform the link state routing algorithm.
ALGORITHM:
You can write it yourself by own content
PROGRAM:
#include<stdio.h>
main()
{
int n,a[10][10],i,j,k;
printf("\n ENTER THE NO.OF NODES: ");
scanf("%d",&n);
printf("\n ENTER THE MATRIX ELEMENTS: ");
for(i=0;i<n;i++)
{
printf("\nENTER THE DISTANCE FOR NODE:%d\n",i+1);
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
for(i=0;i<n;i++)
{
printf("THE LINK STATE STATE PACKETS FOR NODE:%d\n",i+1);
printf("\n NODE\tDISTANCE\n");
for(j=0;j<n;j++)
{
if(a[i][j]!=0&&a[i][j]!=1)
{
printf("%d\t%d\n",j+1,a[i][j]);
}
}
printf("\n\n");
}
}
54
OUTPUT
RESULT:
Thus the given C program has been executed and verified successfully
55
EX. NO : 11
Study of Network simulator (NS) and simulation of
DATE :
Congestion Control Algorithms using NS
AIM
To study about the Network Simulator and to demonstrate the creation of a simple
network using NS2.
THEORY
In the network research area, it is very costly to deploy a complete test bed
containing multiple networked computers, routers and data links to validate and verify a
certain network protocol or a specific network algorithm. Network simulation is a technique
where a program models the behaviour of a network either by calculating the interaction
between the different network entities using mathematical formula, or by actually
capturing and playing back observations form a production network. Most of the simulators
are GUI driven while some are CLI driven. An important output of simulations is the trace
files which log every event that occurred in the simulation. Trace files are used for further
analysis.
Network Simulator
NS is an event driven network simulator developed at UC Berkeley that
simulates variety of IP networks. It implements network protocols such as TCP and UDP,
traffic source behavior such as FTP, Telnet, Web, CBR and VBR, router queue management
mechanism such as Drop Tail, RED and CBQ, routing algorithms such as Dijkstra, and
more. NS is Objectoriented Tcl (OTcl) script interpreter that has a simulation event
scheduler and network component object libraries, and network setup (plumbing) module
libraries (actually, plumbing modules are implemented as member functions of the base
simulator object).
To setup and run a simulation network, a user should write an OTcl script that
initiates an event scheduler, sets up the network topology using the network objects and
the plumbing functions in the library, and tells traffic sources when to start and stop
transmitting packets through the event scheduler. The term "plumbing" is used for a
network setup, because setting up a network is plumbing possible data paths among
network objects by setting the "neighbor" pointer of an object to the address of an
appropriate object. When a user wants to make a new network object, he or she can easily
make an object either by writing a new object or by making a compound object from the
object library, and plumb the data path through the object. This may sound like
complicated job, but the plumbing OTcl modules actually make the job very easy. The
power of NS comes from this plumbing.
Another major component of NS beside network objects is the event scheduler. An
event in NS is a packet ID that is unique for a packet with scheduled time and the pointer
to an object that handles the event. In NS, an event scheduler keeps track of simulation
time and fires all the events in the event queue scheduled for the current time by invoking
appropriate network components, which usually are the ones who issued the events, and let
them do the appropriate action associated with packet pointed by the event.
56
Network components communicate with one another passing packets, however this
does not consume actual simulation time. All the network components that need to spend
some simulation time handling a packet (i.e. need a delay) use the event scheduler by
issuing an event for the packet and waiting for the event to be fired to itself before doing
further action handling the packet. For example, a network switch component that
simulates a switch with 20 microseconds of switching delay issues an event for a packet to
be switched to the scheduler as an event 20 microsecond later. The scheduler after 20
microsecond dequeues the event and fires it to the switch component, which then passes the
packet to an appropriate output link component. Another use of an event scheduler is
timer. For example, TCP needs a timer to keep track of a packet transmission time out for
retransmission (transmission of a packet with the same TCP packet number but different
NS packet ID). Timers use event schedulers in a similar manner that delay does. The only
difference is that timer measures a time value associated with a packet and does an
appropriate action related to that packet after a certain time goes by, and does not simulate
a delay.
For efficiency reason, NS separates the data path implementation from control path
implementations. In order to reduce packet and event processing time (not simulation
time), the event scheduler and the basic network component objects in the data path are
written and compiled using C++. These compiled objects are made available to the OTcl
interpreter through an OTcl linkage that creates a matching OTcl object for each of the C++
objects and makes the control functions and the configurable variables specified by the C++
object act as member functions and member variables of the corresponding OTcl object. In
this way, the controls of the C++ objects are given to OTcl
57
A Simple Network Topology and Simulation Scenario
This network consists of 4 nodes (n0, n1, n2, n3) as shown in figure. The duplex links between n0 and n2,
and n1 and n2 have 2 Mbps of bandwidth and 10 ms of delay. The duplex link between n2 and n3 has 1.7
Mbps of bandwidth and 20 ms of delay. Each node uses a DropTail queue, of which the maximum size is
10. A "tcp" agent is attached to n0, and a connection is established to a tcp "sink" agent attached to n3.
As default, the maximum size of a packet that a "tcp" agent can generate is 1KByte. A tcp "sink" agent
generates and sends ACK packets to the sender (tcp agent) and frees the received packets. A "udp" agent
that is attached to n1 is connected to a "null" agent attached to n3. A "null" agent just frees the packets
received. A "ftp" and a "cbr" traffic generator are attached to "tcp" and "udp" agents respectively, and
the "cbr" is configured to generate 1 KByte packets at the rate of 1 Mbps. The "cbr" is set to start at 0.1
sec and stop at 4.5 sec, and "ftp" is set to start at 1.0 sec and stop at 4.0 sec.
58
Sample network
59
60
EX. NO : 12
Data Encryption and decryption
DATE :
Aim
To implement encryption and decryption of a file using Java.
ALGORITHM
1. Start the Program
2. Get an instance of cipher using getInstance() method.
3. Generate the key using appropriate key generation methods. It is generateKey()
in symmetric key encryption and generateKeyPair() in asymmetric key encryption.
4. Create a file to encrypt(for eg. cleartext.txt ) using notepad or choose appropriate
file and give input to the script.
5. Methods CipherInputStream and CipherOutputStream are used to for encryption
and decryption process
6. Encrypted text is stored in new file(ciphertextSymm.txt) file. Decrepted text is
also stored in separate file(cleartextAgainSymm.txt).
7. End the Program
Program
Symmetric Key Encryption
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class ExampleCrypt {
61
public static void main(String[] args) throws Exception {
Cipher cipher = Cipher.getInstance("AES");
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
SecretKey secKey = keyGen.generateKey();
cipher.init(Cipher.ENCRYPT_MODE, secKey);
String cleartextFile = "cleartext.txt";
String ciphertextFile = "ciphertextSymm.txt";
FileInputStream fis = new FileInputStream(cleartextFile);
FileOutputStream fos = new FileOutputStream(ciphertextFile);
CipherOutputStream cos = new CipherOutputStream(fos, cipher);
byte[] block = new byte[8];
int i;
while ((i = fis.read(block)) != 1) {
cos.write(block, 0, i);
}
cos.close();
String cleartextAgainFile = "cleartextAgainSymm.txt";
cipher.init(Cipher.DECRYPT_MODE, secKey);
fis = new FileInputStream(ciphertextFile);
CipherInputStream cis = new CipherInputStream(fis, cipher);
fos = new FileOutputStream(cleartextAgainFile);
while ((i = cis.read(block)) != 1) {
fos.write(block, 0, i);
}
fos.close();
}
}
Asymmetric Key Encryption
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
62
import java.security.*;
import javax.crypto.*;
public class ExampleRSA {
public static void main(String[] args) throws Exception {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
Cipher cipher = Cipher.getInstance("RSA");
kpg.initialize(1024);
KeyPair keyPair = kpg.generateKeyPair();
Private Key privKey = keyPair.getPrivate();
PublicKey pubKey = keyPair.getPublic();
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
String cleartextFile = "cleartext.txt";
String ciphertextFile = "ciphertextRSA.txt";
FileInputStream fis = new FileInputStream(cleartextFile);
FileOutputStream fos = new FileOutputStream(ciphertextFile);
CipherOutputStream cos = new CipherOutputStream(fos, cipher);
byte[] block = new byte[32];
int i;
while ((i = fis.read(block)) != 1) {
cos.write(block, 0, i);
}
cos.close();
String cleartextAgainFile = "cleartextAgainRSA.txt";
cipher.init(Cipher.DECRYPT_MODE, privKey);
fis = new FileInputStream(ciphertextFile);
CipherInputStream cis = new CipherInputStream(fis, cipher);
fos = new FileOutputStream(cleartextAgainFile);
while ((i = cis.read(block)) != 1) {
fos.write(block, 0, i);
}
fos.close();
}
}
SAMPLE OUTPUT
Symmetric Encryption
I:\ \LAB\programs\encryption>javac ExampleCrypt.java
I:\ \LAB\programs\encryption>java ExampleCrypt
I:\ \LAB\programs\encryption>
Asymmetric Encryption
I:\ \LAB\programs\encryption>javac ExampleRSA.java
I:\ \LAB\programs\encryption>java ExampleRSA
I:\ \LAB\programs\encryption>
63
RESULT:
Thus the given implementation of encryption and decryption of a file using Java has
been executed successfully.
64