Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
87 views52 pages

RECORD

The program writes a Java client to download a web page using TCP sockets. It creates a socket connection to the server on port 80 using HTTP. It then uses a BufferedReader on the output stream to read the response from the server and display the downloaded web page. It closes the connection once the request is serviced. Any errors in connecting to the server will result in a Malformed URL exception.

Uploaded by

ravi ravi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
87 views52 pages

RECORD

The program writes a Java client to download a web page using TCP sockets. It creates a socket connection to the server on port 80 using HTTP. It then uses a BufferedReader on the output stream to read the response from the server and display the downloaded web page. It closes the connection once the request is serviced. Any errors in connecting to the server will result in a Malformed URL exception.

Uploaded by

ravi ravi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 52

EX NO:1A USAGE OF COMMANDS LIKE TCPDUMP, NETSTAT, IFCONFIG,

NSLOOKUP AND TRACEROUTE


DATE:

AIM:
To study the usage of commands like tcpdump, netstat, ifconfig, nslookup and traceroute.

DESCRIPTION:
LIST OF COMMANDS:
TCPDUMP:
Tcpdump is a common packet analyzer that runs under the command line. It allows the user to
display TCP/IP and other packets being transmitted or received over a network to which the
computer is attached.
Tcpdump is a command line utility that allows you to capture and analyze network traffic going
through your system. It is often used to help troubleshoot network issues, as well as a security tool.
sudo yum install -y tcpdump
Capturing packets with tcpdump
use the command tcpdump -D to see which interfaces are available for capture
sudo tcpdump -D
1.eth0
2.virbr0
3.eth1
4.any (Pseudo-device that captures on all interfaces)
5.lo [Loopback]
Capture all packets in any interface by running this command:
sudo tcpdump -i any
To limit the number of packets captured and stop tcpdump, use the -c option:
sudo tcpdump -i any -c 5NETSTAT:
Displays active TCP connections, ports on which the computer is listening, Ethernet statistics, the
IP routing table, IPv4 statistics (for the IP, ICMP, TCP, and UDP protocols), and IPv6 statistics (for
the IPv6, ICMPv6, TCP over IPv6, and UDP over IPv6 protocols).
Syntax
netstat [-a] [-e] [-n] [-o] [-p Protocol] [-r] [-s] [Interval]
Examples:

NETSTAT:
Netstat –s provides statistics about incoming and outgoing traffic.

Command Explanation

netstat -a Shows all sockets , both listening and non-listening, all protocols like tcp, udp
etc
netstat -at Shows only tcp connections (-au shows only udp connections)

netstat -ant Shows all TCP connections with no dns resolution (show ip numbers instead).

netstat -al Shows only listening sockets

Also show pid and to which program each socket belongs, e add extra info like
sudo netstat -aep
the user. Run as root to see all pids.

netstat -s > file2.txt Shows network statistics

netstat -r Shows kernel routing information. This is the same output as route -e

Displays a table of all network interfaces.Add -e to get output similar to


netstat -i
ifconfig

netstat -ct displays tcp connections continuously

netstat -g Display multicast group membership information for IPv4 and IPv6

Display all services listening for tcp and udp, all free open ports on the local
netstat -lntu
machine

netstat -atnp | grep


Displays all current Established TCP connections
ESTA

NETBIOSSTAT:
Nbtstat (NetBios over TCP/IP) enables you to check information about NetBios names.
It helps us view the NetBios name cache (nbtstat -c) which shows the NetBios names and the
corresponding IP address that has been resolved (nbtstat -r) by a particular host as well as the
names that have been registered by the local system (nbtstat –n).
Syntax
nbtstat [-a RemoteName] [-A IPAddress] [-c] [-n] [-r] [-R] [-RR] [-s] [-S] [Interval]
Examples:
Nbtstat
Nbtstat -c
Nbtstat -n

IFCONFIG:
$ ifconfig
ifconfig is a system administration utility in Unix-like operating systems for network
interface configuration.
The utility is a command-line interface tool and is also used in the system startup scripts of many
operating systems. It has features for configuring, controlling, and querying TCP/IP network
interface parameters

NSLOOKUP:
Nslookup (Name Server lookup) is a UNIX shell command to query Internet domain name
servers.
Examples:
ns lookup espn.com

TRACEROUTE:
In computing, traceroute and tracert are computer networkdiagnostic commands for displaying
the route (path) 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);
Tracert: Determines the path taken to a destination by sending Internet Control Message Protocol
(ICMP) Echo Request messages to the destination with incrementally increasing Time to Live
(TTL) field values.
Examples:
To trace the path to the host named www.google.co.in use following command
tracert www.google.co.in
tracert -d www.google.com
To trace the path to the host named www.google.com and use the loose source route 10.12.0.1-
10.29.3.1-10.1.44.1, type:
tracert -j 10.12.0.1 10.29.3.1 10.1.44.1 www.google.com
Syntax
tracert [-d] [-h MaximumHops] [-j HostList] [-w Timeout] [TargetName]
OUTPUT:
RESULT:
Thus the usage of commands like tcpdump, netstat, ifconfig, nslookup and traceroute were
studied and the commands were executed successfully.
EX NO:1 B SIMULATING PING AND TRACEROUTE COMMANDS

