Mayank Pratap Puri - 1803310117 - CN - File
Mayank Pratap Puri - 1803310117 - CN - File
Mayank Pratap Puri - 1803310117 - CN - File
COMPUTER NETWORK
LABORATORY MANUAL
We wish to serve the nation by becoming a reputed deemed university for providing value
based professional education.
To be recognized globally for delivering high quality education in the ever-changing field of
computer science & engineering, both of value & relevance to the communities we serve.
1. To provide quality education in both the theoretical and applied foundations of Computer
Science and train students to effectively apply this education to solve real world problems.
2. To amplify their potential for lifelong high-quality careers and give them a competitive
advantage in the challenging global work environment.
students which they can use at different levels according to their experience and
contribute for progress and development in the society.
PROGRAM OUTCOMES (POs)
PO5: Modern tool usage: Create, select, and apply appropriate techniques, resources,
a n d modern engineering and IT tools including prediction and modelling to complex
engineering activities with an Understanding of thelimitations.
PO6: The engineer and society: Apply reasoning informed by the contextualknowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.
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 andresponsibilities and
norms of the engineering practice.
PO9: Individual and team work: Function effectively as an individual, and as amember or
leader in diverse teams, and in multidisciplinary settings.
PO12: Life-long learning: Recognize the need for, and have the preparation andability to
engage in independent and life-long learning in the broadest context of technological change.
PSO1: The ability to use standard practices and suitable programming environment to
develop software solutions.
PSO2: The ability to employ latest computer languages and platforms in creating
innovative career opportunities.
.
COURSE OUTCOMES (COs)
CO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2
C320.1 3 3 1 1 2 1 1
C320.2 3 3 2 1 1 1 1 2 2 1
C320.3 3 3 3 1 1 1 1 2 1 2 2 1
C320.4 3 3 3 2 1 2 1 2 2 1
C320.5 3 3 1 1 1 1 2 1
C320
3 3 2.2 1.3 1 1 1 1.4 2 1 1.8 1.6 1
5
INTRODUCTION
NETWORKING BASICS
Host:A computer system that is accessed by a user working at a remote location. It is the remoteprocess
with which a process communicates. It may also be referred as Peer.
Server: In computer networking, a server is a computer designed to process requests and deliver datato
other computers over a local network or the Internet.
Iterative servers: This server knows ahead of time about how long it takes to handle
eachrequest & server process handles each request itself.
Client: A Client is an application that runs on a personal computer or workstation and relies on a
serverto perform some operations.
Network Address: Network addresses give computers unique identities they can use to
communicatewith each other. Specifically, IP addresses and MAC addresses are used on most home and
business networks.
Protocols: A Protocol is a convention or standard rules that enables and controls the
connection,communication and data transfer between two computing endpoints.
Port An interface on a computer to which you can connect a device. It is a "logical connection place"and
specifically, using the Internet's protocol, TCP/IP.
A port is a 16-bit number, used by the host-to-host protocol to identify to which higher-level protocol or
application program (process) it must deliver incoming messages.
PORTS RANGE
Well-known ports 1-1023
Ephemeral ports 1024-5000
User-defined ports 5001-65535
Association: Association is used for 5 tuple that completely specifies the two processes that
makeup a connection.
The local address and foreign address specify the network ID & Host-ID of the local host and the foreign
host in whatever format is specified by protocol suite.
The local process and foreign process are used to identify the specific processes on each system that are
involved in a connection.
which specify each half of a connection. This half association is called a Socket or transport
address.
OSI MODEL
A common way to describe the layers in a network is to use the International Organization for
Standardization (ISO) open systems interconnection (OSI) model for computer communications. This is
a seven-layer model, which we show in Figure below along with the approximate mapping to the
Internet protocol suite.
We consider the bottom two layers of the OSI model as the device driver and networking hardware that
are supplied with the system. The network layer is handled by the IPv4 and IPv6 protocols. The
transport layers that we can choose from are TCP and UDP
The upper three layers of the OSI model are combined into a single layer called the application. This is
the Web client (browser) or whatever application we are using. With the Internet protocols, there is
rarely any distinction between the upper three layers of the OSI model.
The sockets programming interfaces are interfaces from the upper three layers (the "application") into
the transport layer. The sockets provide the interface from the upper three layers of the OSI model into
the transport layer. There are two reasons for this design:
The upper three layers handle all the details of the application and know little about the
communication details. The lower four layers know little about the application, but
handle all the communication details: sending data, waiting for acknowledgments, and so on.
The second reason is that the upper three layers often form what is called a user process while
the lower four layers are normally provided as part of the operating system (OS) kernel.
This lab gives in depth view of how computer networks works in real time, simulation of various
topologies are performed using ns3 tool.
ns-3 has been developed to provide an open, extensible network simulation platform, for
networkingresearch and education. In brief, ns-3 provides models of how packet data networks work and
perform, and provides a simulation engine for users to conduct simulation experiments. Some of the
reasons to use ns-3 include to perform studies that are more difficult or not possible to perform with real
systems, to study system behavior in a highly controllled, reproducible environment, and to learn about
how networks work. Users will note that the available model set in ns-3 focuses on modeling how
Internet protocols and networks work, but ns-3 is not limited to Internet systems; several users are
usingns-3 to model non-Internet-based systems.
Many simulation tools exist for network simulation studies. Below are a few distinguishing features of
ns-3 in contrast to other tools.
ns-3 is designed as a set of libraries that can be combined together and also with other
externalsoftware libraries. While some simulation platforms provide users with a single,
integrated graphical user interface environment in which all tasks are carried out, ns-3 is more
modular in this regard. Several external animators and data analysis and visualization tools can
be used with ns-3. However, users should expect to work at the command line and with C++
and/or Python software development tools.
ns-3 is primarily used on Linux systems, although support exists for FreeBSD, Cygwin(for
Windows), and native Windows Visual Studio support is in the process of being developed.
PREFACE
This practical manual will be helpful for students of Computer Science & Engineering for
understanding the course from the point of view of applied aspects. Though all the efforts
have been made to make this manual error free, yet some errors might have crept in
inadvertently. Suggestions from the readers for the improvement of the manual are most
welcomed.
Pawan Pandey
(Lab Co-Ordinator)
Assistant Professor, Dept. of CSE
.
DO’S AND DONT’S
DO’s
DONT’S
5. Do not touch, connect or disconnect any plug or cable without your faculty/laboratory
technician’s permission.
GENERAL SAFETY INSTRUCTIONS
1. Know the location of the fire extinguisher and the first aid box and how to use them in case
of an emergency.
4. Do not plug in external devices without scanning them for computer viruses.
DETAIL OF THE EXPERIMENTS CONDUCTED
(TO BE USED BY THE STUDENT IN THEIR RECORD)
While preparing the lab records, the student is required to adhere to the following guidelines:
1. Cover page
2. Vision
3. Mission
4. PEOs
5. POs
6. PSOs
7. COs
8. CO-PO-PSO mapping
9. Index
10. Experiments
11. Aim
12. Source code
13. Input-Output
Students are provided with the details of the experiment (Aim, pre-experimental questions,
procedure etc.) to be conducted in next lab and are expected to come prepared for each lab
class.
Faculty ensures that students have completed the required pre-experiment questions and they
complete the in-lab programming assignment(s) before the end of class. Given that the lab
programs are meant to be formative in nature, students can ask faculty for help before and
during the lab class.
Students’ performance will be assessed in each lab based on the following Lab Assessment
Components:
In each lab class, students will be awarded marks out of 5 under each component head,
making it total out of 15 marks.
Raj Kumar Goel Institute of Technology, Ghaziabad
OUTPUT
BIT CLIENT
Localhost/127.0.0.1connect
enter the no of frames to be requested to
server:4 received frame no1
sending acknowledgement for frame
no1 received frame no2
sending acknowledgement for frame
no2 received frame no3
sending acknowledgement for frame
no3 received frame no4
sending acknowledgement for frame no4
BITSERVER
waiting for connection
received request for sending
framessending...... sending frame no1
waiting for acknowledge
received acknowledge for frame
no:1as1 sending frame no2waiting for
acknowledge received acknowledge for
frame no:2as2 sending frame no3
waiting for acknowledge
received acknowledge for frame
no:3as3 sending frame no4
waiting for acknowledge
received acknowledge for frame no:4as4
EXPERIMENT 2. Study of Socket Programming and Client – Server model
Here, we are going to make one-way client and server communication. In this
application, client sends a message to the server, server reads the message and
prints it. Here, two classes are being used: Socket and ServerSocket. The Socket
class is used to communicate client and server. Through this class, we can read and
write message. The ServerSocket class is used at server-side. The accept() method
of ServerSocket class blocks the console until the client is connected. After the
successful connection of client, it returns the instance of Socket at server
side.
Socket class
A socket is simply an endpoint for communications between the machines. The
Socket class can be used to create a socket.
Important methods
Method Description
ServerSocket class
The ServerSocket class can be used to create a server socket. This object is used to
establish communication with the clients.
Important methods
Method Description
1) public Socket accept() returns the socket and establish a connection between
server and client.
Creating Client:
To create the client application, we need to create the instance of Socket class. Here,
we need to pass the IP address or hostname of the Server and a port number. Here,
we are using "localhost" because our server is running on same system.
}catch(Exception }catch(Exception
e){System.out.println(e);} } e){System.out.println(e);} }
} }
ARP protocol is simulated by reading an IP address and returning the MAC address.
RARP protocol is simulated by reading an MAC address and returning the IP address
The program can be extended to read an IP Address / Mac Address and a message
and send a packet to the specified machine using TCP / IP or Datagram sockets
import java.io.*;
import java.util.*;
Process P = Runtime.getRuntime().exec(cmd);
Scanner S = new Scanner(P.getInputStream()).useDelimiter("\\A");
while(S.hasNext())
bw.write(S.next());
bw.close();
fw.close();
}
String line;
fr.close();
br.close();
}
public static void findIP(String mac) throws Exception
{
File fp = new File("ARPTable.txt");
FileReader fr = new FileReader(fp);
BufferedReader br = new BufferedReader(fr);
String line;
if((line == null))
System.out.println("Not found");
fr.close();
br.close();
}
System.out.println("ARP Protocol.");
System.out.print("Enter IP Address: ");
String IP = S.nextLine();
findMAC(IP);
System.out.println("RARP Protocol.");
System.out.print("Enter MAC Address: ");
String MAC = S.nextLine();
findIP(MAC);
}
}
OUTPUT:
>javac arp_rarp.java
>java arp_rarp
ARP Protocol.
Enter IP Address: 10.0.15.253
Internet Address Physical Address Type 10.0.15.253
00-16-76-bd-41-27 dynamic
RARP Protocol.
Enter MAC Address: 01-00-5e-00-00-fc
Internet Address Physical Address Type
224.0.0.252 01-00-5e-00-00-fc static
>java arp_rarp
ARP Protocol.
Enter IP Address: 10.0.15.121
Not found
RARP Protocol.
Enter MAC Address: 01-00-5e-00-00-ff
Not found
ARPTable.txt
Algorithm
Step 1: start the program.
Step 2: Include necessary package in java.
Step 3: To create a process object p to implement the ping
command. Step 4: declare one BufferedReader stream class
object.
Step 5: Get thedetails of the server
5.1: length of the IP address.
5.2 : time required to get the details.
5.3 : send packets , receive packets and lost packets.
5.4: minimum ,maximum and average times.
Step 6: print the results.
Step 7:Stop the program.
Program:
import java.io.*;
import java.net.*;
class pingserver
{
public static void main(String args[])
{
try
{
String str;
System.out.print(" Enter the IP Address to be Ping : ");
BufferedReader buf1=new BufferedReader(new
InputStreamReader(System.in));
String ip=buf1.readLine();
Runtime H=Runtime.getRuntime();
Process p=H.exec("ping " + ip);
InputStream in=p.getInputStream();
BufferedReader buf2=new BufferedReader(new
InputStreamReader(in));
while((str=buf2.readLine())!=null)
{
System.out.println(" " + str);
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
Output:
Enter the IP address to the ping:192.168.0.1
import java.io.BufferedReader;
import java.io.InputStreamReader;
String s = "";
while ((s = inputStream.readLine()) != null)
System.out.println(s);
}
catch (Exception e)
{
}
}
>javac traceroutecmd.java
>java traceroutecmd
EXPERIMENT 5. Create a socket for HTTP for web page upload and
download. Algorithm
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;
dos.write(bytes, 0, bytes.length);
System.out.println("Image sent to server. ");
dos.close();
out.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();
dis.readFully(data);
dis.close();
in.close();
InputStream ian = new ByteArrayInputStream(data);
BufferedImage bImage = ImageIO.read(ian);
JFrame f = new JFrame("Server");
ImageIcon icon = new ImageIcon(bImage);
JLabel l = new JLabel();
l.setIcon(icon);
f.add(l);
f.pack();
f.setVisible(true); } }
EXPERIMENT 6 Write a program to implement RPC (Remote Procedure Call)
A client has a request message that the RPC translates and sends to the server. This
request may be a procedure or a function call to a remote server. When the server
receives the request, it sends the required response back to the client. The client is
blocked while the server is processing the call and only resumed execution after the
server is finished.
HelloWorld.java
package
rpc_helloworld;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
@WebService
@SOAPBinding(style = Style.RPC)
public interface HelloWorld {
@WebMethod String getHelloWorld(String name);
}
HelloWorldImpl.java
package
rpc_helloworld;
import javax.jws.WebService;
@WebService(endpointInterface =
"rpc_helloworld.HelloWorld")
public class HelloWorldImpl implements
HelloWorld{ @Override
public String getHelloWorld(String name) {
return name;
}
}
Publisher.java
package
rpc_helloworld;
import javax.xml.ws.Endpoint;
public class Publisher {
public static void main(String[] args) {
Endpoint.publish("https://localhost:7779/ws/hello",
new HelloWorldImpl());
}
}
rpc_helloworld.java
package
rpc_helloworld;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
public class RPC_HelloWorld {
System.out.println(hello.getHelloWorld("Hello
World!"));
} catch (MalformedURLException ex) {
System.out.println("WSDL document url
error: " + ex);
}
}
}
After create all these files, you need to run your Publisher.Java and then go to your
browser and type the following:
https://localhost:7779/ws/hello?wsdl
Then you will get the response in XML format. After that you need to copy the text that
assign for targetNamespace.
Then paste the text in your Client side file, as the QName first parameter. Now run
your program and you will get the output.
[https://sivakumar-prasanth.medium.com/java-rpc-remote-procedure-call-99cfaca34c36]
EXPERIMENT 7 Implementation of Subnetting.
import java.util.Scanner;
class Subnet{
public static void main(String
args[]){ Scanner sc = new
Scanner(System.in);
System.out.print(“Enter the ip address: “);
String ip = sc.nextLine();
String split_ip[] = ip.split(“\\.”); //SPlit the string after every .
String split_bip[] = new String[4]; //split binary ip
String bip = “”;
for(int i=0;i<4;i++){
split_bip[i] = appendZeros(Integer.toBinaryString(Integer.parseInt(split_ip[i]))); // “18”
=> 18 => 10010 => 00010010
bip += split_bip[i];
}
System.out.println(“IP in binary is “+bip);
System.out.print(“Enter the number of addresses: “);
int n = sc.nextInt();
//Calculation of mask
int bits = (int)Math.ceil(Math.log(n)/Math.log(2)); /*eg if address = 120, log 120/log 2
gives log to the base 2 => 6.9068, ceil gives us upper integer */
System.out.println(“Number of bits required for address = “+bits);
int mask = 32-bits;
System.out.println(“The subnet mask is = “+mask);
/*Output
Server
1. Create a server socket and bind it to port.
2. Listen for new connection and when a connection arrives,
accept it. 3. Read the data from client.
4. Echo the data back to the client.
5. Repeat steps 4-5 until „bye‟ or „null‟ is read.
6. Close all streams.
7. Close the server socket.
8. Stop.
Client
1. Create a client socket and connect it to the server‟s port
number. 2. Get input from user.
3. If equal to bye or null, then go to step 7.
4. Send user data to the server.
5. Display the data echoed by the server.
6. Repeat steps 2-4.
7. Close the input and output streams.
8. Close the client socket.
9. Stop.
OUTPUT
Server:
$ javac tcpechoserver.java
$ java tcpechoserver
Server Ready Client Connected Client [ hello ]
Client [ how are you ] Client [ i am fine ] Client [ ok ]
Client Disconnected
Client :
$ javac tcpechoclient.java
$ java tcpechoclient
Type "bye" to quit
Enter msg to server : hello
Server [ hello ]
Enter msg to server : how are you
Server [ how are you ]
Enter msg to server : i am fine
Server [ i am fine ]
Enter msg to server : ok
Server [ ok ]
Enter msg to server : bye
/ TCP Echo Server-- Disconnected"); }
tcpechoserver.java import catch (IOException ioe)
java.net.*; {
import java.io.*; System.err.println(ioe);
public class tcpechoserver }
{ }
public static void main(String[] arg) }
throws IOException //TCP Echo Client--
{ tcpechoclient.java import
ServerSocket sock = null; java.net.*;
BufferedReader fromClient = null; import java.io.*;
OutputStreamWriter toClient = public class tcpechoclient
null; Socket client = null; {
try public static void main(String[] args)
{ throws IOException
sock = new ServerSocket(4000); {
System.out.println("Server BufferedReader fromServer = null,
Ready"); client = sock.accept(); fromUser = null;
System.out.println("Client Connected"); PrintWriter toServer = null;
fromClient = new BufferedReader(new Socket sock = null;
InputStreamReader(client.getInputStrea try
m())); toClient = new {
OutputStreamWriter(client.getOutputStrea if (args.length == 0)
m()); String line; sock = new
while (true) Socket(InetAddress.getLocalHost(),40
{ 00); else
line = fromClient.readLine(); sock = new
if ( (line == null) || Socket(InetAddress.getByName(args[0]),4
line.equals("bye")) break; 000); fromServer = new
System.out.println ("Client [ " + line + BufferedReader(new
" ]"); toClient.write("Server [ "+ line InputStreamReader(sock.getInputStream()))
+" ]\n"); toClient.flush(); ; fromUser = new BufferedReader(new
} InputStreamReader(System.in));
fromClient.close(); toServer = new
toClient.close(); PrintWriter(sock.getOutputStream(),tr
client.close(); ue); String Usrmsg, Srvmsg;
sock.close(); System.out.println("Type \"bye\" to
System.out.println("Client quit"); while (true)
{ System.out.println(Srvmsg);
System.out.print("Enter msg to }
server : "); Usrmsg = fromUser.close();
fromUser.readLine(); fromServer.close();
if (Usrmsg==null || toServer.close();
Usrmsg.equals("bye")) sock.close();
{ toServer.println("bye"); }
break; catch (IOException ioe)
} {
else System.err.println(ioe);
toServer.println(Usrmsg); }
Srvmsg = fromServer.readLine();
EXPERIMENT 8.b. IMPLEMENTATION OF TCP/IP Chat
// A Java program for a Client // A Java program for a Server
import java.net.*; import java.net.*;
import java.io.*; import java.io.*;
Algorithm Server
Step1: Import java packages and create class file server.
Step2: Create a new server socket and bind it to the port.
Step3: Accept the client connection
Step4: Get the file name and stored into the BufferedReader.
Step5: Create a new object class file and realine.
Step6: If file is exists then FileReader read the content until EOF is
reached. Step7: Stop the program.
Client
Program
File Server :
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
Output
server
E:\nwlab>java FileServer
Sending file ... 9% complete!
Sending file ... 19% complete!
Sending file ... 28% complete!
Sending file ... 38% complete!
Sending file ... 47% complete!
Sending file ... 57% complete!
Sending file ... 66% complete!
Sending file ... 76% complete!
Sending file ... 86% complete!
Sending file ... 95% complete!
Sending file ... 100% complete! File sent successfully!
E:\nwlab>client
E:\nwlab>java FileClient File saved successfully!
E:\nwlab>
EXPERIMENT 9.a. Program to implement DNS in java
import java.net.*;
import java.io.*;
import java.util.*;
public class DNS
{
public static void main(String[] args)
{
int n;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); do
{
System.out.println("\n Menu: \n 1. DNS 2. Reverse DNS 3. Exit \n");
System.out.println("\n Enter your choice");
n = Integer.parseInt(System.console().readLine());
if(n==1)
{
try
{
System.out.println("\n Enter Host Name ");
String hname=in.readLine();
InetAddress address;
address = InetAddress.getByName(hname);
System.out.println("Host Name: " + address.getHostName()); System.out.println("IP:
" + address.getHostAddress());
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
if(n==2)
{
try
{
System.out.println("\n Enter IP address");
String ipstr = in.readLine();
InetAddress ia = InetAddress.getByName(ipstr);
System.out.println("IP: "+ipstr);
System.out.println("Host Name: " +ia.getHostName());
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
}
}while(!(n==3));
}
}
EXPERIMENT 10. STUDY OF NETWORK SIMULATOR (NS)
AIM:
THEORY:
Network Simulator (Version 2), widely known as NS2, is simply an event driven
simulation tool that has proved useful in studying the dynamic nature of
communication networks. Simulation of wired as well as wireless network functions
and protocols (e.g., routing algorithms, TCP, UDP) can be done using NS2. In
general, NS2 provides users with a way of specifying such network protocols and
simulating their corresponding behaviors. Due to its flexibility and modular nature,
NS2 has gained constant popularity in the networking research community since its
birth in 1989.
The above figure shows the basic architecture of NS2. NS2 provides users
with an executable command ns which takes on input argument, the name of a
Tcl simulation scripting file. Users are feeding the name of a Tcl simulation script
(which sets up a simulation) as an input argument of an NS2 executable
command ns.
In most cases, a simulation trace file is created, and is used to plot graph
and/or to create animation. NS2 consists of two key languages: C++ and Object-
oriented Tool Command Language (OTcl). While the C++ defines the internal
mechanism (i.e., a backend) of the
simulation objects, the OTcl sets up simulation by assembling and configuring the
objects as well as scheduling discrete events (i.e., a frontend).
The C++ and the OTcl are linked together using TclCL. Mapped to a C++
object, variables in the OTcl domains are sometimes referred to as handles.
Conceptually, a handle (e.g., n as a Node handle) is just a string (e.g.,_o10) in
the OTcl domain, and does not contain any functionality. instead, the functionality
(e.g., receiving a packet) is defined in the mapped C++ object (e.g., of class
Connector). In the OTcl domain, a handle acts as a frontend which interacts with
users and other OTcl objects. It may defines its own procedures and variables to
facilitate the interaction. Note that the member procedures and variables in the
OTcl domain are called instance procedures (instprocs) and instance variables
(instvars), respectively
Tcl scripting:
• It is not necessary to declare a data type for variable prior to the usage
Basics of TCL
Syntax: command arg1 arg2 arg3
Hello World!
puts stdout{Hello, World!}
Hello, World!
Variables
Command Substitution
set a 5 set len [string length foobar]
set b $a set len [expr [string length foobar] + 9]
Simple Arithmetic
expr 7.2 / 4
Procedures
proc Diag {a b} {
set c [expr sqrt($a * $a + $b * $b)]
return $c }
puts ―Diagonal of a 3, 4 right triangle is [Diag 3 4]‖
Output: Diagonal of a 3, 4 right triangle is 5.0
Loops
while{$i < $n} { for {set i 0} {$i < $n} {incr
... i} {
} ...
}
NS Simulator Preliminaries.
1. Initialization and termination aspects of the ns simulator.
2. Definition of network nodes, links, queues and topology.
3. Definition of agents and of applications.
4. The nam visualization tool.
5. Tracing and random variables.
Initialization and Termination of TCL Script in NS-2
An ns simulation starts with the command
Which is thus the first line in the tcl script? This line declares a new variable as
using the set command, you can call this variable as you wish, In general people
declares it as ns because it is an instance of the Simulator class, so an object the
code[new Simulator] is indeed the installation of the class Simulator using the
reserved word new.
In order to have output files with data on the simulation (trace files) or files
used for visualization (nam files), we need to create the files using ―”open”
command: #Open the Trace file
The above creates a dta trace file called ―out.tr‖ and a nam visualization trace file
called ―out.nam‖.Within the tcl script,these files are not called explicitly by their
names, but instead by pointers that are declared above and called ―tracefile1
and ―nam file respectively. Remark that they begins with a # symbol.The second
line open the file ―out.tr‖ to be used for writing, declared with the letter ―w‖.The
third line uses a simulator method called trace-all that have as parameter the name
of the file where the traces will go.
The last line tells the simulator to record all 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. In our case, this will be the file pointed at by the
pointer ―$namfile ,i.e the file ―out.tr‖. The termination of the program is done
using a ―finish‖ procedure.
#Define a „finish‟ procedure
Proc finish { } {
global ns tracefile1 namfile
$ns flush-trace
Close $tracefile1
Close $namfile
Exec nam out.nam &
Exit 0
The word proc declares a procedure in this case called finish and without arguments.
The word global is used to tell that we are using variables declared outside the
procedure. The simulator method ―flush-trace” will dump the traces on the
respective files. The tcl command
―close” closes the trace files defined before and exec executes the nam
program for visualization.
The command exit will ends the application and return the number 0 as status to the
system. Zero
is the default for a clean exit. Other values can be used to say that is a exit because
something fails.
At the end of ns program we should call the procedure ―finish‖ and specify at what
time the termination should occur. For example,
$ns run
The node is created which is printed by the variable n0. When we shall refer to
that node in the
script we shall thus write $n0.
Once we define several nodes, we can define the links that connect them. An
example of a definition of a link is:
Which means that $n0 and $n2 are connected using a bi-directional link that
has 10ms of propagation delay and a capacity of 10Mb per sec for each direction.
To define a directional link instead of a bi-directional one, we should replace
“duplexlink” by “simplex link”.
In NS, an output queue of a node is implemented as a part of each link
whose input is that node. The definition of the link then includes the way to handle
overflow at that queue. In our case, if the buffer capacity of the output queue is
exceeded then the last packet to
arrive is dropped. Many alternative options exist, such as the RED (Random Early
Discard) mechanism, the FQ (Fair Queuing), the DRR (Deficit Round Robin), the
stochastic Fair Queuing (SFQ) and the CBQ (which including a priority and a round-
robin scheduler). In ns, an output queue of a node is implemented as a part of each
link whose input is that node. We should also define the buffer capacity of the queue
related to each link. An example would be:
The command $ns attach-agent $n0 $tcp defines the source node of the tcp
connection. The command
Defines the behavior of the destination node of TCP and assigns to it a pointer
Above shows the definition of a CBR application using a UDP agent. The
command $ns attach-agent $n4 $sink defines the destination node. The
command $ns connect $tcp $sink finally makes the TCP connection between the
source and destination nodes.
TCP has many parameters with initial fixed defaults values that can be
changed if mentioned explicitly. For example, the default TCP packet size has a size
of 1000bytes.This can be changed to another value, say 552bytes, using the
command $tcp set packetSize_ 552. When we have several flows, we may wish to
distinguish them so that we can identify them with different colors in the visualization
part. This is done by the command $tcp set fid_ 1 that assigns to the TCP connection
a flow identification of “1”.We shall later give the flow identification of “2” to the UDP
connection.
Scheduling Events
NS is a discrete event based simulation. The tcp script defines when event
should occur. The initializing command set ns [new Simulator] creates an event
scheduler, and events are then scheduled using the format:
RESULT:
Thus the Network Simulator 2 is studied in detail.
EXPERIMENT 11. Simulation of Distance Vector/Link State
Routing. .
a) Distance Vector routing protocol ROUTING
Aim:
To simulate and study the link state routing algorithm using simulation using NS2.
Algorithm
There are several variants of flooding algorithm. Most work roughly
as follows:
1. Each node acts as both a transmitter and a receiver.
2. Each node tries to forward every message to every one of its neighbours
except the source node. This results in every message eventually being
delivered to all reachable parts of the network. Algorithms may need to be
more complex than this, since, in
some case, precautions have to be taken to avoid wasted duplicate deliveries
and infinite loops, and to allow messages to eventually expire from the system. A
variant of flooding called selective flooding partially addresses these issues by
only sending packets to routers in the same direction. In selective flooding the
routers don't send every incoming packet on every line but only on those lines
which are going approximately in the right direction.
Program:
set ns [new Simulator]
proc finish {} {
global nf ns tr
$ns flush-trace
close $tr
exec nam out.nam &
exit 0
}
$ns rtproto DV
$ns run
Result:
Thus the Distance Vector Routing Algorithm was Simulated and studied
b) SIMULATION OF LINK STATE ROUTING ALGORITHM
Aim:
To simulate and study the link state routing algorithm using simulation using
NS2. Link State Routing protocol
In link state routing, each router shares its knowledge of its neighborhood with
every other router in the
internet work. (i) Knowledge about Neighborhood: Instead of sending its entire
routing table a router sends
info about its neighborhood only. (ii) To all Routers: each router sends this
information to every other router
on the internet work not just to its neighbor .It does so by a process called
flooding. (iii)Information sharing
when there is a change: Each router sends out information about the neighbors
when there is change.
ALGORITHM:
1. Create a simulator object
2. Define different colors for different data flows
3. Open a nam trace file and define finish procedure then close the trace file,
and execute nam on trace file.
4. Create n number of nodes using for loop
5. Create duplex links between the nodes
6. Setup UDP Connection between n(0) and n(5)
7. Setup another UDP connection between n(1) and n(5)
8. Apply CBR Traffic over both UDP connections
9. Choose Link state routing protocol to transmit data from sender to
receiver. 10. Schedule events and run the program.
Program:
set ns [new Simulator]
set nf [open out.nam w]
$ns namtrace-all $nf
proc finish {} {
global nf ns tr
$ns flush-trace
close $tr
exec nam out.nam &
exit 0
}
$ns rtproto LS
$ns run
Result:
Thus the program for creating Simulation of Distance Vector/Link
State Routing was implemented.
EXPERIMENT-12
Aim: To learn handling and configuration of networking hardware like RJ-45 connector,
CAT-6 cable, crimping tool, etc.
Apparatus (Components): RJ-45 connector, Climping Tool, Twisted pair Cable Procedure:
To do these practical following steps should be done:
1. Start by stripping off about 2 inches of the plastic jacket off the end of the cable. Be very
careful at this point, as to not nick or cut into the wires, which are inside. Doing so could alter
the characteristics of your cable, or even worse render is useless. Check the wires, one
more time for nicks or cuts. If there are any, just whack the whole end off, and start over.
2. Spread the wires apart, but be sure to hold onto the base of the jacket with your other
hand. You do not want the wires to become untwisted down inside the jacket. Category 5
cable must only have 1/2 of an inch of 'untwisted' wire at the end; otherwise it will be 'out of
spec'. At this point, you obviously have ALOT more than 1/2 of an inch of un-twistedwire.
3. You have 2 end jacks, which must be installed on your cable. If you are using a pre-made
cable, with one of the ends whacked off, you only have one end to install - the crossed over
end. Below are two diagrams, which show how you need to arrange the cables for each type
of cable end. Decide at this point which end you are making and examine the associated
picture below.
Diagram shows you how to prepare Cross wired connection
connection
EXPERIMENT-13
Aim: Study of following Network Devices in Detail
∙ Repeater
∙ Hub
∙ Switch
∙ Bridge
∙ Router
∙ Gate Way
2. Hub: An Ethernet hub, active hub, network hub, repeater hub, hub or concentrator is
a device for connecting multiple twisted pair or fiber optic Ethernet devices together and
making them act as a single network segment. Hubs work at the physical layer (layer 1) of
the OSI model. The device is a form of multiport repeater. Repeater hubs also participate in
collision detection, forwarding a jam signal to all ports if it detects a collision.
4. Bridge: A network bridge connects multiple network segments at the data link layer
(Layer 2) of the OSI model. In Ethernet networks, the term bridge formally means a device
that behaves according to the IEEE 802.1D standard. A bridge and switch are very much
alike; a switch being a bridge with numerous ports. Switch or Layer 2 switch is often used
interchangeably with bridge.Bridges can analyze incoming data packets to determine if the
bridge is able to send the given packet to another segment of the network.
6. Gate Way: In a communications network, a network node equipped for interfacing with
another network that uses different protocols.
∙ A gateway may contain devices such as protocol translators, impedance matching devices,
rate converters, fault isolators, or signal translators as necessary to provide system
interoperability. It also requires the establishment of mutually acceptable administrative
procedures between both networks.
∙ A protocol translation/mapping gateway interconnects networks with different network
protocol technologies by performing the required protocol conversions.
EXPERIMENT- 14
Aim: Study of basic network command and Network configuration commands. Apparatus
In this EXPERIMENT- students have to understand basic networking commands e.g ping,
tracert etc.
All commands related to Network configuration which includes how to switch to privilege
mode and normal mode and how to configure router interface and how to save this
configuration to flash memory or permanent memory.
This commands includes
Traceroute:
Tracert is a command which can show you the path a packet of information takes from your
computer to one you specify. It will list all the routers it passes through until it reaches its
destination, or fails to and is discarded. In addition to this, it will tell you how long each 'hop'
from router to router takes.
nslookup:
Displays information from Domain Name System (DNS) name servers. NOTE :If you write
the command as above it shows as default your pc's server name firstly.
ARP:
The ARP cache or table has the dynamic list of IP and MAC addresses of those
devices to which your computer has communicated recently in a local network. The
purpose of maintaining an ARP table is that when you want to communicate with
another device, your device does not need to send the ARP request for the MAC
address of that device.
TELNET:
Telnet is an application that is used to connect to a remote host’s command line
terminal interface. Network and system administrators use this application to
configure and administer network devices such as servers, routers, switches, etc.
This application is based on the connection-oriented Transmission Control Protocol
(TCP).
FTP:
FTP is the simplest file transfer protocol to exchange files to and from a remote
computer or network. Similar to Windows, Linux and UNIX operating systems also
have built-in command line prompts that can be used as FTP clients to make an FTP
connection.
In any command mode, you can get a list of available commands by entering a question mark (?).
EXPERIMENT-15
After configuring the given network a packet should be ping from any one machine to
another.
router0(config)#exit
Building configuration...
speed auto
!
interface FastEthernet0/1
duplex auto
speed auto
!
interface Vlan1
no ip address
shutdown
!
ip classless
!
!
!
!
!
line con 0
line vty 0 4
login
!
!
end
router0#
router0#
configuration...
[OK]
router0#