PDF To Word
PDF To Word
Pag Marks
Ex. Date Name of the Experiment e Date of Awarde Staff Rem
No. No. Completion d Sign arks
AIM
To study the basic networking commands.
COMMANDS
C:\>arp –a: ARP is short form of address resolution protocol, It will show the IP address of your
computer along with the IP address and MAC address of your router.
C:\>hostname: This is the simplest of all TCP/IP commands. It simply displays the name of your
computer.
C:\>ipconfig: The ipconfig command displays information about the host (the
computer your sitting at)computer TCP/IP configuration.
C:\>ipconfig /all: This command displays detailed configuration information about your TCP/IP
connection including Router, Gateway, DNS, DHCP, and type of Ethernet adapter in your system.
C:\>Ipconfig /renew: Using this command will renew all your IP addresses that you are currently
(leasing) borrowing from the DHCP server. This command is a quick problem solver if you are having
connection issues, but does not work if you have been configured with a static IP address.
C:\>Ipconifg /release: This command allows you to drop the IP lease from the DHCP server.
C:\>ipconfig /flushdns: This command is only needed if you‟re having trouble with your networks
DNS configuration. The best time to use this command is after network configuration frustration sets
in, and you really need the computer to reply with flushed.
1
C:\>nbtstat –a: This command helps solve problems with NetBIOS name resolution. (Nbt stands for
NetBIOS over TCP/IP)
C:\>netdiag: Netdiag is a network testing utility that performs a variety of network diagnostic tests,
allowing you to pinpoint problems in your network. Netdiag isn‟t installed by default, but can be
installed from the Windows XP CD after saying no to the install. Navigate to the CD ROM drive letter
and open the support\tools folder on the XP CD and click the setup.exe icon in the support\tools folder.
C:\>netstat: Netstat displays a variety of statistics about a computers active TCP/IP connections. This
tool is most useful when you‟re having trouble with TCP/IP applications such as HTTP, and FTP.
C:\>nslookup: Nslookup is used for diagnosing DNS problems. If you can access a resource by
specifying an IP address but not it‟s DNS you have a DNS problem.
C:\>pathping: Pathping is unique to Window‟s, and is basically a combination of the Ping and Tracert
commands. Pathping traces the route to the destination address then launches a 25 second test of each
router along the way, gathering statistics on the rate of data loss along each hop.
C:\>ping: Ping is the most basic TCP/IP command, and it‟s the same as placing a phone call to your
best friend. You pick up your telephone and dial a number, expecting your best friend to reply with
“Hello” on the other end. Computers make phone calls to each other over a network by using a Ping
command. The Ping commands main purpose is to place a phone call to another computer on the
network, and request an answer. Ping has 2 options it can use to place a phone call to another computer
on the network. It can use the computers name or IP address.
C:\>route: The route command displays the computers routing table. A typical computer, with a single
network interface, connected to a LAN, with a router is fairly simple and generally doesn‟t pose any
network problems. But if you‟re having trouble accessing other computers on your network, you can
use the route command to make sure the entries in the routing table are correct.
2
C:\>tracert: The tracert command displays a list of all the routers that a packet has to go through to get
from the computer where tracert is run to any other computer on the internet. C:\> $ tcpdump -i any
To get the network packets from all network interfaces, run the following command,
3
Experiment Score /10
EX. NO.:1(b) Date of
Completion Additional Credits
ALGORITHM
CONCLUSION
Thus the java program to simulate ping command was executed successfully.
8
Experiment Score /10
EX.NO.:1(C) Date of
Completion Additional Credits
OBJECTIVE
To simulate traceroute command using java language.
OUTCOME
Students gain knowledge of traceroute command using java
ALGORITHM
PROGRAM
import java.util.*;
public class TraceDemo
{
public void trace(String host)
{
try {
Process p = Runtime.getRuntime().exec("Tracert "+host);
Scanner scan = new Scanner(p.getInputStream());
while(scan.hasNextLine())
{
System.out.println(scan.nextLine());
}
}
catch(Exception ex){
System.out.println("Error "+ex);
}}
public static void main(String args[]){
TraceDemo p=new TraceDemo();
p.trace(args[0]);
}
}
OUTPUT
CONCLUSION
Thus the java program to simulate trace route command was executed successfully.
13
Experiment Score /10
EX. NO.:2 Date of
Completion Additional Credits
CREATE SOCKET FOR HTTP FOR WEB PAGE UPLOAD AND DOWNLOAD
OBJECTIVE
To create the HTTP socket for web page upload and download using java programming.
OUTCOME
Students gain knowledge in understanding subnetting and implement using JAVA.
ALGORITHM
PROGRAM
//File Upload and Download Code Example
import javax.swing.*;
import java.net.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
14
BufferedImage img = null;
soc=new Socket("localhost",4000);
dos.write(bytes, 0, bytes.length);
System.out.println("Image sent to server. ");
dos.close();
out.close();
soc.close();
}
}
Server
import java.net.*;
import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.*;
class Server {
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();
f.add(l);
f.pack();
f.setVisible(true);
}
}
OUTPUT
16
CONCLUSION
Thus HTTP socket for web page upload and download using java was written and executed
successfully.
17
Experiment Score /10
EX. NO.:3(a) Date of
Completion Additional Credits
AIM
To write a socket program for implementation of echo.
ALGORITHM
CLIENT SIDE
1. Start the program.
2. Create a socket which binds the Ip address of server and the port address to acquire service.
3. After establishing connection send a data to server.
4. Receive and print the same data from server.
5. Close the socket.
6. End the program.
SERVER SIDE
ECHO CLIENT
import java.io.*;
import java.net.*;
public class eclient
{
String line;
DataInputStream is,is1;
PrintStream os;
try
{
c=new Socket("localhost",8080);
}
catch(IOException e)
{
System.out.println(e);
}
try
{
os=new PrintStream(c.getOutputStream());
is=new DataInputStream(System.in);
is1=new DataInputStream(c.getInputStream());
do
{
System.out.println("client");
line=is.readLine();
os.println(line);
if(!line.equals("exit"))
System.out.println("server:"+is1.readLine());
}while(!line.equals("exit"));
}
catch(IOException e)
{
System.out.println("socket closed");
}}}
Echo Server:
import java.io.*;
import java.net.*;
import java.lang.*;
public class eserver
{
public static void main(String args[])throws IOException
{
ServerSocket s=null;
String line;
22
DataInputStream is;
PrintStream ps;
Socket c=null;
try
{
s=new ServerSocket(8080);
}
catch(IOException e)
{
System.out.println(e);
}
try
{
c=s.accept();
is=new DataInputStream(c.getInputStream());
ps=new PrintStream(c.getOutputStream());
while(true)
{
line=is.readLine();
System.out.println("msg received and sent back to client");
ps.println(line);
}
}
catch(IOException e)
{
System.out.println(e);
}
}
}
OUTPUT
CLIENT
Enter the IP address 127.0.0.1
CONNECTION ESTABLISHED
Enter the data SRM
Client received SRM
SERVER
CONNECTION ACCEPTED
Server received SRM
RESULT Thus the program for simulation of echo server was written & executed
23
Experiment Score /10
EX. NO.:3(b) Date of
Completion Additional Credits
AIM
ALGORITHM
CLIENT
1. Start the program
2. Include necessary package in java
3. To create a socket in client to server.
4. The client establishes a connection to the server.
5. The client accept the connection and to send the data from client to server.
6. The client communicates the server to send the end of the message
7. Stop the program.
SERVER
1. Start the program
2. Include necessary package in java
3. To create a socket in server to client
4. The server establishes a connection to the client.
5. The server accept the connection and to send the data from server to client and
6. vice versa
7. The server communicate the client to send the end of the message.
8. Stop the program.
PROGRAM
TCPserver1.java
24
import java.net.*;
import java.io.*;
public class TCPserver1
{
public static void main(String arg[])
{
ServerSocket s=null;
String line;
DataInputStream is=null,is1=null;
PrintStream os=null;
Socket c=null;
try
{
s=new ServerSocket(9999);
}catch(IOException e)
System.out.println(e);
} try
{
c=s.accept();
is=new
DataInputStream(c.getInputStream());
is1=new DataInputStream(System.in);
os=new
PrintStream(c.getOutputStream()); do
{
line=is.readLine();
System.out.println("Client:"+line);
System.out.println("Server:");
line=is1.readLine();
os.println(line);
25
}
while(line.equalsIgnoreCase("quit")==false);
is.close();
os.close();
}
catch(IOException e)
{
System.out.println(e);
}
}
}
TCPclient1.java
import java.net.*;
import java.io.*;
public class TCPclient1
{
public static void main(String arg[])
{
Socket c=null;
String line;
DataInputStream is,is1;
PrintStream os;
try
{
c=new Socket("10.0.200.36",9999);
}
catch(IOException e)
{
26
System.out.println(e);
}
try
{
os=new PrintStream(c.getOutputStream());
is=new DataInputStream(System.in);
is1=new DataInputStream(c.getInputStream());
do
{
System.out.println("Client:");
line=is.readLine();
os.println(line);
System.out.println("Server:" + is1.readLine());
}
while(line.equalsIgnoreCase("quit")==false);
is1.close();
os.close();
}
catch(IOException e)
{
System.out.println("Socket Closed!Message Passing is over");
}}
OUTPUT:
SERVER
C:\Program Files\Java\jdk1.5.0\bin>javac TCPserver1.java
Note: TCPserver1.java uses or overrides a deprecated API.
Note: Recompile with -deprecation for details.
C:\Program Files\Java\jdk1.5.0\bin>java TCPserver1
27
Client: Hai Server
Server:Hai Client
Client: How are you
Server:Fine
Client: quit
Server:quit
CLIENT
C:\Program Files\Java\jdk1.5.0\bin>javac TCPclient1.java
Note: TCPclient1.java uses or overrides a deprecated API.
Note: Recompile with -deprecation for details.
C:\Program Files\Java\jdk1.5.0\bin>java TCPclient1
Client:Hai Server
Server: Hai Client
Client:How are you
Server: Fine
Client:quit
Server: quit
RESULT
Thus the above program a client-server application for chat using TCP / IP was and
successfully.executed
28
Experiment Score /10
EX. NO.:3(c) Date of
Completion Additional Credits
AIM
To Perform File Transfer in Client & Server Using TCP/IP.
ALGORITHM
CLIENT SIDE
1. Start.
2. Establish a connection between the Client and Server.
3. Socket ss=new Socket(InetAddress.getLocalHost(),1100);
4. Implement a client that can send two requests.
i) To get a file from the server.
ii) To put or send a file to the server.
5. After getting approval from the server ,the client either get file from the server or send
6. file to the server.
SERVER SIDE
1. Start.
2. Implement a server socket that listens to a particular port number.
3. Server reads the filename and sends the data stored in the file for the„get‟ request.
4. It reads the data from the input stream and writes it to a file in theserver for the „put‟
instruction.
5. Exit upon client‟s request.
6. Stop.
PROGRAM
CLIENT SIDE
import java.net.*;
29
import java.io.*;
public class FileClient{
public static void main (String [] args ) throws
IOException { int filesize=6022386; // filesize temporary
hardcoded long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
// localhost for testing
Socket sock = new Socket("127.0.0.1",13267);
System.out.println("Connecting...");
// receive file
byte [] mybytearray = new byte [filesize];
InputStream is = sock.getInputStream();
FileOutputStream fos = new
FileOutputStream("source-copy.pdf"); BufferedOutputStream
bos = new BufferedOutputStream(fos); bytesRead =
is.read(mybytearray,0,mybytearray.length); current =
bytesRead;
do {
bytesRead =
is.read(mybytearray, current,
(mybytearray.length-current)); if(bytesRead >= 0) current
+= bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray, 0 ,
current);
bos.flush();
long end =
System.currentTimeMillis();
System.out.println(end-start);
bos.close();
30
sock.close();
}}
SERVER SIDE
import java.net.*;
import java.io.*;
public class FileServer
{
public static void main (String [] args ) throws
IOException { ServerSocket servsock = new
ServerSocket(13267); while (true) {
System.out.println("Waiting..."); Socket sock =
servsock.accept(); System.out.println("Accepted
connection : " + sock); File myFile = new File
("source.pdf");
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
sock.close();
}}}
OUTPUT
SERVER OUTPUT
C:\Program Files\Java\jdk1.6.0\bin>javac FServer.java
31
C:\Program Files\Java\jdk1.6.0\bin>java FServer
Waiting for clients...
Connection Established
Client wants file:network.txt
CLIENT OUTPUT
C:\Program Files\Java\jdk1.6.0\bin>javac
FClient.java C:\Program
Files\Java\jdk1.6.0\bin>java FClient Connection
request.....Connected Enter the filename:
network.txt
Computer networks: A computer network, often simply referred to as a network, is acollection of
computers and devices connected by communications channels thatfacilitates communications
among users and allows users to shareresources with other user
RESULT
32
Experiment Score /10
EX.NO.: 4 Date of
Completion Additional Credits
OBJECTIVE
To implement a DNS server and client in java using UDP sockets.
OUTCOME
Students become expertise to write socket program for DNS in java using UDP sockets.
ALGORITHM
Server
1. Define a array of hosts and its corresponding IP address in another array
2. Create a datagram socket
3. Create a datagram packet to receive client request
4. Read the domain name from client to be resolved
5. Lookup the host array for the domain name
6. If found then retrieve corresponding address
7. Construct a datagram packet to send response back to the client
8. Repeat steps 3-7 to resolve further requests from clients
9. Close the server socket
10. Stop.
Client
1. Create a datagram socket
2. Get domain name from user
3. Construct a datagram packet to send domain name to the server
4. Create a datagram packet to receive server message
5. If it contains IP address then display it, else display "Domain does not exist"
6. Close.
33
PROGRAM
}
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";
34
senddata = capsent.getBytes();
DatagramPacket pack = new
DatagramPacket(senddata,
senddata.length,ipaddress,port);
serversocket.send(pack);
serversocket.close();
}}}
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();
}}
35
OUTPUT
CONCLUSION
Thus domain name requests by the client are resolved into their respective logical address
using lookup method.
36
Experiment Score /10
EX. NO.:5(a) Date of
Completion Additional Credits
OBJECTIVE
Acquire knowledge on ARP and UDP concepts and can easily exhibit it using Java programming.
OUTCOME
Students gain knowledge in understanding ARP and implement using Java.
ALGORITHM
SERVER
1. Create a server socket.
2. Accept client connection.
3. Read IP address from the client request
4. Check its configuration file and compare with its logical address.
5. If there is a match, send the host physical address.
6. Stop
CLIENT
1. Create a socket.
2. Send IP address to the target machine
3. Receive target's response
4. If it is a MAC address then display it and go to step 6
5. Display "Host not found"
6. Stop
PROGRAM
//ARP Server -- arpserver.java
import java.io.*;
import java.net.*;
class arpserver
{
public static void main(String args[])throws IOException
{
try
{
ServerSocket soc = new ServerSocket(2500);
System.out.println("Server started");
40
Socket client = null;
client = soc.accept();
String str;
PrintStream ps = new PrintStream(client.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
Runtime r = Runtime.getRuntime();
Process p = r.exec("ifconfig eth0");
BufferedReader pin=new BufferedReader(new
InputStreamReader(p.getInputStream())); String haddr = "";
String ipaddr = br.readLine();
int flag = 0;
while((str = pin.readLine())!=null)
{
System.out.println(str);
if((str.indexOf("HWaddr")) != -1)
{
int tlen = str.length();
int hlen = tlen - 19;
haddr = str.substring(hlen,tlen);
}
else if ((str.indexOf(ipaddr)) != -1)
{
flag = 1;
}
}
if (flag == 1)
ps.println(haddr);
ps.close();
br.close();
pin.close();
client.close();
soc.close();
}
catch(IOException io)
{
System.err.println("Exception : " + io.toString());
}}}
OUTPUT
42
CONCLUSION
Thus the java program to simulate ARP protocol was executed successfully.
45
Experiment Score /10
EX. NO.:5(b) Date of
Completion Additional Credits
OBJECTIVE
To simulate RARP protocol using java language.
OUTCOME
Students gain knowledge in understanding RARP protocol using Java.
ALGORITHM
SERVER
1. Create a server socket.
2. Accept client connection.
3. Read MAC address from the client request
4. Check its configuration file and compare with its physical address.
5. If there is a match, send the host logical address.
6. Stop
CLIENT
1. Create a socket.
2. Send physical address to the target machine
3. Receive target's response
4. If it is a IP address then display it and go to step 6
5. Display "Host not found"
6. Stop
PROGRAM
//RARP Server -- rarpserver.java
import java.io.*;
import java.net.*;
class rarpserver
{
public static void main(String args[])throws IOException
{
try
{
ServerSocket soc = new ServerSocket(5000);
System.out.println("Server started");
Socket client = null;
client = soc.accept();
46
String str;
PrintStream ps = new
PrintStream(client.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
Runtime r = Runtime.getRuntime();
Process p = r.exec("ifconfig eth0");
BufferedReader pin = new BufferedReader(new
InputStreamReader(p.getInputStream())); String ipaddr = "";
String haddr = br.readLine();
int flag = 0;
while((str = pin.readLine())!=null)
{
System.out.println(str);
if ((str.indexOf(haddr)) != -1)
{
flag = 1;
}
else if((str.indexOf("inet addr")) != -1)
{
int pos = str.indexOf("inet addr:") + 10;
int offset = pos + 13;
ipaddr = str.substring(pos,offset);
}
}
if (flag == 1)
ps.println(ipaddr);
ps.close();
br.close();
pin.close();
client.close();
soc.close();
}
catch(IOException io)
{
System.err.println("Exception : " + io.toString());
}
}
}
//RARP Client -- rarpclient.java
import java.io.*;
import java.net.*;
class rarpclient
{
public static void main(String args[])
{
47
try
{
Socket client = new Socket("localhost", 5000);
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
PrintStream ps = new
PrintStream(client.getOutputStream());
String haddr,ipaddr = null;
BufferedReader sin = new BufferedReader(new
InputStreamReader(client.getInputStream()));
System.out.print("Enter the physical address : ");
haddr = br.readLine();
ps.println(haddr);
ipaddr = sin.readLine();
if (ipaddr == null)
System.out.println("Host does not exist");
else
System.out.println("Logical Address " + ipaddr);
ps.close();
br.close();
client.close();
}
catch(IOException io)
{
System.err.println(io.toString());
}}}
OUTPUT
48
Experiment Score /10
EX. NO.:6(a) Date of
Completion Additional Credits
Introduction
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. Ever since, several
revolutions and revisions have marked the growing maturity of the tool, thanks to substantial
contributions from the players in the field. Among these are the University of California and Cornell
University who developed the REAL network simulator,1 the foundation which NS is based on.
Since 1995 the Defense Advanced Research Projects Agency (DARPA) supported development
of NS through the Virtual Inter Network Test bed (VINT) project. Currently the National Science
Foundation (NSF) has joined the ride in development. Last but not the least, the group of Researchers
and developers in the community are constantly working to keep NS2 strong and versatile.
Basic Architecture
Figure 2.1 shows the basic architecture of NS2. NS2 provides users with anexecutable
command ns
52
which take 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. Before proceeding further, the readers are encouraged to
learn C++ and OTcl languages. We refer the readers to [14] for the detail of C++, while a brief tutorial
of Tcl and OTcl tutorial are given in Appendices A.1 and A.2, respectively.
NS2 provides a large number of built-in C++ objects. It is advisable to use these C++ objects to
set up a simulation using a Tcl simulation script. However, advance users may find these objects
insufficient. They need to develop their own C++ objects, and use a OTcl configuration interface to put
together these objects. After simulation, NS2 outputs either text-based or animation-based simulation
results. To interpret these results graphically and interactively, tools such as NAM (Network AniMator)
and XGraph are used. To analyze a particular behavior of the network, users can extract a relevant
subset of text-based data and transform it to a more conceivable presentation.
CONCEPT OVERVIEW
NS uses two languages because simulator has two different kinds of things it needs to do. On
one hand, a detailed simulation of protocols requires a systems programming language which can
efficiently
53
manipulate bytes, packet headers, and implement algorithms that run over large data sets. For
these tasks run-time speed is important and turn-around time (run simulation, find bug, fix bug,
recompile, re-run) is less important. On the other hand, a large part of network research involves
slightly varying parameters or configurations, or quickly exploring a number of scenarios.
In these cases, iteration time (change the model and re-run) is more important. Since
configuration runs once (at the beginning of the simulation), run-time of this part of the task is less
important. NS meets both of these needs with two languages, C++ and OTcl.
SIMULATOR INITIALIZATION
When a new simulation object is created in tcl, the initialization procedure performs the
following operations:
The simulator is an event-driven simulator. There are presently four schedulers available in the
simulator, each of which is implemented using a different data structure: a simple linked-list, heap,
calendar queue (default), and a special type call called “real-time”. Each of these is described below.
The scheduler runs by selecting the next earliest event, executing it to completion and returning
to execute the next event. Unit of time used by scheduler is seconds. Presently, the simulator is
single-threaded and only one event in execution at any given time. If more than one event are
scheduled to execute at the same time, their execution is performed on the first scheduled – first
dispatched manner. Simultaneous events are not reordered anymore by schedulers (as it was in earlier
versions) and all schedulers should yield the same order of dispatching given the same input.
NODE BASICS
The basic primitive for creating a node is set ns [new Simulator] $ns node
54
The instance procedure node constructs a node out of simpler classifier objects (Section 5.4). The Node
itself is a standalone class in OTcl. However, most of the components of the node are themselves
TclObjects. The typical structure of a (unicast) node is as shown in Figure 5.1. This simple structure
consists of two TclObjects: an address classifer (classifer_) and a port classifier (dmux_). The function
of these classifiers is to distribute incoming packets to the correct agent or outgoing link.
Set ns [new Simulator]: generates an NS simulator object instance, and assigns it to variable
ns.The "Simulator" objects has member functions that do the following:
Create connections between agents (ex. make connection between a "tcp" and "sink")
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.
55
Procfinish {}: is called after this simulation is over by the command $ns at 5.0 "finish". In this
function, post-simulation processes are specified.
setn0 [$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"andns-2/tcl/libs/ns-node.tcl".
$ns duplex-link node1 node2 bandwidth delay queue-type: creates two simplex links of
specified bandwidth and delay, and connects the two specified nodes. In NS, the output queue of a
node isimplemented 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.
$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.
settcp [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.
56
To create agents or traffic sources, a user should know the class names these objects
(Agent/TCP,
$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.
$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 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.
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.
http://nsnam.isi.edu/nsnam/index.php/Downloading_and_installing_ns-2
After downloading, copy of ns-allinone-2.34.tar.gz from above link, the following steps executed:
57
% ./install
Once following message comes:
(Note: In case there is a failure, as it happens with me, you first need to check what Linux platform
you are using. In my case it is Ubuntu-9.10 version. And in such case you need to provide the UNIX
command and make some modification in „configuration‟ file as suggested in following link:
http://lotti.netsons.org/2009/12/install-ns-allinone-2-34-on-ubuntu-9-10/
Then again type following command: (under directory: …./ns-allinone-2.34)
% ./install
This hopefully will complete successful installation and he below message will come.
Nam has been installed successfully.
Ns-allinone package has been installed successfully.
Next step is to link LD_LIBRARY_PATH environment variable by giving following commands: (if
you are using „sh‟ or „bash‟ – as in my case).
58
Experiment Score /10
EX. NO.:6(b) Date of
Completion Additional Credits
OBJECTIVE
Acquire TCL scripting skills to Implement and simulate congestion control using NS2
simulator.
OUTCOME:
Students become expertise to write tcl script to Implement and simulate congestion control
using NS2 simulator.
ALGORITHM
Step 1: Start the program
Step 2: Create the trace file and NAM file.
Step 3: Setup the topology object
Step 4: Create nodes and set duplex links between the nodes.
Step 5: Create nodes and attach them to the queue, DROPTAIL
Step 6: Configure the nodes and provides initial location of nodes. Generation of
movements is done.
Step 7: Setup a TCP Connection between nodes
Step 8: Define a initialize positions for the nam window.
Step 9: Telling nodes when the simulation ends
Step 10: Ending nam and the simulation
PROGRAM
set ns [new Simulator]
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
59
set n3 [$ns node]
set n4 [$ns node]
Agent/TCP set_nam_tracevar_true
set tcp [new Agent/TCP]
$tcp set window 1
$tcp set maxcwnd 1
$tcp set fid 1
60
$ns attach-agent $n0 $tcp
proc finish {} {
global ns nf
$ns flush-trace
close $nf
OUTPUT
STOP WAIT PROTOCOL
PROGRAM://GO BACK
set ns [new Simulator]
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
CONCLUSION
Thus tcl programs were executed to simulate the performance of stop wait and Go back N protocol
using ns2.
PRACTICE EXERCISES
1. Write a TCL script to drop down the packets in particular link at specific time.
2. Write a TCL script to drop the packets in router and Endserver link at 1.6sec.
64
3. Write a TCL script to drop down the packets in same link at particular time intervals
4. TCL script to handle trace annotation.
5. Write a TCL script for display the nodes activity in simulation window using trace annotation
VIVA QUESTIONS
1. What command is used to stop RIP routing updates from exiting out an interface but still allow
the interface to receive RIP route updates?
2. If your routing table has a static, a RIP, and an IGRP route to the same network, which route
will be used to route packets by default?
3. Which command displays RIP routing updates?
4. What are the basic components of router
5. Explain routing table
6. What is distance vector routing protocol
7. Explain some basics of internet routing
8. What is static and dynamic routing
9. What are the fields included in routing table?
10. What is split horizon?
TECHNICAL QUESTIONS
1. Which one of the following algorithm is not used for congestion control?
A) traffic aware routing B) admission control
C) load shedding D) none of the above
2. The network layer concerns with
A) bits B) frames
C) packets D) none of the above
3. The 4 byte IP address consists of
A) n/w address B) host address
C) both A and B D) none of the above
4. The subnet gets increasingly loaded with packets causing increase in delay in the delivery of
packets, which can lead to more retransmission, and ultimately increasing more and more traffic. This is a
concept
called as _________
5. ______ is a static algorithm in which every incoming packet is sent out on every outgoing line
except
the one it arrives on. This method usually generates vast number of duplicate packets.
AIM:
To simulate TCP/UDP Performance Using Simulation Tool
PROGRAM:
set ns [new Simulator]
set lan [$ns newLan "$n3 $n4 $n5" 0.5Mb 40ms LL Queue/DropTail MAC/Csma/Cd
Channel]
# PPP
$ns at 125.0 "finish"
$ns run
70
OUTPUT:
RESULT:
Thus Carrier Sense Multiple Access Protocol - MAC Protocol is simulated in NS2
71
Experiment Score /10
EX.NO.:8(a) Date of
Completion Additional Credits
OBJECTIVE
Acquire tcl scripting skills to simulate link state routing protocol using NS2 simulator.
OUTCOME
Students become expertise to write tcl script to simulate link state routing protocol
using NS2
simulator.
PROGRAM
74
OUTPUT
CONCLUSION
Thus tcl programs were executed to simulate the performance of link state routing protocol
using
ns2
75
Experiment Score /10
EX. NO.:8(b) Date of
Completion Additional Credits
OBJECTIVE
Acquire tcl scripting skills to simulate distance vector routing protocol using NS2 simulator.
OUTCOME
Students become expertise to write tcl script to simulate distance vector routing protocol using
NS2
simulator.
PROGRAM
set ns [new Simulator]
set nf [open out.nam w]
$ns namtrace-all $nf
set tr [open out.tr w]
$ns trace-all $tr
proc finish {} {
global nf ns tr
$ns flush-trace
close $tr
exec nam out.nam &
exit 0
}
76
set tcp [new Agent/TCP]
$ns attach-agent $n0 $tcp
$ns rtproto DV
$ns at 0.0 "$ftp start"
$ns at 0.0 "$cbr start"
$ns at 5.0 "finish"
$ns run
77
OUTPUT:
CONCLUSION
Thus tcl programs were executed to simulate the performance of distance vector routing
protocol using ns2.
79
80
Experiment Score /10
EX. NO.:9 Date of
Completion Additional Credits
AIM:
To simulate Distance Vector Multicast Routing Protocol in NS2
PROGRAM:
#define options
create-god $val(nn)
82
#configure the nodes
$ns node-config -adhocRouting DSR \
-llType LL \
-macType Mac/802_11 \
-ifqType Queue/DropTail/PriQueue \
-ifqLen 50 \
-antType Antenna/OmniAntenna \
-propType Propagation/TwoRayGround \
-phyType Phy/WirelessPhy \
-channelType Channel/WirelessChannel \
-topoInstance $topo \
-agentTrace ON \
-routerTrace ON \
-macTrace OFF \
-movementTrace ON
#generation of movements
$ns run
84
OUTPUT:
RESULT:
Thus Distance Vector Multicast Routing Protocol is simulated in NS2
Experiment Score /10
EX. NO.:10 Date of
Completion Additional Credits
OBJECTIVE
To implement error correction Using CRC( Cyclic redundancy check)
OUTCOMES
Students gain knowledge in error correction and cyclic redundancy check concepts.
ALGORITHM
PROGRAM
import java.io.*;
import java.util.*;
class crc_gen
{
public static void main(String args[]) throws
IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int[] data;
int[] div;
int[] divisor;
int[] rem;
int[] crc;
int data_bits, divisor_bits, tot_length;
*/ tot_length=data_bits+divisor_bits-1;
div=new int[tot_length];
rem=new int[tot_length];
crc=new int[tot_length];
/*------------------ CRC GENERATION-----------------------*/
for(int i=0;i<data.length;i++)
div[i]=data[i];
System.out.println();
System.out.println("CRC code : ");
for(int i=0;i<crc.length;i++)
System.out.print(crc[i]);
/*-------------------ERROR DETECTION---------------------*/
System.out.println();
System.out.println("Enter CRC code of "+tot_length+" bits : ");
for(int i=0; i<crc.length; i++)
crc[i]=Integer.parseInt(br.readLine());
91
System.out.println("THANK YOU.... :)");
}
{
int cur=0;
while(true)
{
for(int i=0;i<divisor.length;i++)
rem[cur+i]=(rem[cur+i]^divisor[i]);
if((rem.length-cur)<divisor.length)
break;
}
return rem;
}
}
OUTPUT:
92
CONCLUSION
Thus the java program to simulate error correction using CRC was executed successfully.