DATE:

AIM:
To Write the java program for simulating Ping and Trace route commands.

ALGORITHM:
1.Start the program.
2.Create a new socket.
3.Get the local Host number using the function.
4.Using readline function get the systems time, length of data send and its TTL.
5. Stop the program.

PROGRAM:
CLIENT:
import java.io.*;
import java.net.*;
import java.util.Calendar;
class pingclient
{
public static void main(String args[])throws Exception
{
String str; int c=0; long t1, t2;
Socket s=new Socket("127.0.0.1",5555);
DataInputStream dis=new DataInputStream(s.getInputStream());
PrintStream out=new PrintStream(s.getOutputStream());
while(c<4)
{
t1=System.currentTimeMillis();
str="Welcome to network programming world"; out.println(str);
System.out.println(dis.readLine()); t2=System.currentTimeMillis();

System.out.println(";TTL="+(t2-t1)+"ms"); c++;
}
s.close();
}
}

SERVER:
import java.io.*;
import java.net.*;
import java.util.*;
import java.text.*;
class pingserver
{
public static void main(String args[])throws Exception
{
ServerSocket ss=new ServerSocket(5555);
Socket s=ss.accept();
int c=0;
while(c<4)
{
DataInputStream dis=new DataInputStream(s.getInputStream());
PrintStream out=new PrintStream(s.getOutputStream());
String str=dis.readLine();
out.println("Reply from"+InetAddress.getLocalHost()+";Length"+str.length());
c++;
}
s.close();
}
}
OUTPUT :
SERVER:

CLIENT:
RESULT:
Thus the program was implemented for simulating Ping and Trace route commands.

EX NO: 2 WRITE A HTTP WEB CLIENT PROGRAM TO DOWNLOAD A


WEB PAGE USING TCP SOCKETS
DATE:

AIM:
To write a java program for creating socket for HTTP web page upload and download.

CONCEPT:
HTTP
1. The Hypertext Transfer Protocol (HTTP) is a protocol used mainly to access data on the
World Wide Web.
2. HTTP functions as a combination of FTP and SMTP.
3. SMTP messages are stored and forwarded, but HTTP messages are delivered immediately.
4. The commands from the client to the server are embedded in a request message. The
contents of the requested file or other information are embedded in a response message.

ALGORITHM:
Step1: Set a server port as 80.
Step2: Using HTTP services create a Socket for server by specifying the server port
Step3: Use HTTP socket for connecting the client to the URL.
Step4: Use BufferedReader to output stream to place the response from the server by the client.
Step5: Close the Connection as soon the request is been serviced. Use Malformed URL exception
If any errors in grabbing the server

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);
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 f = new JFrame("Server");
ImageIcon icon = new ImageIcon(bImage);
JLabel l = new JLabel();
l.setIcon(icon);
f.add(l);
f.pack();
f.setVisible(true);
}
}

OUTPUT:
RESULT:
Thus the program for creating sockets for HTTP web page upload and download was
implemented.

EX NO: 3A ECHO SERVER AND ECHO CLIENT USING TCP SOCKETS


DATE:

AIM:

To write a java program to implement echo client server using TCP/IP.

ALGORITHM:
1. Start the program.
2. Include necessary package in java.
3. Create a socket from client to server.
4. The client establishes a connection to the server.
5. The client accepts the connection and sends data to server and the server to replay the echo
message to the client.
6. The client communicates the server to send the end of the message.
7. Stop the program.

PROGRAM:

ECHO SERVER:
import java.io.*;
import java.net.*;
public class EchoServer
{
public static void main(String args[]) throws Exception
{
try
{
int Port;
BufferedReader Buf =new BufferedReader(new
InputStreamReader(System.in));
System.out.print(" Enter the Port Address : " );
Port=Integer.parseInt(Buf.readLine());
ServerSocket sok =new ServerSocket(Port);
System.out.println(" Server is Ready To Receive a Message. ");
System.out.println(" Waiting ..... ");
Socket so=sok.accept();
if(so.isConnected()==true)
System.out.println(" Client Socket is Connected Succecfully. ");
InputStream in=so.getInputStream();
OutputStream ou=so.getOutputStream();
PrintWriter pr=new PrintWriter(ou);
BufferedReader buf=new BufferedReader(new
InputStreamReader(in));
String str=buf.readLine();
System.out.println(" Message Received From Client : " + str);
System.out.println(" This Message is Forwarded To Client. ");
pr.println(str);
pr.flush();
}
catch(Exception e)
{
System.out.println(" Error : " + e.getMessage());
}
}
}

ECHOCLIENT
import java.io.*;
import java.net.*;
public class EchoClient
{
public static void main(String args[]) throws Exception
{
try {
int Port;
BufferedReader Buf =new BufferedReader(new
InputStreamReader(System.in));

System.out.print(" Enter the Port Address : " );


Port=Integer.parseInt(Buf.readLine());
Socket sok=new Socket("localhost",Port);
if(sok.isConnected()==true)
System.out.println(" Server Socket is Connected Succecfully. ");
InputStream in=sok.getInputStream();
OutputStream ou=sok.getOutputStream();
PrintWriter pr=new PrintWriter(ou);
BufferedReader buf1=new BufferedReader(new
InputStreamReader(System.in));
BufferedReader buf2=new BufferedReader(new
InputStreamReader(in));
String str1,str2;
System.out.print(" Enter the Message : ");
str1=buf1.readLine();
pr.println(str1);
pr.flush();
System.out.println(" Message Send Successfully. ");
str2=buf2.readLine();
System.out.println(" Message From Server : " + str2);
}
catch(Exception e)
{
System.out.println(" Error : " + e.getMessage());
}
}
}

