Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
13 views78 pages

Aids NT Lab-1

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 78

An Autonomous Institution

Approved by AICTE, Affiliated to Anna University, Chennai.


ISO 9001:2015 Certified Institution, Accredited by NBA (BME, CSE, ECE, EEE, IT & MECH),
Accredited by NAAC.
#42, Avadi-Vel Tech Road, Avadi, Chennai- 600062, Tamil Nadu, India.
DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND DATA SCIENCE

191CS42C / NETWORKS LABORATORY

NAME :

REGISTER NO :

VM NO : VM -

BRANCH : AI&DS

YEAR : II

SEMESTER : IV

DEPARTMENT OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE


Vision

➢ To promote centre of excellence through effectual Teaching and Learning, imparting the contemporary knowledge
centric education through innovative research in multidisciplinary fields.
Mission

➢ To impart quality technical skills through practicing, knowledge updating in recent technology and produce
professionals with multidisciplinary and leadership skills.
➢ To promote innovative thinking for design and development of software products of varying complexity withintelligence
to fulfil the global standards and demands.
➢ To inculcate professional ethics among the graduate and to adapt the changing technologies through lifelong learning.
An Autonomous Institution
Approved by AICTE, Affiliated to Anna University, Chennai.
ISO 9001:2015 Certified Institution, Accredited by NBA (BME, CSE, ECE, EEE, IT & MECH),
Accredited by NAAC.
#42, Avadi-Vel Tech Road, Avadi, Chennai- 600062, Tamil Nadu, India.

CERTIFICATE

Name …………………….………………Year: ……………… Semester: ..................... Branch:


B.TECH – ARTIFICIAL INTELLIGENCE AND DATA SCIENCE University Register
No………………….. College VM No:……………… Certified that this is the bonafide record of work
done by the above student in the 191CS42C– NETWORKS LABORATORY during the academic year
2023-2024.

Signature of the Course In-charge Signature of Head of the Department

Submitted for the University Practical Examination held on ………………... at VEL TECH MULTI
TECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE, No.42, AVADI – VEL
TECH ROAD, AVADI, CHENNAI-600062.

Signature of Examiners

Internal Examiner:…………… External Examiner:………………

Date:………………
DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND DATA SCIENCE

POs Programme Outcomes (POs)

PO1 Engineering Knowledge: Apply knowledge of mathematics, science, engineering


fundamentals and an Engineering Specialization to the solution of complex engineering
problems.

PO2 Problem Analysis: Identify, formulate, review research literature and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.

PO3 Design / Development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet specified needs with appropriate consideration
for public health and safety, cultural, societal, and environmental considerations.

PO4 Conduct Investigations of Complex Problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.

PO5 Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with
an understanding of the limitations.

PO6 The Engineer and Society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant tothe
professional engineering practice.

PO7 Environment and sustainability: Understand the impact of the professional engineering solutions
in societal and environmental contexts, and demonstrate the knowledge of, and need for
sustainable development.

PO8 Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms
of the engineering practice.

PO9 Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.

PO10 Communication: Communicate effectively on complex engineering activities with the


engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions

PO11 Project Management and Finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.

PO12 Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
PROGRAM EDUCATIONAL OBJECTIVES(PEOs)

PEOs Programme Educational Objectives(PEOs)

Train the graduates with the potential of strong knowledge in the respective field and to create
PEO1
innovative multidisciplinary solutions for challenges in the society.

Groom the engineers to understand, analyse different nature of data and use Machine Learning
PEO2 techniques to develop software systems with varying complexity for data intensive
applications.

To practice professionalism among the graduates and reflect good leadership skills with ethical
PEO3
standards and continued professional development through lifelong learning.

PROGRAMMESPECIFICOUTCOMES(PSOs)

PSO’s PROGRAMMESPECIFICOUTCOMES(PSOs)

To impart theoretical knowledge in the respective field along with recent industrial tools
PSO1
and techniques to solve societal problems

Apply the core competency obtained in the field of Machine Learning for analysis, design
PSO2
and development of computing systems for multi-disciplinary problems

Acquire knowledge in the field of intelligence, deep learning and develop software
PSO3
solutions for security and analytics of large volume of data.
COURSE OBJECTIVES

The student should be made to:


• To learn network commands
• To learn socket programming
• To implement and analyze various network protocols
• To learn and use simulation tools
• To use simulation tools to analyze the performance of various network protocols

COURSE OUTCOMES
At the end of the course, the student should be able to

Course CO Statements
Outcome

CO1 Implement various protocols using TCP and UDP


CO2 Compare the performance of different transport layer protocols
CO3 Use simulation tools to measure the performance of various network protocols
Analyze various routing algorithms
CO4
CO5 Implement error correction codes

CO – PO & PSO

CO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2 PSO3

CO1 3 3 3 3 3 2 2 2 2 1 1 1 3 2 1

CO2 3 3 3 3 2 2 2 2 2 1 1 1 2 2 1

CO3 3 3 3 3 3 2 2 2 1 1 1 1 2 2 1

CO4 3 3 3 3 3 2 2 2 1 1 1 1 2 2 1

CO5 3 3 3 3 3 1 1 1 1 1 1 1 1 1 1

CO 3 3 3 3 3 2 2 2 1 1 1 1 2 2 1
LIST OF
EXPERIMENTS

Ex. Page
Date List of Exercises CO Marks signature
No No
a. Implementations of Sliding Window CO1
1 Protocol
b. Implementation of Stop and Wait Protocol CO1

Study of Socket programming CO1, CO2


2 and Client-Server model (Date and Time server
Model)
a. Implementation of ARP protocol CO1, CO2
3
b. Implementation of RARP protocol CO1, CO2

a. Implementation of PINGcommand CO1, CO2