OUTPUT :
RESULT:

Thus the program to implement the concept of echo server and client using TCP was
executed and verified successfully.

EX NO: 3B CHAT USING TCP SOCKETS


DATE:

AIM:

To Write a java program to implement client-server application for chat using TCP.

ALGORITHM:
CLIENT:
1. Start the program.
2. Include necessary package in java.
3. Create a socket from client to server.
4. The client establishes a connection to the server.
5. The client accepts the connection and to send the data from client to server and vice versa.
6. The client communicates the server to send the end of the message.
7. Stop the program.

ALGORITHM:
SERVER:
1. Start the program.
2. Include necessary package in java.
3. Create a socket from server to client.
4. The server establishes a connection to the client.
5. The server accepts the connection and to send the data from server to client and vice versa.
6. The server communicates the client to send the end of the message.
7. Stop the program.
PROGRAM:

TCPCHATCLIENT.JAVA
import java.io.*;

import java.net.*;
public class TcpChatClient
{
@SuppressWarnings("deprecation")
public static void main(String args[]) throws
Exception{ InetAddress in =
InetAddress.getLocalHost();
Socket s = new Socket(in,3000);
System.out.println("CLIENT READY");
DataInputStream dis = new DataInputStream(s.getInputStream());
PrintStream ps = new PrintStream(s.getOutputStream());
try {
while (true) {
String st = new DataInputStream(System.in).readLine();
ps.println("CLIENT MESSAGE:"+" "+st);
st = dis.readLine();
System.out.println(st);
}
} catch (Exception e) {
// TODO: handle exception
System.out.println("ERROR:"+" "+e);
}
}
}
TCPCHATSERVER.JAVA import
java.net.*;
import java.io.*;
public class TcpChatServer
{
ServerSocket m_ServerSocket;
Socket clientSocket;
public TcpChatServer()
{
try
{
}
{
}
m_ServerSocket = new ServerSocket(3000);
catch(IOException ioe)
{
System.out.println("Could not create server socket at 12111. Quitting.");
System.exit(-1);
}
System.out.println("SERVER READY:");
System.out.println("Listening for
clients....."); int id = 0;
while(true)
{
try
{
clientSocket = m_ServerSocket.accept();
ClientServiceThread cliThread = new ClientServiceThread(clientSocket, id+
+); cliThread.start();
}
catch(IOException ioe)
{
System.out.println("Exception encountered on accept. Ignoring. Stack Trace
:"); ioe.printStackTrace();
}
}
}
public static void main (String[] args)
{
new TcpChatServer();
}
class ClientServiceThread extends Thread
{
Socket
m_clientSocket; int
m_clientID = -1;
boolean m_bRunThread = true;
ClientServiceThread(Socket s, int
clientID)
{
m_clientSocket = s;
m_clientID =
clientID;
}
public void run(){
try {
DataInputStream dis = new
DataInputStream(clientSocket.getInputStream()); PrintStream
ps = new PrintStream(clientSocket.getOutputStream());
while (true) {
String st =
dis.readLine
();
System.out.
println();
st = new
DataInputStream(System.in).readLi
ne(); ps.println("SERVER
MESSAGE:"+" "+st); }
} catch (Exception e) {
// TODO: handle
exception
System.out.println("
ERROR:"+" "+e);
}
}
}
}

OUTPUT:
RESULT:

Thus the program to implement the concept of chat application using


TCP was executed and verified successfully.
EX NO: 3C FILE TRANSFER USING TCP SOCKETS

DATE:

AIM:

To Write a program to transfer a file from server to client using TCP/IP.

ALGORITHM:
1. Start the program.
2. Include necessary package in java.
3. Create a socket in client to server.
4. The client establishes a connection to the server.
5. The client accepts the connection and transfers the file to server.
6. The server communicates the client that the file is received.
7. Stop the program.

PROGRAM:
SERVER:
ft2server.java
import java.io.*;
import java.net.*;
import java.util.*;
public class ft2server{
public static void main(String args[])throws IOException{
ServerSocket ss=null;
try{
ss=new ServerSocket(8081);
}
catch(IOException e)
{ System.out.println("Could
n't listen"); System.exit(0);
}
Socket cs=null; try{
cs=ss.accept();
System.out.println("Connection established"+cs);
}
catch(Exception e){
System.out.println("Accept failed");
System.exit(1);}
PrintWriter put=new PrintWriter(cs.getOutputStream(),true);
BufferedReader st=new BufferedReader(new InputStreamReader(cs.getInputStream()));
String s=st.readLine();
System.out.println("The requested file is:"+s);
File f=new File(s);
if(f.exists()){
BufferedReader d=new BufferedReader(new FileReader(s));
String line;
while((line=d.readLine())!=null){
put.write(line);
put.flush();}
d.close();
System.out.println("File transfered");
cs.close();
ss.close();
}}}
CLIENT:
ft2client.java
import java.io.*;
import java.net.*;
import java.util.*;
public class ft2client{
public static void main(String args[]) throws IOException{
Socket s=null;
BufferedReader get=null;
PrintWriter put=null;
try{
s=new Socket("192.168.2.203",8081);
get=new BufferedReader(new InputStreamReader(s.getInputStream()));
put=new PrintWriter(s.getOutputStream(),true);
}
catch(Exception e){
System.out.println(e);}
String u,f;
System.out.println("Enter the file name to transfer from server:");
DataInputStream dis=new DataInputStream(System.in);
f=dis.readLine();
put.println(f);
File f1=new File(f);
FileOutputStream fs=new FileOutputStream(f1);
while((u=get.readLine())!=null){
byte jj[]=u.getBytes();
fs.write(jj);
}
fs.close();
System.out.println("File received");
s.close();
}}
OUTPUT:

RESULT:

Thus the program to transfer a file from server to client using TCP was executed and
verified successfully.
EX NO: 4 DOMAIN NAME SYSTEM USING TCP& UDP

DATE:

AIM:

To write a java program to implement the concept of domain name system using TCP/UDP.

ALGORITHM:
1. Start the program.
2. Include the header files.
3. Declare the variables and assign the values.
4. In try selection, declare the runtime and process.
5. Input the domain name of domain name system.
6. Return the IP address of corresponding domain name to the requested client from domain name
server.
7. Stop the program.

PROGRAM:
CLIENT:
Clientdns12.java
import java.io.*;
import java.net.*;
import java.util.*;
class Clientdns12{
public static void main(String args[]){
try{
DatagramSocket client=new DatagramSocket();
InetAddress
addr=InetAddress.getByName("192.168.2.140");
byte[] sendbyte=new byte[1024];
byte[] receivebyte=new byte[1024];
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the DOMAIN NAME or IP adress:");
String str=in.readLine();
sendbyte=str.getBytes();
DatagramPacket sender=new
DatagramPacket(sendbyte,sendbyte.length,addr,1309); client.send(sender);
DatagramPacket receiver=new
DatagramPacket(receivebyte,receivebyte.length);
client.receive(receiver);
String s=new String(receiver.getData());
System.out.println("IP address or DOMAIN NAME: "+s.trim());
client.close();
}
catch(Exception e){
System.out.println(e);
}}}

SERVER:
Serverdns12.java
import java.io.*;
import java.net.*;
import java.util.*;
class Serverdns12{
public static void main(String args[]){
try{
DatagramSocket server=new DatagramSocket(1309);
while(true){
byte[] sendbyte=new byte[1024];
byte[] receivebyte=new byte[1024];
DatagramPacket receiver=new DatagramPacket(receivebyte,receivebyte.length);
server.receive(receiver);
String str=new String(receiver.getData());
String s=str.trim();
InetAddress addr=receiver.getAddress();
int port=receiver.getPort();
String ip[]={"165.165.80.80","165.165.79.1"};
String name[]={"www.aptitudeguru.com","www.downloadcyclone.blogspot.com"};
for(int i=0;i<ip.length;i++){
if(s.equals(ip[i])){
sendbyte=name[i].getBytes();
DatagramPacket sender=new DatagramPacket(sendbyte,sendbyte.length,addr,port);
server.send(sender);
break;
}
else if(s.equals(name[i])){
sendbyte=ip[i].getBytes();
DatagramPacket sender=new DatagramPacket(sendbyte,sendbyte.length,addr,port);
server.send(sender);
break;
}}
break;
}}
catch(Exception e){
System.out.println(e);
}}}
OUTPUT:

RESULT:

Thus the program to implement the concept of domain name system using TCP/UDP was
executed and verified successfully.
EX NO: 5 SIMULATION OF ARP/RARP PROTOCOL

DATE:

AIM:
Write a program to implement the concept of ARP/RARP protocol.

ALGORITHM:
1. Start the program.
2. Include necessary package in java.
3. Get MAC or physical address of system using ARP.
4. Display MAC or physical address of system using ARP.
5. Stop the program.

PROGRAM:
App.java
import java.io.*;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
public class App{
public static void main(String[] args){
InetAddress ip;
try{
ip = InetAddress.getLocalHost();
System.out.println("Current IP address : " + ip.getHostAddress());
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
byte[] mac = network.getHardwareAddress();
System.out.print("Current MAC address : ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < mac.length; i++){
sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
}
System.out.println(sb.toString());
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (SocketException e)
{
e.printStackTrace();
}}}

serverrarp.java
import java.io.*;
import java.net.*;
import java.util.*;
class Serverrarp
{
public static void main(String args[])
{
try{
ServerSocket obj=new ServerSocket(139);
Socket obj1=obj.accept();
while(true)
{
DataInputStream din=new DataInputStream(obj1.getInputStream());
DataOutputStream dout=new DataOutputStream(obj1.getOutputStream());
String str=din.readLine();
String ip[]={"165.165.80.80","165.165.79.1"};
String mac[]={"6A:08:AA:C2","8A:BC:E3:FA"};
for(int i=0;i<mac.length;i++)
{
if(str.equals(mac[i]))
{
dout.writeBytes(ip[i]+'\n'); break;
}
}
obj.close();
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Clientrarp.java

import java.io.*; import


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

DataInputStream din=new DataInputStream(clsct.getInputStream());


DataOutputStream dout=new DataOutputStream(clsct.getOutputStream());
System.out.println("Enter the Physical Addres (MAC):");
String str1=in.readLine();
dout.writeBytes(str1+'\n'); String
str=din.readLine();
System.out.println("The Logical address is(IP): "+str);
clsct.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}

OUTPUT:
RESULT:

Thus the implementation of ARP and RARP protocol was verified and implemented
successfully.

EX NO: 6 STUDY OF NETWORK SIMULATOR (NS) AND SIMULATION OF


CONGESTION CONTROL ALGORITHMS USING NS

DATE:

AIM:
To study about the network simulator version 2 package.
DESCRIPTION:
INTRODUCTION ABOUT NS 2:
NS (version 2) is an object-oriented, discrete event driven network simulator developed at UC
Berkely written in C++ and OTcl. It is used by networking research to simulate wired, wireless and
satellite networks.
NS started as a variant of the REAL network simulator in 1989 and has since been supported
by the VINT project and others. NS allows for the simulation of various protocols, applications,
routing, queue types etc. A graphical front end has been developed for use with Ns known as network
animator (nam). Alternatively trace files can be created for analysis, which can be displayed using
Xgraph, Microsoft Excel and many more.
NS is primarily useful for simulating local and wide area networks. Although NS is fairly easy
to use once you get to know the simulator, it is quite difficult for a first time user, because there are few
user-friendly manuals. Even though there is a lot of documentation written by the developers which has
in depth explanation of the simulator, it is written with the depth of a skilled NS user.

BACKGROUND OF NS 2:
Node types
Nodes in Ns are the hardware entities (hosts) within a simulation topology. Each simulation
requires an instance of the simulator class. Nodes are defined in a standalone class in Otcl. Two basic
node types exist unicast and multicast, which contain components that are TclObjects, which give them
the correct functionality for routing in a particular simulation.
The node can be configured to customize it for example to create a mobile node in a wireless
topology. Unicast is the default in Ns. Nodes contain a node entry object and classifiers but to get
started the two main classifiers defined for a node that are of concern here are an address classifier and
a port classifier which ensure incoming packets are sent to the correct agent or outgoing link. This gives
us our first two key words “Agent” and “Link” which allows us to look at a basic node. In the diagram
below there are two nodes, which have a link. The link can be either simplex or duplex.
Each node has an agent attached; this is the connection / protocol, which could be TCP. On top
of this agent sits an application, which puts traffic onto our network such as FTP. An agent is normally
software based.

[Fig-1. Node Construction]


An agent comes in two flavors, a Source agent and a sink agent. The source agent is the
generator of packet data and the sink node is the destination of the packet data. Lets call our nodes
node1 on the left and node2 on the right.
If TCP was added to node1 making it a source agent and we needed to send data to node2 a
TCPsink agent would have to be attached to node2. Once the two agents are attached an explicit
declaration is required to connect the two nodes. Alternatively UDP could have been used on node1
and a null agent sink on node2.
So a node has agents attached and applications attached to the agent only certain applications
should be attached to certain agents for example UDP and CBR we will discuss CBR in more detail
later. A node can have one or more links. A node can be a source or sink node or even both depending
on the topology.
Network protocols
IP[Internet Protocol]->A layer 3 Protocol. Comes in two versions IPV4, IPV6. This is a data-oriented
protocol that communicates data across a network that is used by both source and host.
TCP[Transmission Control Protocol]->IETF RFC 793 defines TCP. TCP is a connection-oriented
protocol. A highly reliable protocol that guarantees delivery. That is normally associated with IP in the
TCP/IP model.
UDP[User Datagram Protocol]->IETF RFC 768 defines the UDP transport protocol. UDP does not
guarantee delivery of a message.
HTTP[Hyper Text Transfer Protocol]->Is a request response protocol used on the World Wide Web
(WWW). Maintained by the W3C org. Defined in RFC2068.
POP3[Post Office Protocol version 3]->Used to retrieve emails from a server for a local client over
TCP/IP. Various RFC’s exist for POP3.
SNMP[Simple Network Management Protocol]->Used to monitor network-attached devices for
conditions.
SMTP [Simple Mail Transfer Protocol]->Used for e-mail transmission across the Internet.
SSH[Secure Shell]->Is an application and a protocol. Used for executing commands on a remote
computer.
IMAP[Internet Message Access Protocol]->Used for retrieving e-mails from a remote server. It
leaves a copy on the server as opposed to deleting.
NNTP[Network News Transfer Protocol]->Used by the Usenet Internet service.
LDAP[Lightweight Directory Access Protocol]->Used for accessing online directory services.
DHCP[Dynamic Host Control Protocol]->Dynamically Allocates IP addresses to clients on a LAN.
SPX[Sequenced Packet Exchange]->A Novell protocol used to manage Internet Package Exchange
(IPX).
BGP[Border Gateway Protocol]->Routing Protocol on the Internet. Used by ISP’s
EIGRP[Enhanced Interior Gateway Routing Protocol]->Cisco routing protocol based on IGRP but
can deal with classless interdomian routing
IGRP[ Interior Gateway Routing Protocol]->IGRP is a distance vector routing protocol designed by
Cisco. Used by routers to exchange routing data.
RIP[Routing Information protocol]->Allows routers to adapt dynamically to changing network
connections
PPTP[Point to Point Tunneling Protocol]->Used to establish a connection between two computers
using a phone line.
ARP[Address Resolution Protocol]->Is a method of finding a hosts Ethernet MAC address from its IP
address
MARS[ Multicast Address Resolution Server]->Multicasting is where a source sends a packet
simultaneously to multiple destinations. Some defined protocols are agents and some are traffic sources

Typical applications
Two common applications that are used in Ns, which most will have heard of are FTP and
Telnet. When we use these applications from a home or business Pc / workstation, we are in fact using
the client or traffic source part of the application. All forms of users from various locations use FTP
widely and this client software can be by different vendors. To transfer a file-using FTP we put traffic
on the network, but in order for us to complete this we need to connect to a FTP server (FTP daemon)
or the sink node.
Telnet works with the same type of principle in that it uses TCP as the agent with a client
application and traffic is placed on the on the network for example to gain a remote login to a server
(sink node). Other examples of typical applications are e-mail using SMTP all senders are using a client
(agent) which then transfers your e-mail by putting traffic on the network to connect via a e-mail server
(sink node).
This sink node may if required then become an agent to pass on the data to another sink node,
before the person you sent the e-mail to, client application requests the e-mail you sent from the sink
node. HTTP is another example using a web browser as a client, which puts traffic on the network to
connect to a web server (sink node). The more you think about it the more applications you could add
to the list.
Constant bit rate (CBR) data transfer
CBR reserves a constant amount of bandwidth during the connection set up even when idle. The
CBR service was conceived to support applications such as voice and video, which require jitter (small
time variations).
The source may send at a negotiated or lower rate at any time and for any duration. The
connection in Ns would normally be set up with a UDP agent and the traffic source would be CBR. In
the diagram below node0 and 1 are both using UDP and CBR, which are sending data via node2 to the
null agent sink node3. There is bandwidth congestion at node2 which means packets of data are being
dropped for example using a drop tail queue. This results in node3 not receiving all the data.

[Fig-2 Drop tail queue]


In CBR when packets are lost they are not re transmitted as receiving packets late in a voice or
video stream is of no use. The human eye and mind will normally fill in any small gaps. This is one
eason why CBR may run over UDP as there is no need to receive an acknowledgement. For streams of
data that require some form of order, TCP should be used.
Traffic generator function
In order to put traffic on a network we need to attach an agent to a node and attach the
application to the agent and link the source and sink nodes.
Set up a UDP connection with a variable name of udp and attach the UDP agent (variable name
$udp) to node1 (variable name $n1).
set udp [new Agent/UDP]
$ns attach-agent $n1 $udp
Set up a null agent sink node with a variable name of null. Attach the null agent (variable name
$null) to node3 (variable name $n3). Then connect the traffic source node (node1) to our sink node
(node3).

set null [new Agent/Null]


$ns attach-agent $n3 $null
$ns connect $udp $null
Set up a CBR over a UDP connection. Each Traffic source has various attributes, for example
the packet size is set to 1000 bytes.
set cbr [new Application/Traffic/CBR]
$cbr attach-agent $udp
$cbr set packet_size_ 1000
Schedule events for the CBR agent i.e. tell it when to send data and when to stop.
$ns at 0.1 "$cbr start"
$ns at 5.0 "$cbr stop"
COMPONENTS OF NS 2:
The structure of ns, including how to add a C++ patch (briefly)
Ns uses two languages C++ to implement protocols and Object Oriented Tcl (OTcl) to write
simulation scripts. Ns is an OTcl script interpreter that has a simulation event scheduler and network
libraries. So we write an Otcl script, which initiates an event scheduler. In the script we define the
topology of the network using objects and functions from the libraries.
Traffic is added to the network and told when to commence and when to end. This is handled by
the event scheduler, as is the termination of the simulation. The results from the interpreter can then be
analysed or graphically displayed using nam. Without getting to complicated data path
implementations are written and compiled by C++ in order to save processing time.
Once compiled these objects become available to the OTcl interpreter via an OTcl linkage. The
linkage creates a matching OTcl object and makes available to it functions and variables that are also
available to the linked C++ object. A class hierarchy in C++ (also called the compiled hierarchy), and a
similar class hierarchy within the OTcl interpreter (also called the interpreted hierarchy) are also
maintained between the linkage.
[Fig-5 Linkage [NIL01]]

[ Fig-6 Architecture [NIL01]]


If we look at the structure of Ns we develop and execute in Tcl using object libraries contained in
OTcl. The event scheduler and most network components are developed in C++ to give us the Ns
simulation. The Tclcl is the Tcl/C++ interface between OTcl and C++.
In order to enhance the functionality of Ns extensions are added. These extensions are
modifications to the C++ or OTcl source code. Alternatively these may be completely new agents or
traffic sources etc. As an example the event scheduler and network component object classes are
located in the Ns-2 directory. In the Ns-2 directory are UDP.h and UDP.cc, which are the C++ files used
to implement the UDP agent (this location may vary with different versions of Ns). Similarly the tcl/lib
directory contains the OTcl source code for node, links etc. To patch Ns to work with a new or modified
agent means the creation of C++ code, which will involve the creation of a class and possibly

a header file. A linkage has to be set up within the C++ class to ensure the OTcl can use instances of the
C++ class. Dependent on what is being written, a header file may have to be registered in the packet.h
and ns-packet.tcl.
An overview object modeling using C++
The object-oriented paradigm covers three main areas encapsulation, Inheritance and
polymorphism. C++ extends C by allowing new data types to be defined in a word it encapsulates C. A
class is a logical method that organises data and functions to be contained in the same structure. A class
contains members, which can be allocated permissions that are either public private or protected.
The public part is accessible from anywhere the class can be seen. The private part can only be
used by member functions that makeup the same class or from a friend class. Protected is similar to
private but with the exception of derived classes can also access the class. Each object is an instance of
a class, which has its own data and functions. Constructors and deconstructors are used with classes.
Inheritance allows us to build new classes from existing classes and hence reuse code.
Inheritance again comes in three forms public, private and protected. Member functions from the base
class are made available depending on the form to all derived classes.lymorphism meaning many
forms allows a collection of different object types to be manipulated uniformly through a generic
interface.
Polymorphism comes in three types virtual functions, function name overloading and operator
overloading. The inheritance hierarchy of related objects can be manipulated in the same way using
virtual functions. Function name overloading is when a function is declared more than once in a
program.
When a set of functions that perform a similar operation, overloading is used to collect them
under the same name. The compiler will then determine which function to call. Operators are defined
similar to functions but can be members or non-members of a class. Operators can take two arguments
and are either unary or binary.
We can see how C++ through Tclcl can allow us to create similar hierarchies in both C++ and
OTcl using the linkage, which allows members functions to be shared.
The role of the Tk/Tcl and OTcl command language
Tcl is a command line tool Tk is a graphical interface for Tcl. Tcl is used because of the fast
iteration time it takes to modify a simulation model and re run the script file. Tcl/Tk uses a simple
interface so users do not have to learn any complex languages such as C++.
OTcl as already discussed is built upon or encapsulates features of Tcl and as OTcl is object
oriented it is interfaced with C++ through the use of Tclcl. OTcl is the front-end to the simulator as it is
interpreted rather than compiled, the benefits for Ns is development speed rather than it’s slower
execution speed. So we could say OTcl is used for control as it allows us to design our simulations by
sharing member functions. OTcl is used for triggered actions. It also manipulates the existing objects
in C++.

BASICS OF USING NS 2:
 Download the software.
 Install NS 2 in your home directory.
- Compile the latest version of NS 2.
- Validate NS 2.
 Create your topology.
- Need to understand the real topology and the directory structure in NS 2.
- Modify the existing in C++/.tcl files.
- Create your own .tcl script for this.
 Execute the script.
- Analyze your result.
- To run, $ ns filename.tcl and this will then run the script and show the animation in
nam.
- Initially, NS2 instantiates C++ classes based on the tcl scripts.

- Output is in the form of Trace files.


To understand the simulation process more clearly, we are in need to know about two
features of NS 2.
(i) NAM Window
(ii) Trace file format
NAM Window:
Nam is a Tcl/TK based animation tool for viewing network simulation traces and real world
packet trace data. The design theory behind nam was to create an animator that is able to read large
animation data sets and be extensible enough so that it could be used indifferent network visualization
situations. Under this constraint nam was designed to read simple animation event commands from a
trace file. In order to handle large animation data sets a minimum amount of information is kept in
memory. Event commands are kept in the file and reread from the file whenever necessary.
The first step to use nam is to produce the trace file. The trace file contains topology
information, e.g., nodes, links, as well as packet traces. Usually, the trace file is generated by ns.
During an ns simulation, user can produce topology configurations, layout information, and packet
traces using tracing events in ns. However any application can generate a nam trace file.
When the trace file is generated, it is ready to be animated by nam. Upon startup, nam will read
the trace file, create topology, pop up a window, do layout if necessary, and then pause at time 0.
Through its user interface, nam provides control over many aspects of animation. These functionalities
will be described in detail in the USER INTERFACE section.
There are bugs in nam however each successive has become much more stable than the previous
one.
Starting nam
You can either start nam with the command 'nam <nam-file>'Where '<nam-file>' is the name
of a nam trace file that was generated by ns, or you can execute it directly out of the Tcl simulation
script for the simulation which you want to visualize. Below you can see a screenshot of a nam window
where the most important functions are being explained.
Sample output windows of nam:
Trace file format
Each trace line starts with an event (+, -, d, r) descriptor followed by the simulation time (in
seconds) of that event, and from and to node, which identify the link on which the event occurred.the
next information in the line before flags (appeared as "------" since no flag is set) is packet type and size
(in Bytes). Currently, NS implements only the Explicit Congestion Notification (ECN) bit, and the
remaining bits are not used.
The next field is flow id (fid) of IPv6 that a user can set for each flow at the input OTcl script.
Even though fid field may not used in a simulation, users can use this field for analysis purposes.
The fid field is also used when specifying stream color for the NAM display. The next two
fields are source and destination address in forms of "node.port".
The next field shows the network layer protocol's packet sequence number. Note that even
though UDP implementations do not use sequence number, NS keeps track of UDP packet sequence
number for analysis purposes.
The last field shows the unique id of the packet.
Fig: Trace File Format

SAMPLE CODE EXPLAINING ABOUT NS 2:


How to create a network object
To enable the simulation to run we need to create an instance of the simulator class. In the
example the instance is given the variable name ns.
#Create a simulator object
set ns [new Simulator]
Open trace files outX.tr for use with Xgraph and out.nam for nam. Multiple copies can be created.
#Open the trace files outX.tr for Xgraph and out.nam for nam
set f0 [open out0.tr w]
set f1 [open out1.tr w]
set f2 [open out2.tr w]
set nf [open out.nam w]
$ns namtrace-all $nf
A finish procedure needs to be created to close the output files, execute Xgraph and nam and exit.
#Define a 'finish' procedure
proc finish {} {
global ns nf f0 f1 f2
$ns flush-trace
#Close the NAM trace
file close $nf
#Close the output
files close $f0
close
$f1
close
$f2
#Execute xgraph to display the results
exec xgraph out0.tr out1.tr out2.tr -geometry 600x400 &
#Execute NAM on the trace
file exec nam out.nam &
exit 0
}
How to create network nodes
Create instances of node. In the example the instances are given the variable names n0 and n1.
#Create Six
nodes set n0
[$ns node] set
n1 [$ns node]
How to link nodes together to make a network
The code specifies what nodes are to be linked together including the link type and
parameters.
#Create links between the nodes
$ns duplex-link $n0 $n2 1Mb 10ms DropTail
$ns duplex-link $n1 $n2 1Mb 10ms DropTail
How to add a protocol to a network
A TCP agent is created with the variable name tcp and attached to node 0 (n0).
#Setup a TCP1
connection set tcp [new
Agent/TCP]
$tcp set class_ 2
$ns attach-agent $n0 $tcp
Next we create a sink node with the variable name sink and attach it to node 5 (n5).
Finally we connect the tcp agent to the sink.
set sink [new Agent/TCPSink]
$ns attach-agent $n5 $sink
$ns connect $tcp $sink

How to add a traffic source to the model


A FTP traffic source (application) is created with a variable name ftp and attached to the agent
tcp.
#Setup a FTP over TCP
connection set ftp [new
Application/FTP]
$ftp attach-agent $tcp
$ftp set type_ FTP
Plot a graph showing the output results from a simulation
In order to use Xgraph we need to create output files to store the results in. Each set of data is
stored in one trace file.
#Open the trace files outX.tr for
Xgraph set f0 [open out0.tr w]
set f1 [open
out1.tr w] set f2
[open out2.tr w]
In the finish procedure we need to close the output files and execute Xgraph specifying what
output files to use and the size of the window.
#Close the output
files close $f0
clos
e $f1
clos
e $f2
#Execute xgraph to display the results
exec xgraph out0.tr out1.tr out2.tr -geometry 600x400 &
In the example script procedures are used. In the first procedure UDP agents are attached to a
node.
By the nature of the procedure multiple agents can be added by calling the procedure
with the appropriate parameters.
#Create a UDP agent and attach it to the
node set source [new Agent/UDP]
$ns attach-agent $node $source
Secondly we add an exponential traffic source defining the parameters that will be used.
Again multiple traffic sources can be added by calling the procedure with the correct
parameters.
#Create an Exponential traffic agent and set its
properties set traffic [new
Application/Traffic/Exponential]
$traffic set packetSize_ $size
$traffic set burst_time_ $burst
Next we attach the traffic source to the agent. The second procedure counts how many
bytes the sink has received and calculates the bandwidth used in Mbit/s and writes it to the
specified output file in this case f0.
#Calculate the bandwidth (in MBit/s) and write it to the
files puts $f0 "$now [expr $bw0/$time*8/1000000]"
A Loss monitor agent is created and attached to a node
#Create five traffic sinks and attach them to the nodes
n2 n3 set sinkl1 [new Agent/LossMonitor]
$ns attach-agent $n2 $sinkl1
Variables are created which uses an expression to pass parameters back to the procedure
expo- traffic, which creates Traffic sources with the appropriate parameters.
#Create three traffic sources
set source0 [expo-traffic $n2 $sinkl1 200 2s 1s 100k]
Finally we call the record procedure to gather the data for output. The traffic sources are
told when to start and stop and define the duration of the simulation before running it.
#Start record procedure
$ns at 0.0 "record"
#Start the traffic sources
$ns at 0.1 "$source0 start"
#Stop the traffic sources
$ns at 5.0 "$source0 stop"
#Call the finish procedure after 5 seconds of simulation time
$ns at 5.2 "finish"
#Run the simulation
$ns run

The complete commented script that when run will invoke the nam and Xgraph. Two screen
shots are shown below of the result.

[ Fig Xgraph.]

RESULT:
Thus the study about network simulator version 2 package has been completed successfully.

You might also like