4
b. Implementation of TRACEROUTE CO1, CO2,
command CO4
Uploading and downloading imagefile using CO1, CO2,
5 Socket programming CO4
` Applications using TCP Sockets like: CO1, CO2,
a. Echo client and Echo server CO4
6 b. Chat Application CO1, CO2,
CO4,CO5
c. File Transfer using TCPSocket CO1, CO2,
CO4, CO5.
7 Implementation of DNS using UDP sockets CO1, CO2,
CO4
Study of Network Simulator (NS) and CO1-CO3
Simulation of Congestion Control Algorithms
8
using NS
a. Study of TCP performance usingsimulation CO1 - CO3
tool
9 b. Study of UDP performance usingsimulation CO1 - CO3
tool
Study of Distance vector/Link CO1 - CO4
10 State routing algorithm using NS
Implementation of Go Back NARQ Protocol CO1, CO2,
11 CO4
Implementation of Error CorrectionCode (CRC) CO1, CO2,
12 CO4, CO5
EXNO: 1A DATE:

IMPLEMENTATION OF SLIDING WINDOW PROTOCOL

AIM:
To write a java program to perform Sliding Window protocol.

ALGORITHM:

STEP 1: Start the program


STEP 2: Sender keeps track of outstanding frames and updates the variable and window

as acknowledgements arrive.
STEP 3: Receiver sliding window waits for a specific frame to arrive in a specific
order andframe arriving out of order is discarded and needs to be resent.
STEP 4: Commence transmission.
STEP 5: Deal with damaged or lost frame.
STEP 6: Deal with damaged or lost acknowledgement.
STEP 7: Deal with delayed acknowledgement.
STEP 8: Update sender windows
STEP 9: Stop the program.

PROGRAM:

SENDER PROGRAM

import java.net.*;
import java.io.*;
import java.rmi.*;
class slidesender
{
public static void main(String a[])throws Exception
{
ServerSocketser=new ServerSocket(10); Socket s=ser.accept();
DataInputStream in=new DataInputStream(System.in);
DataInputStream in1=new DataInputStream(s.getInputStream());
String sbuff[]=new String[8];
PrintStream p;
intsptr=0,sws=8,nf,ano,i; String ch;
do
{
p=new PrintStream(s.getOutputStream());
7
System.out.print("Enter the no. of frames : ");
nf=Integer.parseInt(in.readLine()); p.println(nf);
if(nf<=sws-1)
{
System.out.println("Enter "+nf+" Messages to be send\n"); for(i=1;i<=nf;i++)
{
sbuff[sptr]=in.readLine();
p.println(sbuff[sptr]);
sptr=++sptr%8;
}
sws-=nf;
System.out.print("Acknowledgment received"); ano=Integer.parseInt(in1.readLine());
System.out.println(" for "+ano+" frames"); sws+=nf;
}
else
{
System.out.println("The no. of frames exceeds window size"); break;
}
System.out.print("\nDo you wants to send some more frames : "); ch=in.readLine();
p.println(ch);
}
while(ch.equals("yes"));
s.close();
}
}

RECEIVER PROGRAM
import java.net.*;
import java.io.*;
class slidereceiver
{
public static void main(String a[])throws Exception
{
Socket s=new Socket(InetAddress.getLocalHost(),10);
DataInputStream in=new DataInputStream(s.getInputStream());
PrintStream p=new PrintStream(s.getOutputStream());
inti=0,rptr=-1,nf,rws=8;
String rbuf[]=new String[8];
String ch;
System.out.println();
do
{
nf=Integer.parseInt(in.readLine());
if(nf<=rws-1)
{
for(i=1;i<=nf;i++)
{
8
rptr=++rptr%8;
rbuf[rptr]=in.readLine();
System.out.println("The received Frame " +rptr+" is : "+rbuf[rptr]);
}
rws-=nf;
System.out.println("\nAcknowledgment sent\n");
p.println(rptr+1);
rws+=nf;
}
else
break;
ch=in.readLine();
}
while(ch.equals("yes"));
}
}

OUTPUT:

Sender Window

9
Receiver Window

RESULT:
Thus the program for implementation of sliding window protocol was executed and the
output is verified successfully.

INFERENCE:

10
EXNO: 1B DATE:

IMPLEMENTATION OF STOP AND WAIT PROTOCOL

AIM:
To write a java program to perform stop and wait protocol.

ALGORITHM:

STEP 1: Start the program


STEP 2: Sender keeps track of outstanding frames and updates the variable and window as
acknowledgements arrive.
STEP 3: Receiver sliding window waits for a specific frame to arrive in a specific order and
framearriving out of order is discarded and needs to be resent.
STEP 4: Commence transmission.
STEP 5: Deal with damaged or lost frame.
STEP 6: Deal with damaged or lost acknowledgement.
STEP 7: Deal with delayed acknowledgement.
STEP 8: Update sender windows
STEP 9: Stop the program.

PROGRAM

SENDER PROGRAM

import java.io.*;
import java.net.*;
public class Sender{
Socket sender;
ObjectOutputStream out;
ObjectInputStream in;
String packet,ack,str, msg;
int n,i=0,sequence=0;
Sender(){}
public void run(){
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Waiting for Connection....");
sender = new Socket("localhost",2004);
sequence=0;
11
out=new ObjectOutputStream(sender.getOutputStream());
out.flush();
in=new ObjectInputStream(sender.getInputStream());
str=(String)in.readObject();
System.out.println("reciver > "+str);
System.out.println("Enter the data to send....");
packet=br.readLine();
n=packet.length();
do{
try{
if(i<n){
msg=String.valueOf(sequence);
msg=msg.concat(packet.substring(i,i+1));
}
else if(i==n){
msg="end";out.writeObject(msg);break;
}
out.writeObject(msg);
sequence=(sequence==0)?1:0;
out.flush();
System.out.println("data sent>"+msg);
ack=(String)in.readObject();
System.out.println("waiting for ack.....\n\n");
if(ack.equals(String.valueOf(sequence))){
i++;
System.out.println("receiver > "+" packet recieved\n\n");
}
else{
System.out.println("Time out resending data....\n\n");
sequence=(sequence==0)?1:0;
}
}catch(Exception e){}
}while(i<n+1);
System.out.println("All data sent. exiting.");
}catch(Exception e){}
finally{
try{
in.close();
out.close();
sender.close();
}
12
catch(Exception e){}
}
}
public static void main(String args[]){
Sender s=new Sender();
s.run();
}
}

RECEIVER PROGRAM

import java.io.*;
import java.net.*;
public class Reciever{
ServerSocket reciever;
Socket connection=null;
ObjectOutputStream out;
ObjectInputStream in;
String packet,ack,data="";
int i=0,sequence=0;
Reciever(){}
public void run(){
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
reciever = new ServerSocket(2004,10);
System.out.println("waiting for connection...");
connection=reciever.accept();
sequence=0;
System.out.println("Connection established :");
out=new ObjectOutputStream(connection.getOutputStream());
out.flush();
in=new ObjectInputStream(connection.getInputStream());
out.writeObject("connected .");
do{
try{
packet=(String)in.readObject();
if(Integer.valueOf(packet.substring(0,1))==sequence){
data+=packet.substring(1);
sequence=(sequence==0)?1:0;
System.out.println("\n\nreceiver >"+packet);
}
else
{
System.out.println("\n\nreceiver >"+packet +" duplicate data");
}
if(i<3){
out.writeObject(String.valueOf(sequence));i++;
}
else{
13
out.writeObject(String.valueOf((sequence+1)%2));
i=0;
}
}
catch(Exception e){}
}while(!packet.equals("end"));

System.out.println("Data recived="+data);
out.writeObject("connection ended .");
}
catch(Exception e){}
finally{
try{
in.close();
out.close();
reciever.close();
}
catch(Exception e){}
}
}
public static void main(String args[]){
Reciever s=new Reciever();
while(true){
s.run();
}
}
}

OUTPUT

SENDER OUTPUT

14
RECEIVER OUTPUT

RESULT:
Thus the program for implementation of stop and wait protocol was executed and the
output is verified successfully.

INFERENCE:

15
EXNO: 2 DATE:
STUDY OF SOCKET PROGRAMMING CLIENT-SERVER MODEL

(DATE AND TIME OF SERVER)


AIM:

To write a socket program to send Date and Time from Server to Client.

ALGORITHM:

TCP Date and Time Server

STEP 1: Include necessary header files to support functions for Socket


definitions, Sockettypes, Internet addresses, I/O functions, UNIX system calls.
STEP 2: Declare variables for Socket ID, Port number, Socket addresses, Character buffer
etc.
STEP 3: Create socket for server and bind socket with addresses.
STEP 4: Specify number of allowed connections.
STEP 5: Wait for connection.
STEP 6: Accept connection if any.
STEP 7: Retrieve information from Connected Socket tom display date and time.
STEP 8: Send the retrieved information to Connected Socket.
STEP 9: Close Connected Socket.

TCP Date and Time Client

1. Include necessary header files to support functions for Socket definitions,


Sockettypes, Internet addresses, I/O functions, UNIX system calls.
2. Declare variables for Socket ID, Port number, Socket addresses, Character buffer etc.
3. Create socket for client.
4. Connect client socket to the server socket addresses.
5. Give the request to the server to display the date and time.

6. Retrieve the information from server and display it.

16
SERVER PROGRAM

filename: tcpserver.java
import java.io.*;
import java.net.*;
import java.util.*;
class tcpserver
{
public static void main(String args[]) throws Exception
{
ServerSocket soc=new ServerSocket(10000);
System.out.println("Server is Ready......Waiting for Client Request ......");
while(true) {
Socket so=soc.accept();
OutputStream os=so.getOutputStream();
DataOutputStream dos=new DataOutputStream(os);
Date d=new Date();
dos.writeUTF(d.toString());
dos.close();
soc.close();
so.close();
}
}}

CLIENT PROGRAM
filename: tcpclient.java
import java.io.*;
import java.net.*;
class tcpclient
{
public static void main(String args[])throws Exception
{
try
{
Socket ss=new Socket(args[0],10000);
InputStream is=ss.getInputStream();
DataInputStream dis=new DataInputStream(is);
String info=dis.readUTF();
System.out.println("Message From Server");
System.out.println("Received at Client");
System.out.println("\t\t"+info);
dis.close();
ss.close();
}

catch(Exception e)
{
System.out.println("Inside Exception");
}
}}
17
OUTPUT:

CLIENT WINDOW

SERVER WINDOW

RESULT:

Thus the socket program to send Date and Time from Server to Client was executed and
output is verified successfully.

INFERENCE:

18
EXNO: 3A DATE:
IMPLEMENTATION OF ARP PROTOCOLS

AIM:

To write a java program for implementing the Address Resolution Protocol (ARP).

DESIGN APPROACH:

ARP is a low-level protocol used to bind a address dynamically. It allows a host to find a
physical address of a target host on the same physical network given only its IP address. ARP
hides the underlying network physical addressing. It can be thought of as aprt of physical network
system and not the internet protocols. ARP broadcasts special packets with destination‘s IP
address to all hosts. The destination host only will respond with physical address. When the
response is received, the sender use the physical address of destination host to send all the packets.
Hardware Type(16 bits): The type of interface the sender seeks an answer for.
Protocol Type(16 bits): The high level software address to be provided.
HLEN(8 bits)- Length of the arbitrary physical address.
PLEN(8 bits)-Length of the arbitrary protocol address
OPERATION(16 bits)-The specific type of operation required-ARP.request-1,
ARP.response-2
SENDER HA(6 octets)-The sender‘s actual hardware address scalable upto 6 bytes.
SENDER IP(4 octets)-The sender‘s IP address, always 32 bits.
TARGET HA(6 octets)-The destination node‘s HA, scalable to 6 bytes.
TARGET IP(4 octets)-The destination node‘s IP address, always 32 bits.

19
FUNCTIONS USED:

1. FileInputStream- input stream that reads from a file


FileInputStream(String filename)
2. FileOutputStream-output stream that writes to a file
FileOutputStream(String filename)
3. Runtime.getRuntime()- This static method gives a reference to the current Runtime
objects.
4. process exec(String program) throws IOException-executes the program specified by
the program as a separate process
5. BufferedReader- Buffered Input character stream
6. InputStreamReader- input stream that translates bytes to character.
7. PrintWriter-Character based class for console output.
8. System.in-To read input from console.

Implementation of ARP

import java.io.*;
import java.net.*;
class Corarp
{
public static void main(String args[])throws Exception
{
try
{
BufferedReader in=null; FileOutputStream fout;
FileInputStream fin;
Runtime r=Runtime.getRuntime(); Process p=r.exec("arp -a");
in=new BufferedReader(new InputStreamReader(p.getInputStream()));
fout=new FileOutputStream("out.data");
PrintWriter pw=new PrintWriter(fout,true);
String line;
while((line=in.readLine())!=null)
{
System.out.println(line);
pw.println(line);
}
fin=new FileInputStream("out.data");
BufferedReader bin1=new
BufferedReader(newInputStreamReader(System.in));
BufferedReader bin=new BufferedReader(new InputStreamReader(fin));

20
String l,l1,l2;
l1=bin1.readLine();
l1=" "+l1;
l=bin.readLine();
while((l=bin.readLine())!=null)
{
if(l.startsWith(l1))
{
l2=l.substring(25,41);
System.out.println(l2);
break;
}
}
in.close();
}
catch(IOException e)
{
}
}
}

21
OUTPUT:

RESULT:

Thus the program to implement Address Resolution Protocol was executed and the
output was verified successfully.

INFERENCE:

22
EXNO: 3B DATE:
IMPLEMENTATION OF RARP PROTOCOLS

AIM:

To write a java program for implementing the Reverse Address Resolution Protocol
(RARP)

DESIGN APPROACH:

RARP does the reverse operation of ARP, when we give the Physical address RARP
provides the corresponding IP address

Hardware Type(16 bits): The type of interface the sender seeks an answer for.
Protocol Type(16 bits): The high level software address to be provided.
HLEN(8 bits)- Length of the arbitrary physical address.
PLEN(8 bits)-Length of the arbitrary protocol address
OPERATION(16 bits)-The specific type of operation required-ARP.request-1,
ARP.response-2
SENDER HA(6 octets)-The sender‘s actual hardware address scalable upto 6 bytes.
SENDER IP(4 octets)-The sender‘s IP address, always 32 bits.
TARGET HA(6 octets)-The destination node‘s HA, scalable to 6 bytes.

TARGET IP(4 octets)-The destination node‘s IP address, always 32 bits.

23
FUNCTIONS USED:

1. FileInputStream- input stream that reads from a file


FileInputStream(String filename)
2. FileOutputStream-output stream that writes to a file
FileOutputStream(String filename)
3. Runtime.getRuntime()- This static method gives a reference to the current Runtime
objects.
4. process exec(String program) throws IOException-executes the program specified by
the program as a separate process
5. BufferedReader- Buffered Input character stream
6. InputStreamReader- input stream that translates bytes to character.
7. PrintWriter-Character based class for console output.
8. System.in-To read input from console.
9. String substring(int,int)- gives a part of string, starting from the position of first
parameter, fill the position of the second parameter.
10. PrintWriterObject.println(string)- writes string to the file.

PROGRAM:
import java.io.*;
import java.net.*;
class Corrarp
{
public static void main(String args[])throws Exception
{
try
{
BufferedReader in=null;
FileOutputStream fout;
FileInputStream fin;
Runtime r=Runtime.getRuntime();
Process p=r.exec("arp -a");
in=new BufferedReader(new InputStreamReader(p.getInputStream()));
fout=new FileOutputStream("out.data");
PrintWriter pw=new PrintWriter(fout,true);
String line;
while((line=in.readLine())!=null)
{
System.out.println(line);
pw.println(line);
}
fin=new FileInputStream("out.data");
BufferedReader bin1=new BufferedReader(new
InputStreamReader(System.in));
BufferedReader bin=new BufferedReader(new InputStreamReader(fin));
String l,l1,l2;
l1=bin1.readLine();
24
l=bin.readLine();
while((l=bin.readLine())!=null)

{
if(l.startsWith("Int")||l.startsWith(" Int"))
{
continue a;
}
l2=l.substring(24,41);
if(l2.equals(l1))
{
System.out.println(l); break;
}
}
in.close();
}
catch(IOException e)
{
}
}
}

25
OUTPUT:

RESULT:

Thus the program for implementing Reverse Address Resolution Protocol was executed
and the output is verified successfully.

INFERENCE:

26
EXNO: 4A DATE:
IMPLEMENTATION OF PING COMMAND

AIM:

To write a program for implementing the simulating ping command.

DESIGN APPROACH:

Runtime- class that encapsulates the runtime environment

Runtime.getRuntime()-static method that gives reference to a current runtime object

Process exec(string prgname)throws IOException

This method executes the program specified by the ‘prgname’ as a separate process. An
object of type process is returned that describes the new process.

The ping command gives the following informations:

• IP address
• Number of bytes of data sent
• Round Trip Time measured in millisec
• TTL(Time to Live)- this value decreases by one when it passes through each node,server
or router, when it drops to zero, the packet is discarded.

ALGORITHM:

Step1: Get the reference to the current runtime object


Step2: Execute the program with Tracert as a separate process
Step3: Check for reply
Step4: Display the status of Tracert
Step5: Close the connection

27
PROGRAM:

import java.net.*;
import java.io.*;
class ping
{
public static void main(String a[]) throws Exception
{
BufferedReader in =null;
try
{
Runtime r = Runtime.getRuntime();
Process p = r.exec("ping 132.147.205.18");
if(p==null)
{
System.out.println("There is no reply");
}
in = new BufferedReader(new
InputStreamReader(p.getInputStream()));
String line;
while((line = in.readLine())!=null)
{
System.out.println(line);
}
in.close();
}
catch(IOException e)
{
System.out.println(e.toString());
}
}
}

28
OUTPUT:

RESULT:

Thus the program to implement ping command was executed and the output is verified
successfully.

INFERENCE:

29
EXNO: 4B DATE:
IMPLEMENTATION OF TRACEROUTE COMMAND
AIM:

To write a program for implementing the Trace route command.

DESIGN APPROACH:

In computing, traceroute is a computer network diagnostic tool for displaying the route
and measuring transit delays of packets across an Internet Protocol (IP) network. The history of
the route is recorded as the round-trip times of the packets received from each successive host
(remote node) in the route (path); the sum of the mean times in each hop indicates the total time
spent to establish the connection. Traceroute proceeds unless all (three) sent packets are lost more
than twice, then the connection is lost and the route cannot be evaluated. Ping, on the other hand,
only computes the final round-trip times from the destination point.

ALGORITHM:

STEP 1: Get the reference to the current runtime object


STEP 2: Execute the program with Tracert as a separate process
STEP 3: Check for reply
STEP 4: Display the status of Tracert
STEP 5: Close the connection

PROGRAM:

import java.net.*;
import java.io.*;
class ping
{
public static void main(String a[]) throws Exception
{
BufferedReader in =null; try
{
Runtime r = Runtime.getRuntime();
Process p = r.exec("tracert 132.147.205.18");
if(p==null)
{
System.out.println("There is no reply");
}
in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while((line = in.readLine())!=null)
{

30
System.out.println(line);
}
in.close();
}
catch(IOException e)
{
System.out.println(e.toString());
}
}
}

OUTPUT:

RESULT:

Thus the program for implement the TRACEROUTE command was executed and the output
was verified successfully.

INFERENCE:

31
EXNO: 5 DATE:
UPLOADING AND DOWNLOADING IMAGE FILE USING
SOCKET PROGRAMMING

AIM:

To write a java program to create socket for uploading and downloading an image file.

ALGORITHM:

STEP 1: Start the program.


STEP 2: Get the frame size from the user
STEP 3: To create the frame based on the user request.
STEP 4: To send frames to server from the client side.
STEP 5: If your frames reach the server, it will send ACK signal to client
otherwise it willsend NACK signal to client.
STEP 6: Stop the program
PROGRAM:

CLIENT

import javax.swing.*;
import java.net.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Client
{
public static void main(String args[]) throws Exception
{
Socket soc;
BufferedImage img = null; soc=new Socket("localhost",4000);
System.out.println("Client is running. ");
try
{
System.out.println("Reading image from disk. ");
img = ImageIO.read(new File("digital_image_processing.jpg"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, "jpg", baos);

32
baos.flush();
byte[] bytes = baos.toByteArray();
baos.close();
System.out.println("Sending image to server. ");
OutputStream out = soc.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
dos.writeInt(bytes.length);
dos.write(bytes, 0, bytes.length);
System.out.println("Image sent to server. ");
dos.close();
out.close();
}
catch (Exception e)
{
System.out.println("Exception: " + e.getMessage());
soc.close();
}
soc.close();
}
}

SERVER

import java.net.*;
import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.*;
class Server
{
public static void main(String args[]) throws Exception
{
ServerSocket server=null;
Socket socket;
server=new ServerSocket(4000);
System.out.println("Server Waiting for image");
socket=server.accept();
System.out.println("Client connected.");
InputStream in = socket.getInputStream();
DataInputStream dis = new DataInputStream(in);
int len = dis.readInt();
System.out.println("Image Size: " + len/1024 + "KB");
byte[] data = new byte[len];
dis.readFully(data);
dis.close();
in.close();
InputStream ian = new ByteArrayInputStream(data);
BufferedImage bImage = ImageIO.read(ian); JFrame
33
f = new JFrame("Server");
ImageIcon icon = new ImageIcon(bImage);
JLabel l = new JLabel();
l.setIcon(icon);
f.add(l);
f.pack();
f.setVisible(true);
}}

34
OUTPUT

CLIENT

SERVER

RESULT:

Thus the program for HTTP web client program to download a web page using TCP
socket was executed and the output is verified successfully.

INFERENCE:

35
EXNO: 6A DATE:
APPLICATIONS USING TCP SOCKETS

IMPLEMENTATION OF ECHO

AIM:
To write a Network Socket program for implementing the echo operation.

ALGORITHM:

TCP Echo Server

STEP 1: Include necessary header files to support functions for Socket


definitions, Socket types, Internet addresses, I/O functions, UNIX
systemcalls.
STEP 2: Declare variables for Socket ID,Port number,Socket addresses,
Character buffer etc.
STEP 3: Create socket for server and bind socket with addresses.
STEP 4: Specify number of allowed connections.
STEP 5: Wait for connection.
STEP 6: Accept connection if any.
STEP 7: Retrieve information from Connected Socket.
STEP 8: Echo retrieved information to Connected Socket.
STEP 9: Close Connected Socket.

TCP Echo Client

STEP 1: Include necessary header files to support functions for Socket


definitions, Socket types, Internet addresses, I/O functions, UNIX
systemcalls.
STEP 2: Declare variables for Socket ID, Port number, Socket addresses, Character
buffer etc.
STEP 3: Create socket for client.
STEP 3: Connect client socket to the server socket addresses.
STEP 4: Give message to be echoed.
1. STEP 4: Retrieve echoed information from server and display it.

36
SERVER PROGRAM:

import java.io.*;
import java.net.*;
import java.lang.String.*;
public class Secho
{
public static void main(String args[]) throws Exception
{
ServerSocket ss =new ServerSocket(123);
Socket s=ss.accept();
DataInputStream in= new DataInputStream(s.getInputStream());
DataOutputStream out=new DataOutputStream(s.getOutputStream());
String str;
System.out.println("\nSERVER SIDE!...");
while(true)
{
str=in.readLine();
out.writeBytes(str+"\n");
System.out.println("Msg from Client");
System.out.println(str+"\n");
}
}
}

CLIENT PROGRAM:

import java.io.*;
import java.net.*;
import java.lang.String.*;
public class Cecho
{
public static void main(String args[]) throws Exception
{
DataInputStream in=new DataInputStream (System.in);
Socket s=new Socket("LocalHost",123);
DataInputStream inecho=new DataInputStream(s.getInputStream());
DataOutputStream out=new DataOutputStream(s.getOutputStream());
String str;
System.out.println("\nCLIENT SIDE!...\nType EXIT TO QUIT\nEnter Client Msg");
while((str=in.readLine())!=null)
{
out.writeBytes(str+"\n");
if(str.equals("exit"))
{
out.writeBytes("\nClient Terminated");
break;
}

37
else
{
System.out.println("\nEcho From Server");
System.out.print(str+"\n");
System.out.println("\nCLIENT SIDE!...\nEnter Client Msg")
}

}}

OUTPUT::

SERVER:

38
CLIENT:

RESULT:
Thus, the program for implementation of ECHO was executed and output is verified
successfully.

INFERENCE:

39
EXNO: 6B DATE:
CHAT APPLICATION

AIM:
To write a network program for implementing chat using TCP socket.

ALGORITHM:

STEP 1: Client sends the request to server


STEP 2: Server runs the request and the connection with the client that has requested the server.
STEP 3: The client sends the message to server.
STEP 4: The server process it and it is displayed (i.e.,) replier by sending the message to
clientalso displayed.
STEP 5: Stop the program.

SERVER PROGRAM:

import java.io.*;
import java.net.*;
public class chatserver
{
public static void main(String args[])throws Exception
{
DataInputStream din=null;
DataOutputStream dout=null;
Socket c=null;
ServerSocket m=null;
DataInputStream stdin=new DataInputStream(System.in);
try
{
m=new ServerSocket(68);
c=m.accept();
din=new DataInputStream(c.getInputStream());
dout=new DataOutputStream(c.getOutputStream());
}
catch(Exception e)
{
}
while(c!=null)
{
String m2; System.out.println("Server");
while(true)
{
String m1=din.readLine();

40
System.out.println("Message from client.."+m1);
System.out.println("\n\n Enter the message...");
m2=stdin.readLine();
dout.writeBytes(""+m2);
dout.writeBytes("\n");
}
}
din.close();
dout.close();
c.close();
m.close();
}
}

CLIENT PROGRAM:

import java.io.*;
import java.net.*;
public class chatclient
{
public static void main(String args[])throws Exception
{
Socket c=null;
DataInputStream uin=null;
DataInputStream din=null;
DataOutputStream dout=null;
try
{
c=new Socket("localhost",68);
uin=new DataInputStream(System.in);
din=new DataInputStream(c.getInputStream());
dout=new DataOutputStream(c.getOutputStream());
}
catch(Exception e)
{
}
if(c!=null)
{
String inp;
System.out.println("Enter the message:");
while((inp=uin.readLine())!=null)
{
dout.writeBytes(""+inp);
dout.writeBytes("\n");
System.out.println("Echoed message from server.."+din.readLine());
System.out.println("Enter ur message:");
}
}

41
din.close();
dout.close();
c.c lose();
}
}

OUTPUT:
CLIENT

SERVER:

RESULT:
Thus the program for CHAT APPLICATION was executed and output is verified
successfully.
INFERENCE:

42
EXNO: 6C Date:
FILE TRANSFER USING TCP SOCKET

AIM:

To write a Java program to perform file transfer using TCP sockets

ALGORITHM:

SERVER:

STEP 1: Create a server socket


STEP 2: Create a new file
STEP 3: Get the input from the file using FileInputStream
STEP 4: Copy the contents of the file to the FileOutputStream
STEP 5: Close the socket
STEP 6: Stop the program

CLIENT:

STEP 1: Create a socket


STEP 2: Get the input from the socket using InputStream
STEP 3: Copy the contents of the file to the FileOutputStream
STEP 4: Print the contents of the file
STEP 5: Close the socket

STEP 6: Stop the program

PROGRAM

FILE CLIENT

import java.io.*;
import java.net.*;
import java.util.*;
class Clientfile
{
public static void main(String args[])
{
try
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
Socket clsct=new Socket("127.0.0.1",139);

43
DataInputStream din=new DataInputStream(clsct.getInputStream());
DataOutputStream dout=new DataOutputStream(clsct.getOutputStream());
System.out.println("Enter the file name:");
String str=in.readLine();
dout.writeBytes(str+'\n');
System.out.println("Enter the new file name:");
String str2=in.readLine();
String str1,ss;
FileWriter f=new FileWriter(str2);
char buffer[];
while(true)
{
str1=din.readLine();
if(str1.equals("-1")) break;
System.out.println(str1);
buffer=new char[str1.length()];
str1.getChars(0,str1.length(),buffer,0);
f.write(buffer);
}
f.close();
clsct.close();
}
catch (Exception e)
{
System.out.println(e);
}}}

FILE SERVER

import java.io.*;
import java.net.*;
import java.util.*;
class Serverfile
{
public static void main(String args[])
{
try
{
ServerSocket obj=new ServerSocket(139);
while(true)
{
Socket obj1=obj.accept();
DataInputStream din=new DataInputStream(obj1.getInputStream());
DataOutputStream dout=new DataOutputStream(obj1.getOutputStream());
String str=din.readLine();
FileReader f=new FileReader(str);
BufferedReader b=new BufferedReader(f);
String s;

44
while((s=b.readLine())!=null)
{
System.out.println(s);
dout.writeBytes(s+'\n');
}
f.c lose();
dout.writeBytes("-1\n");
}}
catch(Exception e)
{ System.out.println(e);}
}}

OUTPUT:

CLIENT

45
SERVER

RESULT:

Thus the program for FILE TRANSFER was executed and the output is verified
successfully.

INFERENCE:

46
EXNO: 7 DATE:
IMPLEMENTATION OF DNS USING UDP SOCKETS

AIM:

To implement a DNS server and client in java using UDP sockets.

ALGORITHM:

SERVER

STEP 1: Create an array of hosts and its ip address in another array


STEP 2: Create a datagram socket and bind it to a port
STEP 3: Create a datagram packet to receive client request
STEP 4: Read the domain name from client to be resolved
STEP 5: Lookup the host array for the domain name
STEP 6: If found then retrieve corresponding address
STEP 7: Create a datagram packet and send ip address to client
STEP 8: Repeat steps 3-7 to resolve further requests from clients
STEP 9: Close the server socket
STEP 10: Stop

CLIENT

STEP 1: Create a datagram socket


STEP 2: Get domain name from user
STEP 3: Create a datagram packet and send domain name to the server
STEP 4: Create a datagram packet to receive server message5. Read server's response
STEP 5: If ip address then display it else display "Domain does not exist"
STEP 6: Close the client socket

STEP 7: Stop

47
PROGRAM

// UDP DNS Server -- udpdnsserver.java

import java.io.*;
import java.net.*;
public class udpdnsserver
{
private static int indexOf(String[] array, String str)
{
str = str.trim();
for (int i=0; i < array.length; i++)
{
if (array[i].equals(str))
return i;
}
return -1;
}
public static void main(String arg[])throws IOException
{
String[] hosts = {"yahoo.com", "gmail.com","cricinfo.com", "facebook.com"};
String[] ip = {"68.180.206.184", "209.85.148.19","80.168.92.140",
"69.63.189.16"};
System.out.println("Press Ctrl + C to Quit");
while (true)
{
DatagramSocket serversocket=new DatagramSocket(1362);
byte[] senddata = new byte[1021];
byte[] receivedata = new byte[1021];
DatagramPacket recvpack = new DatagramPacket(receivedata,
receivedata.length);
serversocket.receive(recvpack);
String sen = new String(recvpack.getData());
InetAddress ipaddress = recvpack.getAddress();
int port = recvpack.getPort();
String capsent;
System.out.println("Request for host " + sen);
if(indexOf (hosts, sen) != -1)
capsent = ip[indexOf (hosts, sen)];
else
capsent = "Host Not Found";
senddata = capsent.getBytes();
DatagramPacket pack = new DatagramPacket(senddata,
senddata.length,ipaddress,port);
serversocket.send(pack);
serversocket.close();
}
}
}

48
//UDP DNS Client -- udpdnsclient.java

import java.io.*;
import java.net.*;
public class udpdnsclient
{
public static void main(String args[])throws IOException
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
DatagramSocket clientsocket = new DatagramSocket();
InetAddress ipaddress;
if (args.length == 0)
ipaddress = InetAddress.getLocalHost();
else
ipaddress = InetAddress.getByName(args[0]);
byte[] senddata = new byte[1024];
byte[] receivedata = new byte[1024];
int portaddr = 1362;
System.out.print("Enter the hostname : ");
String sentence = br.readLine();
Senddata = sentence.getBytes();
DatagramPacket pack = new DatagramPacket
(senddata,senddata.length, ipaddress,portaddr);
clientsocket.send(pack);
DatagramPacket recvpack =new
DatagramPacket(receivedata,receivedata.length);
clientsocket.receive(recvpack);
String modified = new String(recvpack.getData());
System.out.println("IP Address: " + modified);
clientsocket.close();
}

OUTPUT

SERVER

$ javac udpdnsserver.java

$ java udpdnsserver

Press Ctrl + C to Quit

Request for host yahoo.com

Request for host cricinfo.com

Request for host youtube.com

49
CLIENT

$ javac udpdnsclient.java

$ java udpdnsclient

Enter the hostname : yahoo.com

IP Address: 68.180.206.184

$ java udpdnsclient

Enter the hostname : cricinfo.com

IP Address: 80.168.92.140

$ java udpdnsclient

Enter the hostname : youtube.com

IP Address: Host Not Found

RESULT:

Thus the program for implementation of DNS was executed and the output is
verified successfully.

INFERENCE:

50
EXNO: 8 DATE:
STUDY OF NETWORK SIMULATOR

AIM:

To study the network simulator and to simulate the congestion control mechanisms.

PROCEDURE:
An NS script starts with making a Simulator object instance.

• set ns [new Simulator]: generates an NS simulator object instance, and assigns it to


variable ns (italics is used for variables and values in this section). What this line does is
the following:

o Initialize the packet format (ignore this for now)


o Create a scheduler (default is calendar scheduler)
o Select the default address format (ignore this for now)

The "Simulator" object has member functions that do the following:

o Create compound objects such as nodes and links (described later)


o Connect network component objects created (ex. attach-agent)
o Set network component parameters (mostly for compound objects)
o Create connections between agents (ex. make connection between a "tcp"
and "sink")
o Specify NAM display options etc.
Most of member functions are for simulation setup (referred to as plumbing
functions in the Overview section) and scheduling, however some of them are
for the NAM display. The "Simulator" object member function implementations
are located in the "ns-2/tcl/lib/ns-lib.tcl" file.

• $ns color fid color: is to set color of the packets for a flow specified by the flow id(fid).
This member function of "Simulator" object is for the NAM display, and has no effect
on the actual simulation.

• $ns namtrace-all file-descriptor: This member function tells the simulator to record
simulation traces in NAM input format. It also gives the file name that the trace will be
written to later by the command $ns flush-trace. Similarly, the member function trace-
all is for recording the simulation trace in a general format.

• proc finish {}: is called after this simulation is over by the command $ns at 5.0 "finish".
In this function, post-simulation processes are specified.

• set n0 [$ns node]: The member function node creates a node. A node in NS is compound
object made of address and port classifiers (described in a later section). Users can create
a node by separately creating an address and a port classifier objects and connecting
them together. However, this member function of Simulator object makes the job easier.
To see how a node is created, look at the files: "ns-2/tcl/libs/ns- lib.tcl" and "ns-
2/tcl/libs/ns-node.tcl".
51
• $ns duplex-link node1 node2 bandwidth delay queue-type: creates two simplex linksof
specified bandwidth and delay, and connects the two specified nodes. In NS, theoutput
queue of a node is implemented as a part of a link, therefore users should specify the
queue-type when creating links. In the above simulation script, DropTail queue is used.
If the reader wants to use a RED queue, simply replace the word DropTail with RED.
The NS implementation of a link is shown in a later section. Like a node, a link is a
compound object, and users can create its sub-objects and connect them and the nodes.
Link source codes can be found in "ns-2/tcl/libs/ns-lib.tcl" and "ns-2/tcl/libs/ns-link.tcl"
files. One thing to note is that you can insert error modules in a link component to
simulate a lossy link (actually users can make and insert any network objects). Refer to
the NS documentation to find out how to do this.

• $ns queue-limit node1 node2 number: This line sets the queue limit of the two simplex
links that connect node1 and node2 to the number specified. At this point, the authors
do not know how many of these kinds of member functions of Simulator objects are
available and what they are. Please take a look at "ns-2/tcl/libs/ns-lib.tcl" and "ns-
2/tcl/libs/ns-link.tcl", or NS documentation for more information.

• $ns duplex-link-op node1 node2 ...: The next couple of lines are used for the NAM
display. To see the effects of these lines, users can comment these lines out and try the
simulation.
Now that the basic network setup is done, the next thing to do is to setup traffic agents such as
TCP and UDP, traffic sources such as FTP and CBR, and attach them to nodes and agents
respectively.

• set tcp [new Agent/TCP]: This line shows how to create a TCP agent. But in general, users can
create any agent or traffic sources in this way. Agents and traffic sources are in fact basic objects
(not compound objects), mostly implemented in C++ and linked to OTcl. Therefore, there are
no specific Simulator object member functions that create these object instances. To create
agents or traffic sources, a user should know the class names these objects (Agent/TCP,
Agnet/TCPSink, Application/FTP and so on). This information can be found in the NS
documentation or partly in this documentation. But one shortcut is to look at the "ns-
2/tcl/libs/ns-default.tcl" file. This file contains the default configurable parameter value settings
for available network objects. Therefore, it works as a good indicator of what kind of network
objects are available in NS and what are the configurable parameters.

• $ns attach-agent node agent: The attach-agent member function attaches an agent object
created to a node object. Actually, what this function does is call the attach member
function of specified node, which attaches the given agent to itself. Therefore, a user can
do the same thing by, for example, $n0 attach $tcp. Similarly, each agent object has a
member function attach-agent that attaches a traffic source object to itself.

• $ns connect agent1 agent2: After two agents that will communicate with each other are
created, the next thing is to establish a logical network connection between them. This
line establishes a network connection by setting the destination address to each others'
network and port address pair.

Assuming that all the network configuration is done, the next thing to do is write a simulation
scenario (i.e. simulation scheduling). The Simulator object has many scheduling member
52
functions. However, the one that is mostly used is the following:

• $ns at time "string": This member function of a Simulator object makes the scheduler
(scheduler_ is the variable that points the scheduler object created by [new Scheduler]
command at the beginning of the script) to schedule the execution of the specified string
at given simulation time. For example, $ns at 0.1 "$cbr start" will make the scheduler
call a start member function of the CBR traffic source object, which starts the CBR to
transmit data. In NS, usually a traffic source does not transmit actual data, but it notifies
the underlying agent that it has some amount of data to transmit, and the agent, just
knowing how much of the data to transfer, creates packets and sends them.

After all network configuration, scheduling and post-simulation procedure specifications are
done, the only thing left is to run the simulation. This is done by $ns run.

53
PROGRAM:

#Create a simulator object


set ns [new Simulator]

#Define different colors for data flows (for NAM)


$ns color 1 Blue
$ns color 2 Red

#Open the NAM trace file


set nf [open out.nam w]
$ns namtrace-all $nf

#Define a 'finish' procedure


proc finish {} {
global ns nf
$ns flush-trace
#Close the NAM trace file
close $nf
#Execute NAM on the trace file
exec nam out.nam &
exit 0
}

#Create four nodes


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

#Create links between the nodes


$ns duplex-link $n0 $n2 2Mb 10ms DropTail
$ns duplex-link $n1 $n2 2Mb 10ms DropTail
$ns duplex-link $n2 $n3 1.7Mb 20ms DropTail

#Set Queue Size of link (n2-n3) to 10


$ns queue-limit $n2 $n3 10

#Give node position (for NAM)


$ns duplex-link-op $n0 $n2 orient right-down
$ns duplex-link-op $n1 $n2 orient right-up
$ns duplex-link-op $n2 $n3 orient right

#Monitor the queue for link (n2-n3). (for NAM)


$ns duplex-link-op $n2 $n3 queuePos 0.5
#Setup a TCP connection
set tcp [new Agent/TCP]
$tcp set class_ 2
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink]
$ns attach-agent $n3 $sink
54
$ns connect $tcp $sink
$tcp set fid_ 1

#Setup a FTP over TCP connection


set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ftp set type_ FTP

#Setup a UDP connection


set udp [new Agent/UDP]
$ns attach-agent $n1 $udp
set null [new Agent/Null]
$ns attach-agent $n3 $null
$ns connect $udp $null
$udp set fid_ 2

#Setup a CBR over UDP connection set


cbr [new Application/Traffic/CBR]
$cbr attach-agent $udp
$cbr set type_ CBR
$cbr set packet_size_ 1000
$cbr set rate_ 1mb
$cbr set random_ false

#Schedule events for the CBR and FTP agents


$ns at 0.1 "$cbr start"
$ns at 1.0 "$ftp start"
$ns at 4.0 "$ftp stop"
$ns at 4.5 "$cbr stop"

#Detach tcp and sink agents (not really necessary)


$ns at 4.5 "$ns detach-agent $n0 $tcp ; $ns detach-agent $n3 $sink"

#Call the finish procedure after 5 seconds of simulation time


$ns at 5.0 "finish"

#Print CBR packet size and interval


puts "CBR packet size = [$cbr set packet_size_]"
puts "CBR interval = [$cbr set interval_]"

#Run the simulation


$ns run

55
OUTPUT

RESULT:

Thus the NS2 simulation for congestion control was successfully completed.

INFERENCE:

56
EXNO: 9A DATE:

STUDY OF TCP PERFORMANCE USING SIMULATION TOOL

AIM:

To simulate the TCP Performance using NS2

ALGORITHM:

STEP 1: Create a simulator object


STEP 2: Define different flows for data flows
STEP 3: Trace all events in a nam file and text file
STEP 4: Create source nodes (s1, s2, s3), gateway (G) and receiver (r)
STEP 5: Describe their layout topology
STEP 6: Specify the link between nodes
STEP 7: Define the queue size between nodes G and r as 5
STEP 8: Monitor queue on all links vertically 90°
STEP 9: Create TCP agents tcp1, tcp2, tcp3 and attach it to nodes s1, s2 and s3
respectively
STEP 10: Create three TCP sinks and attach it to node r
STEP 11: Connect traffic sources to the sink
STEP 12: Create FTP agents ftp1, ftp2, ftp3 and attach it to tcp1, tcp2 and tcp3
Respectively Label the nodes at start time
STEP 13: Schedule ftp1, ftp2, ftp3 to start at 0.1 and stop at 5.0seconds
STEP 14: Call finish procedure at 5.25 seconds
STEP 15: Run the simulation
STEP 16: Execute NAM on the trace file
STEP 17: Observe the simulated events on the NAM editor and packet flow on link G to r
STEP 18: View the trace file and analyse the events

STEP 19: Stop

57
PROGAM:

#Study of TCP performance - TCP.tcl

#Create a simulator object


set ns [new Simulator]

#Open trace files


set f [open droptail-queue-out.tr w]
$ns trace-all $f

#Open the nam trace file


set nf [open droptail-queue-out.nam w]
$ns namtrace-all $nf

#s1, s2 and s3 act as sources. set s1 [$ns node]


set s2 [$ns node] set s3 [$ns n ode]
#G acts as a gateway set G [$ns node]
#r acts as a receiver set r [$ns node]
#Define different colors for data flows
$ns color 1 red
$ns color 2 SeaGreen
$ns color 3 blue

#Create links between the nodes


$ns duplex-link $s1 $G 6Mb 10ms DropTail
$ns duplex-link $s2 $G 6Mb 10ms DropTail
$ns duplex-link $s3 $G 6Mb 10ms DropTail
$ns duplex-link $G $r 3Mb 10ms DropTail

#Define the layout of the nodes


$ns duplex-link-op $s1 $G orient right-up
$ns duplex-link-op $s2 $G orient right
$ns duplex-link-op $s3 $G orient right-down
$ns duplex-link-op $G $r orient right

#Define the queue size for the link between node G and r
$ns queue-limit $G $r 5

#Monitor the queues for links vertically


$ns duplex-link-op $s1 $G queuePos 0.5
$ns duplex-link-op $s2 $G queuePos 0.5
$ns duplex-link-op $s3 $G queuePos 0.5
$ns duplex-link-op $G $r queuePos 0.5

#Create a TCP agent and attach it to node s1 set tcp1 [new Agent/TCP/Reno]
$ns attach-agent $s1 $tcp1
$tcp1 set window_ 8
$tcp1 set fid_1

58
#Create a TCP agent and attach it to node s2 set tcp2 [new Agent/TCP/Reno]
$ns attach-agent $s2 $tcp2
$tcp2 set window_ 8
$tcp2 set fid_2

#Create a TCP agent and attach it to node s3 set tcp3 [new Agent/TCP/Reno]
$ns attach-agent $s3 $tcp3
$tcp3 set window_ 4
$tcp3 set fid_3

#Create TCP sink agents and attach them to node r


set sink1 [new Agent/TCPSink]
set sink2 [new Agent/TCPSink]
set sink3 [new Agent/TCPSink]
$ns attach-agent $r $sink1
$ns attach-agent $r $sink2
$ns attach-agent $r $sink3
#Connect the traffic sources with the traffic sinks
$ns connect $tcp1 $sink1
$ns connect $tcp2 $sink2
$ns connect $tcp3 $sink3

#Create FTP applications and attach them to agents


set ftp1 [new Application/FTP]
$ftp1 attach-agent $tcp1
set ftp2 [new Application/FTP]
$ftp2 attach-agent $tcp2
set ftp3 [new Application/FTP]
$ftp3 attach-agent $tcp3

#Define a 'finish' procedure proc finish {}


{
global ns
$ns flush-trace
puts "running nam. "
exec nam -a droptail-queue-out.nam & exit 0
}

#Define label for nodes


$ns at 0.0 "$s1 label Sender1"
$ns at 0.0 "$s2 label Sender2"
$ns at 0.0 "$s3 label Sender3"
$ns at 0.0 "$G label Gateway"
$ns at 0.0 "$r label Receiver"

#Schedule ftp events


$ns at 0.1 "$ftp1 start"
$ns at 0.1 "$ftp2 start"
$ns at 0.1 "$ftp3 start"
$ns at 5.0 "$ftp1 stop"
59
$ns at 5.0 "$ftp2 stop"
$ns at 5.0 "$ftp3 stop"

#Call finish procedure after 5 seconds of simulation time


$ns at 5.25 "finish"

#Run the simulation


$ns run

OUTPUT

$ ns TCP.tcl

60
RESULT:

Thus the simulation of TCP performance was done using NS2 successfully.

INFERENCE:

61
EXNO: 9B DATE:

STUDY OF UDP PERFORMANCE USING SIMULATION TOOL

AIM:

To study the performance of UDP by simulating a simple network

ALGORITHM:

STEP 1: Create a simulator object


STEP 2: Define different color for data flows
STEP 3: Trace all events in a nam file.
STEP 4: Create four nodes n0, n1, n2 and n3
STEP 5: Describe their layout topology
STEP 6: Specify the link capacity betweennodes
STEP 7: Monitor queue on the link n2 to n3 vertically 90°
STEP 8: Create a UDP agents udp0, udp1 and attach it to nodes n0 and n1 respectively
STEP 9: Create a CBR traffic cbr0, cbr1 and attach it to udp0 and udp1 respectively
STEP 10: Create a traffic sink and attach it to node n3
STEP 11: Connect sources to the sink
STEP 12: Label the nodes
STEP 13: Schedule cbr0 to start at 0.5 and stop at 4.5 seconds
STEP 14: Schedule cbr1 to start at 1.0 and stop at 4.0 seconds
STEP 15: Call finish procedure at 5.0 seconds
STEP 16: Run the simulation
STEP 17: Execute NAM on the trace file
STEP 18: Observe simulated events on the NAM and packet flow on link n2 to n3
STEP 19: Stop

62
PROGRAM

#Study of UDP performance - UDP.tcl

#Create a simulator object


set ns [new Simulator]

#Define different colors for data flows


$ns color 1 Blue
$ns color 2 Red

#Open the nam trace file set nf [open out.nam w]


$ns namtrace-all $nf

#Create four nodes


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

#Create links between the nodes


$ns duplex-link $n0 $n2 1Mb 10ms DropTail
$ns duplex-link $n1 $n2 1Mb 10ms DropTail
$ns duplex-link $n3 $n2 1Mb 10ms SFQ

#Specify layout of nodes


$ns duplex-link-op $n0 $n2 orient right-down
$ns duplex-link-op $n1 $n2 orient right-up
$ns duplex-link-op $n2 $n3 orient right

#Monitor the queue for the link 2—3 vertically


$ns duplex-link-op $n2 $n3 queuePos 0.5

#Create a UDP agent and attach it to node n0


set udp0 [new Agent/UDP]
$udp0 set class_ 1
$ns attach-agent $n0 $udp0

# Create a CBR traffic source and attach it to udp0


set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0

#Create a UDP agent and attach it to node n1 set udp1 [new Agent/UDP]
$udp1 set class_ 2
$ns attach-agent $n1 $udp1

63
# Create a CBR traffic source and attach it to udp1
set cbr1 [new Application/Traffic/CBR]
$cbr1 set packetSize_ 500
$cbr1 set interval_ 0.005
$cbr1 attach-agent $udp1

#Create a Null agent (a traffic sink) and attach it to node n3


set null0 [new Agent/Null]
$ns attach-agent $n3 $null0

#Connect traffic sources with the traffic sink


$ns connect $udp0 $null0
$ns connect $udp1 $null0

#Define finish procedure proc finish {}


{
global ns nf
$ns flush-trace

#Close the trace file close $nf

#Execute nam on the trace file exec nam -a out.nam & exit
0
}

#Define label for nodes


$ns at 0.0 "$n0 label Sender1"
$ns at 0.0 "$n1 label Sender2"
$ns at 0.0 "$n2 label Router"
$ns at 0.0 "$n3 label Receiver"

#Schedule events for the CBR agents


$ns at 0.5 "$cbr0 start"
$ns at 1.0 "$cbr1 start"
$ns at 4.0 "$cbr1 stop"
$ns at 4.5 "$cbr0 stop"

#Call finish procedure after 5 seconds of simulation time


$ns at 5.0 "finish"

#Run the simulation


$ns run

64
OUTPUT

$ ns UDP.tcl

RESULT:

Thus the simulation of UDP performance was done using NS2 successfully.

INFERENCE:

65
EXNO: 10A DATE:

SIMULATION OF DISTANCE VECTOR ROUTING

AIM:

To simulate the distance vector routing algorithm using NS2.

ALGORITHM:

STEP 1: Create a simulator object.


STEP 2: Define different colors for different data flows.
STEP 3: Open a nam trace file and define finish procedure then close the
trace file,and execute nam on trace file.
Create n number of nodes using for loop.
Create duplex links between the nodes.
Setup UDP Connection between n(0) and n(5).
Setup another UDP connection between n(1) and n(5).
Apply CBR Traffic over both UDP connections.
Choose distance vector routing protocol to transmit data from sender to receiver.

Schedule events and run the program.

PROGRAM:

set ns [new Simulator] set nr [open thro.tr w]

$ns trace-all $nr

set nf [open thro.nam w]

$ns namtrace-all $nf


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

66
for { set i 0 } { $i < 12} { incr i 1 } {
set n($i) [$ns node]}
for {set i 0} {$i < 8} {incr i} {
$ns duplex-link $n($i) $n([expr $i+1]) 1Mb 10ms DropTail }
$ns duplex-link $n(0) $n(8) 1Mb 10ms DropTail
$ns duplex-link $n(1) $n(10) 1Mb 10ms DropTail
$ns duplex-link $n(0) $n(9) 1Mb 10ms DropTail
$ns duplex-link $n(9) $n(11) 1Mb 10ms DropTail
$ns duplex-link $n(10) $n(11) 1Mb 10ms DropTail
$ns duplex-link $n(11) $n(5) 1Mb 10ms DropTail
set udp0 [new Agent/UDP]
$ns attach-agent $n(0) $udp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0
set null0 [new Agent/Null]
$ns attach-agent $n(5) $null0
$ns connect $udp0 $null0
set udp1 [new Agent/UDP]
$ns attach-agent $n(1) $udp1
set cbr1 [new Application/Traffic/CBR]
$cbr1 set packetSize_ 500
$cbr1 set interval_ 0.005
$cbr1 attach-agent $udp1
set null0 [new Agent/Null]
$ns attach-agent $n(5) $null0
$ns connect $udp1 $null0
$ns rtproto DV
$ns rtmodel-at 10.0 down $n(11) $n(5)
$ns rtmodel-at 15.0 down $n(7) $n(6)
$ns rtmodel-at 30.0 up $n(11) $n(5)
$ns rtmodel-at 20.0 up $n(7) $n(6)
$udp0 set fid_ 1
$udp1 set fid_ 2
$ns color 1 Red
$ns color 2 Green
$ns at 1.0 "$cbr0 start"
$ns at 2.0 "$cbr1 start"
$ns at 45 "finish"
$ns run

67
OUTPUT

RESULT:

Thus the Distance Vector Routing Algorithm was Simulated and studied.

INFERENCE:

68
EXNO: 10B DATE:

SIMULATION OF LINK STATE ROUTING

AIM:

To simulate the link state routing algorithm using NS2.

ALGORITHM:

STEP 1: Create a simulator object


STEP 2: Define different colors for different data flows
STEP 3: Open a nam trace file and define finish procedure then close the
trace file,and execute nam on trace file.
STEP 4: Create n number of nodes using for loop
STEP 5: Create duplex links between the nodes
STEP 6:Setup UDP Connection between n(0) and n(5)
STEP 7: Setup another UDP connection between n(1) and n(5)
STEP 8: Apply CBR Traffic over both UDP connections
STEP 9: Choose Link state routing protocol to transmit data from sender to receiver.
STEP 10: Schedule events and run the program.

PROGRAM:

set ns [new Simulator]


set nr [open thro.tr w]
$ns trace-all $nr
set nf [open thro.nam w]
$ns namtrace-all $nf
proc finish { } {
global ns nr nf
$ns flush-trace
close $nf
close $nr
exec nam thro.nam &
exit 0 }
for { set i 0 } { $i < 12} { incr i 1 } {
set n($i) [$ns node]}
for {set i 0} {$i < 8} {incr i} {
$ns duplex-link $n($i) $n([expr $i+1]) 1Mb 10ms DropTail }
$ns duplex-link $n(0) $n(8) 1Mb 10ms DropTail
$ns duplex-link $n(1) $n(10) 1Mb 10ms DropTail

69
$ns duplex-link $n(0) $n(9) 1Mb 10ms DropTail
$ns duplex-link $n(9) $n(11) 1Mb 10ms DropTail
$ns duplex-link $n(10) $n(11) 1Mb 10ms DropTail
$ns duplex-link $n(11) $n(5) 1Mb 10ms DropTail
set udp0 [new Agent/UDP]
$ns attach-agent $n(0) $udp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0
set null0 [new Agent/Null]
$ns attach-agent $n(5) $null0
$ns connect $udp0 $null0
set udp1 [new Agent/UDP]
$ns attach-agent $n(1) $udp1
set cbr1 [new Application/Traffic/CBR]
$cbr1 set packetSize_ 500
$cbr1 set interval_ 0.005
$cbr1 attach-agent $udp1
set null0 [new Agent/Null]
$ns attach-agent $n(5) $null0
$ns connect $udp1 $null0
$ns rtproto LS
$ns rtmodel-at 10.0 down $n(11) $n(5)
$ns rtmodel-at 15.0 down $n(7) $n(6)
$ns rtmodel-at 30.0 up $n(11) $n(5)
$ns rtmodel-at 20.0 up $n(7) $n(6)
$udp0 set fid_ 1
$udp1 set fid_ 2
$ns color 1 Red
$ns color 2 Green
$ns at 1.0 "$cbr0 start"
$ns at 2.0 "$cbr1 start"
$ns at 45 "finish"
$ns run

70
OUTPUT

RESULT:

Thus the Distance vector Routing Algorithm was simulated and studied.

INFERENCE:

71
EXNO: 11 DATE:

IMPLEMENTATION OF GO BACK N ARQ PROTOCOL


AIM
To implement a sliding window protocol that uses Go Back N ARQ.

ALGORITHM:

SENDER

STEP 1: Create a server socket


STEP 2: Assume the sending window size as 7 (m = 3).
STEP 3: If receiver is ready, initialize sender's frame sequence to 0.
STEP 4: Get data from user.
STEP 5: Send it to the receiver along with sequence number.
STEP 6: Increment sequence number by 1.
STEP 7: Repeat steps 4–6 until all frames have been sent.
STEP 8: Wait for acknowledgements.
STEP 9: If all acknowledgements have arrived then go to step 12.
STEP 10: Set sequence number to earliest outstanding frame for which there is no ACK.
STEP 11: Go to step 4.
STEP 12: Stop

RECEIVER

1. Indicate to sender, the readiness to accept frames.


2. Initialize receiver's expected frame sequence to 0.
3. Accept the incoming frame.
4. If frame's sequence receiver's sequence then go to step 7.
5. Send an acknowledgement.
6. Repeat steps 3–6 until all frames are received in sequence and go to step 9.
7. Discard frame, thereby force the sender to retransmit.
8. Go to step 3.
9. Stop.

72
PROGRAM

Go Back N Sender

import java.io.*;
import java.net.*;
public class GBNSend
{
String output[] = new String[7];
void sendMsg(BufferedReader buff, BufferedReader in, PrintWriter out, int x)
throws Exception
{
try
{
for(int i=x; i<7; i++)
{
System.out.print("Content for frame" + i + " : ");
output[i] = in.readLine();
out.println(output[i]);
out.flush();
}
}
catch(Exception e)
{
System.out.println("exception is" + e);
}
}

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


{
GBNSend g = new GBNSend();
ServerSocket ssoc = new ServerSocket(6000);
Socket soc = ssoc.accept();
String input[] = new String[7];
BufferedReader buff = new BufferedReader(new InputStreamReader(soc.getInputStream()));
PrintWriter out = new PrintWriter(new OutputStreamWriter(soc.getOutputStream()));
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Window size 7");
System.out.println("Enter message in format-- SeqNoData");
int x = 0;
g.sendMsg(buff,in,out,0);
for(int j=0; j<7; j++)
{
String s = new String();
input[j] = buff.readLine();
s = j + "";
if(input[j].startsWith(s))
System.out.println("Ack for frame" + j);
else
{
System.out.println("Frame" + j + " lost/corrupt. Go Back & resend");
x = j;
73
g.sendMsg(buff,in,out,j);
--j;
}
}
soc.close();
ssoc.close();
}
}

//Go Back N Receiver--GBNReceive.java


import java.io.*;
import java.net.*;
public class GBNReceive
{
String input[] = new String[7];
void ReceiveMsg(BufferedReader buff, PrintWriter out, int x) throws Exception
{
try
{
for(int i=x; i<7; i++)
input[i] = buff.readLine();
}

catch(Exception e)
{
System.out.println("exception is" + e);
}
}

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


{
GBNReceive g = new GBNReceive();
Socket soc = new Socket("localhost", 6000);
BufferedReader buff = new BufferedReader(new InputStreamReader(soc.getInputStream()));
PrintWriter out = new PrintWriter(new OutputStreamWriter(soc.getOutputStream()));
int x = 0;
g.ReceiveMsg(buff,out,0);
for(int j=x; j<7; j++)
{
String s = new String(); s = j + "";
if(g.input[j].startsWith(s))
{
String rmsg = g.input[j];
rmsg = rmsg.substring(1,rmsg.length());
System.out.println("Frame" + j + "data is " + rmsg);
out.println(j + "ack"); out.flush();
}
else
{
out.println("no ack");
out.flush();
74
--j;
}}
soc.close();
}
}

OUTPUT:

Sender

Receiver

RESULT:
Thus the java program to simulate Go-Back-N ARQ was done and output verified.

INFERENCE:

75
EXNO: 12 DATE:

IMPLEMENTATION OF ERROR CORRECTION CODE


CYCLIC REDUNDANCY CHECK

AIM:

To Implement Cyclic Redundancy check.

ALGORITHM:

STEP 1: Enter the number of data bits.


STEP 2: Enter the number of generator bits.
STEP 3: Enter the data bits.
STEP 4: Enter the generator bits.
STEP 5: Print the code bits.

STEP 6: Stop the program.

PROGRAM:

import java.util.Scanner;
class CRC
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int m,g[],n,d[],z[],r[],msb,i,j,k;
System.out.print("Enter no. of data bits : ");
n=sc.nextInt();
System.out.print("Enter no. of generator bits : ");
m=sc.nextInt();
d=new int[n+m];
g=new int[m];
System.out.print("Enter data bits : ");
for(i=0;i<n;i++)
d[i]=sc.nextInt();
System.out.print("Enter generator bits : ");
for(j=0;j<m;j++)
g[j]=sc.nextInt();
for(i=0;i<m-1;i++)
d[n+i]=0;
r=new int[m+n];
for(i=0;i<m;i++)
r[i]=d[i];
z=new int[m];

76
for(i=0;i<m;i++)
z[i]=0;
for(i=0;i<n;i++)
{
k=0;
msb=r[i];
for(j=i;j<m+i;j++)
{
if(msb==0)
r[j]=xor(r[j],z[k]);
else
r[j]=xor(r[j],g[k]);
k++;
}
r[m+i]=d[m+i];
}
System.out.print("The code bits added are : ");
for(i=n;i<n+m-1;i++)
{
d[i]=r[i];
System.out.print(d[i]);
}
System.out.print("\nThe code data is : ");
for(i=0;i<n+m-1;i++)
{
System.out.print(d[i]);
}
}
public static int xor(int x,int y)
{
if(x==y)
return(0);
else
return(1);
}
}

77
OUTPUT:

Enter no. of data bits : 14


Enter no. of generator bits : 4
Enter data bits : 1
1
0
1
0
0
1
1
1
0
1
1
0
0
Enter generator bits :
1
0
1
1
The code bits added are : 100
The code data is : 11010011101100100

RESULT:
Thus the java program to implement Cyclic Redundancy check was done and output was
verified.

INFERENCE:

78

You might also like