You are on page 1of 54

PANIMALAR ENGINEERING COLLEGE

DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS


REGISTER NO:211421244029

EX NO: 1(A) IMPLEMENTATION OF NETWORKING COMMANDS

AIM :

To use commands like tcpdump, netstat, ifconfig, nslookup and trace route
capture ping and trace route PDUs using a network protocol analyzer and
examine.

NETWORK COMMANDS

C:\tcpdump

tcpdump is a most powerful and widely used command-line packets


sniffer or package analyzer tool which is used to capture or filter TCP/IP
packets that received or transferred over a network on a specificinterface.

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:\>ifconfig

The ifconfig command is used to get the information of active network-


interfaces in a Unix-like operating system such as Linux, whereas
ipconfig is used in the Windows OS.

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:\>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:\>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
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029
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.

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:\>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.

RESULT
Thus the above list of primitive has been studied.
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029

EX NO: 1(B)
CAPTURE PING PDUS USING A NETWORK PROTOCOL ANALYZER

PROGRAM:
import java.util.*;
public class PingDemo
{
public void Ping(String host)
{
try
{
Process p=Runtime.getRuntime().exec("ping "+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[])
{
PingDemo p1=new PingDemo();
p1.Ping(args[0]);}}
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029

OUTPUT:
Pinging 172.16.25.5 with 32 bytes of data
Reply from 172.16.25.5 : bytes=32 time<1ms TTL=128
Reply from 172.16.25.5 : bytes=32 time<1ms TTL=64
Reply from 172.16.25.5 : bytes=32 time<1ms TTL=64
Reply from 172.16.25.5 : bytes=32 time<1ms TTL=64
Ping statistics for 172.16.25.5:
Packets: send=4 , received=4, lost=0 (0%loss);
Approximate round trip times in milli-seconds:
Minimum = 0 ms, maximum=0 ms, average=0 ms.

RESULT:
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029

EX NO:1(C)
CAPTURE TRACE ROUTE PDUS USING A NETWORK PROTOCOL ANALYZER
PROGRAM:
import java.util.*;
public class trace
{
public void tracefn(String host)
{
try{
Process P=Runtime.getRuntime().exec("tracert "+host);
Scanner s=new Scanner(P.getInputStream());
while(s.hasNextLine())
{
System.out.println(s.nextLine());
}
}
catch(Exception e)
{
System.out.println("error"+e);
}
}
public static void main(String args[])
{
trace t=new trace();
t.tracefn(args[0]);
}
}
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029

OUTPUT:
Tracing route to www.google.com [216.239.38.120] over a maximum of 30 hops.

RESULT:
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029
EX NO:2
CLIENT SOCKET PROGRAM FOR HTTP FOR WEB PAGE UPLOAD AND
DOWNLOAD
PROGRAM:
import java.net.*;
import java.io.*;
public class webpage
{
public static void main(String args[]) throws Exception
{
String image="https://www.w3schools.com";
String destnfile="scholls.html";
saveimage(image,destnfile);
}
public static void saveimage(String image,String destnfile) throws IOException
{
URL U=new URL(image);
InputStream is=U.openStream();
OutputStream os=new FileOutputStream(destnfile);
byte[] b=new byte[2048];
int length;
while((length=is.read(b))!=-1)
{
os.write(b,0,length);
}
System.out.println("file downloaded");
is.close();
os.close();}}
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029

OUTPUT:
>javac webpage.java
>java webpage
File downloaded

RESULT:
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029

EX NO:3(A)
ECHO CLIENT AND SERVER
PROGRAM:
FOR SERVER:
import java.io.*;
import java.net.*;
public class Server{
private Socket soc=null;
private ServerSocket Server=null;
private DataInputStream in;
public Server(int port)
{
try
{
Server=new ServerSocket(port);
System.out.println("server started");
System.out.println("waiting for a client");
soc=Server.accept();
System.out.println("client connected");
in=new DataInputStream(new BufferedInputStream(soc.getInputStream()));
String line=" ";
while(!line.equals("end"))
{try
{
line=in.readUTF();
System.out.println(line);
}catch(IOException e){System.out.println("error " +e);}
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029
}System.out.println("closing connection");
soc.close();
in.close();
}catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String [] args)
{
Server S=new Server(2000);
}
}
FOR CLIENT:
import java.io.*;
import java.net.*;
public class Client{
private Socket soc=null;
private DataInputStream in;
private DataOutputStream out;
public Client(String address,int port)
{
try
{
soc=new Socket(address,port);
System.out.println("connected");
in=new DataInputStream(System.in);
out=new DataOutputStream(soc.getOutputStream());
}
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029
Catch(UnknownHostException e)
{
System.out.print(e);
}
String line=" ";
while(!line.equals("end"))
{
try
{
line=in.readLine();
System.out.println(line);
}
catch(IOException e)
{
System.out.println("error " +e);
}
}
System.out.println("closing connection");
soc.close();
in.close();
out.close();
}
public static void main(String [] args)
{
Client c=new Client(“172.16.25.3”,5000);
}
}
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029

OUTPUT:
>java server
Server started
Waiting for client
Client connected
Hello
Fghf
end
closing connection
>java client
Connected
Hello
Fghf
end
Closing connection

RESULT:
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029

EX NO:3(B)
CLIENT-SERVER APPLICATION FOR CHAT
PROGRAM:
FOR SERVER:
import java.io.*;
import java.net.*;
class chatserver
{
public static void main(String args[]) throws Exception
{
ServerSocket SS=new ServerSocket(3333);
Socket s=SS.accept();
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
String str="",str1="";
while(!str.equals("bye"))
{

str=din.readUTF();
System.out.println("client says: "+str);
str1=br.readLine();
dout.writeUTF(str1);
dout.flush();
}
din.close();
dout.close();
s.close();
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029
SS.close();
}
}
FOR CLIENT:
import java.io.*;
import java.net.*;
class chatclient
{
public static void main(String args[]) throws Exception
{
Socket s= new Socket("localhost",3333);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
String str="",str1="";
while(!str.equals("bye"))
{
str=br.readLine();
dout.writeUTF(str);
dout.flush();
str1=din.readUTF();
System.out.println("server says: "+str1);
}
din.close();
dout.close();
s.close();
}}
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029

OUTPUT:
>java chatserver
Client sys: hello
Hello
Client says: how are you?
I am fine
Client says: bye
Bye
>java chatclient
Hello
Server says: hello
How are you?
Server says: I am fine
Bye

RESULT:
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029

EX NO:3(C)
FILE TRANSFER USING TCP
PROGRAM:
FOR SERVER:
import java.io.*;
import java.net.*;
public class fileserver
{
public static void main(String args[]) throws Exception
{
ServerSocket ss=new ServerSocket(6666);
Socket s= ss.accept();
FileInputStream fin=new FileInputStream("a.txt");
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
int r;
while((r=fin.read())!=-1)
{
dout.write((char)r);
}
System.out.println("file transfer completed");
s.close();
ss.close();
}
}
FOR CLIENT:
import java.io.*;
import java.net.*;
public class fileclient
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029
{
public static void main(String args[]) throws Exception
{
Socket s= new Socket("localhost",6666);
FileOutputStream fout=new FileOutputStream("b.txt");
DataInputStream din=new DataInputStream(s.getInputStream());
int r;
while((r=din.read())!=-1)
{
fout.write((char)r);
}
System.out.println("file transfer completed");
s.close();
}
}
OUTPUT:
>java fileserver
File transfer completed
>java fileclient
File transfer completed
a.text:
hello,everyone!
b.txt:
hello,everyone!

RESULT:
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029

Ex.No:4 SIMULATION OF DNS USING UDP SOCKET

Client:
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("127.0.0.1");
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();
}
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029
catch(Exception e)
{
System.out.println(e);
}
}
}
SERVER:
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();
System.out.println(s);
InetAddress addr=receiver.getAddress();
int port=receiver.getPort();
String ip[]={"165.165.80.80","165.165.79.1"};
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029
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);
}
}
}
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029
OUTPUT:
E:\nwlab>java dnsserver Press Ctrl + C to Quit
Request for host google.com
Request for host flipkart.com
Client E:\nwlab>java dnsclient
Enter the hostname : google.com
IP Address: 172.217.11.14
E:\nwlab>java dnsclient
Enter the hostname : flipkart.com IP Address: Host Not Found

RESULT:
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029

EX NO:5(A)
SIMULATION OF ARP PROTOCOL

PROGRAM:
CLIENT PROGRAM:
import java.io.*;
import java.net.*;
import java.util.*;
class Clientarp
{
public static void main(String args[]) throws IOException
{
try
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
Socket s=new Socket("localhost",6666);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
System.out.print("Enter the Logical address(IP) : ");
String str1=in.readLine();
dout.writeBytes(str1+'\n');
String str=din.readLine();
System.out.println("The Physical Address is : "+str);
s.close();
}
catch (Exception e)
{
System.out.println(e);
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029
}}}
SERVER PROGRAM:
import java.io.*;
import java.net.*;
import java.util.*;
class Serverarp
{
public static void main(String args[])
{
try
{
ServerSocket obj=new ServerSocket(6666);
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","192.168.7.3"};
String mac[]={"07:01:02:01:2C:4B","4A:30:10:21:10:1A","47:20:1B:2E:08:EE"};
for(int i=0;i<ip.length;i++)
{
if(str.equals(ip[i]))
{
dout.writeBytes(mac[i]+'\n');
break;
}
}
obj.close();
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}

OUTPUT:
D:\>javac Serverarp.java
Note: Serverarp.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
D:\java Serverarp
D:\>javac Clientarp.java
Note: Clientarp.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
D:\>java Clientarp
Enter the Logical address(IP) : 192.168.7.3
The Physical Address is : 47:20:1B:2E:08:EE

RESULT:
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029

EX NO:5(B)
SIMULATION RARP PROTOCOL
PROGRAM:
Client Program:
import java.io.*;
import java.net.*;
import java.util.*;
class Clientrarp
{
public static void main(String args[]) throws IOException
{
try
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
Socket s=new Socket("localhost",6666);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
System.out.print("Enter the Physical address(IP) : ");
String str1=in.readLine(); dout.writeBytes(str1+'\n');
String str=din.readLine();
System.out.println("The Logical Address is : "+str); s.close();
}catch (Exception e)
{
System.out.println(e);
}}}
SERVER PROGRAM:
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029
import java.io.*;
import java.net.*;
import java.util.*;
class Serverarp
{
public static void main(String args[])
{
try
{
ServerSocket obj=new ServerSocket(6666);
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","192.168.7.3"};
String mac[]={"07:01:02:01:2C:4B","4A:30:10:21:10:1A","47:20:1B:2E:08:EE"};
for(int i=0;i<mac.length;i++)
{
if(str.equals(mac[i]))
{
dout.writeBytes(ip[i]+'\n');
break;
}
}
obj1.close();
}
}
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029
catch(Exception e)
{
System.out.println(e);
}}}

OUTPUT:
D:\>javac Serverarp.java
D:\java Serverarp
D:\>javac Clientarp.java
D:\>java Clientarp
Enter the Physical address (MAC) : 4A:30:10:21:10:1A
The Logical Address is(IP): 165.165.79.1

RESULT:
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029

EX NO:06
DATE:
STUDY OF NS-2
AIM:
To study about NS2 simulator in detail.
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 behaviours.
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 Testbed (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 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.
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029
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 behaviour 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, detailed simulations of protocols requires a systems programming language which
can efficiently 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.
Tcl scripting
Tcl is a general purpose scripting language. [Interpreter]
• Tcl runs on most of the platforms such as Unix, Windows, and Mac.
• The strength of Tcl is its simplicity.
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029
• 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]
Wired TCL Script Components
Create the event scheduler
Open new files & turn on the tracing
Create the nodes
Setup the links
Configure the traffic type (e.g., TCP, UDP, etc)
Set the time of traffic generation (e.g., CBR, FTP)
Terminate the simulation

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
set ns [new Simulator]
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
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029
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
set tracefile1 [open out.tr w]
$ns trace-all $tracefile1 #Open the NAM trace file
set namfile [open out.nam w]

$ns namtrace-all $namfile


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 ―namfile
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.
Define a “finish‟ procedure
Proc finish { } {
global ns tracefile1 namfile
$ns flush-trace Close $tracefile1 Close $namfile Exec nam out.nam & Exit 0
}

Definition of a network of links and nodes


The way to define a node is
set n0 [$ns node]
Once we define several nodes, we can define the links that connect them. An example
of a definition of a link is:
$ns duplex-link $n0 $n2 10Mb 10ms DropTail

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 ―duplex-link
by Simplex- link.
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029
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:
#set Queue Size of link (n0-n2) to 20
FTP over TCP
TCP is a dynamic reliable congestion control protocol. It uses Acknowledgements created by
the destination to know whether packets are well received.
There are number variants of the TCP protocol, such as Tahoe, Reno, NewReno, Vegas. The
type of agent appears in the first line:
set tcp [new Agent/TCP]
The command $ns attach-agent $n0 $tcp defines the source node of the tcp connection.
The command set sink [new Agent /TCPSink] Defines the behavior of the destination node of
TCP and assigns to it a pointer called sink.
#Setup a UDP connection set udp [new Agent/UDP]
$ns attach-agent $n1 $udp set null [new Agent/Null]
$ns attach-agent $n5 $null
$ns connect $udp $null
$udp set fid_2
#setup a CBR over UDP connection
The below 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.
set cbr [new Application/Traffic/CBR]
$cbr attach-agent $udp
$cbr set packetsize_ 100
$cbr set rate_ 0.01Mb
$cbr set random_ false

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.
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029
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.

RESULT:
Thus the Network Simulator 2 is studied in detail.
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029

EX NO :7
DATE:
STUDY OF TCP/UDP PERFORMANCE USING NS2
AIM:
To implement the study of TCP/UDP performance using Network Simulator.
ALGORITHM:
1. Create a simulation object
2. Set routing protocol to routing
3. Trace packets and all links onto NAM trace and to trace file
4. Create right nodes
5. Describe their layout topology
6. Add a sink agent to node
7. Connect source and sink.
8. Observe the traffic route when link is up and down
9. View the simulated events and trace file analyze it
10. Start the scheduler

PROGRAM:
set ns [new Simulator]
# Define different colors
# for data flows (for NAM)
$ns color 1 Blue
$ns color 2 Red
# Open the NAM trace file set nf [open out.nam w]
$ns namtrace-all $nf
# Define a 'finish' procedure
proc finish {} {
global ns nf
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029
$ns flush-trace
# Close the NAM trace file close $nf
# Execute NAM on the trace file
exec nam out.nam &
exit 0
}
# Create four nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
# Create links between the nodes
$ns duplex-link $n0 $n2 2Mb 10ms DropTail
$ns duplex-link $n1 $n2 2Mb 10ms DropTail
$ns duplex-link $n2 $n3 1.7Mb 20ms DropTail
# Set Queue Size of link (n2-n3) to 10
$ns queue-limit $n2 $n3 10
# Give node position (for NAM)
$ns duplex-link-op $n0 $n2 orient right-down
$ns duplex-link-op $n1 $n2 orient right-up
$ns duplex-link-op $n2 $n3 orient right
# Monitor the queue for link (n2-n3). (for NAM)
$ns duplex-link-op $n2 $n3 queuePos 0.5
# Setup a TCP connection set tcp [new Agent/TCP]
$tcp set class_ 2
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink]
$ns attach-agent $n3 $sink
$ns connect $tcp $sink
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029
$tcp set fid_ 1
# Setup a FTP over TCP connection set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ftp set type_ FTP

# Setup a UDP connection set udp [new Agent/UDP]


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

# Setup a CBR over UDP connection set cbr [new Application/Traffic/CBR]


$cbr attach-agent $udp
$cbr set type_ CBR
$cbr set packet_size_ 1000
$cbr set rate_ 1mb
$cbr set random_ false

# Schedule events for the CBR and FTP agents


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

# Print CBR packet size and interval


puts "CBR packet size = [$cbr set packet_size_]" puts "CBR interval = [$cbr set interval_]"
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029
# Run the simulation
$ns run

RESULT:
Thus , the performance of TCP/UDP using Network Simulator was studied and output is
verified successfully.
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029

EX NO: 8
DATE:
SIMULATION OF DISTANCE VECTOR ROUTING ALGORITHM
AIM:
To simulate and study the Distance Vector routing algorithm using simulation.
SOFTWARE REQUIRED:
NS-2
THEORY:
Distance Vector Routing is one of the routing algorithm in a Wide Area Network for
computing shortest path between source and destination. The Router is one main devices used
in a wide area network. The main task of the router is Routing. It forms the routing table and
delivers the packets depending upon the routes in the table-either directly or via an
intermediate devices.Each router initially has information about its all neighbors. Then this
information will be shared among nodes.
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 tracefile.
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 distance vector 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]
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029
$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
}
set n0 [$ns node] set n1 [$ns node] set n2 [$ns node] set n3 [$ns node]
$ns duplex-link $n0 $n1 10Mb 10ms DropTail
$ns duplex-link $n1 $n3 10Mb 10ms DropTail
$ns duplex-link $n2 $n1 10Mb 10ms DropTail
$ns duplex-link-op $n0 $n1 orient right-down
$ns duplex-link-op $n1 $n3 orient right
$ns duplex-link-op $n2 $n1 orient right-up set tcp [new Agent/TCP]
$ns attach-agent $n0 $tcp
set ftp [new Application/FTP]
$ftp attach-agent $tcp
set sink [new Agent/TCPSink]
$ns attach-agent $n3 $sink set udp [new Agent/UDP]
$ns attach-agent $n2 $udp
set cbr [new Application/Traffic/CBR]
$cbr attach-agent $udp set null [new Agent/Null]
$ns attach-agent $n3 $null
$ns connect $tcp $sink
$ns connect $udp $null
$ns rtmodel-at 1.0 down $n1 $n3
$ns rtmodel-at 2.0 up $n1 $n3
$ns rtproto DV
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029
$ns at 0.0 "$ftp start"
$ns at 0.0 "$cbr start"
$ns at 5.0 "finish"
$ns run

RESULT:
Thus the Distance Vector Routing Algorithm was Simulated and studied.
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029

EX NO:9
DATE:
SIMULATION OF LINK STATE ROUTING ALGORITHM
AIM:
To simulate and study the link state routing algorithm using simulation.
SOFTWARE REQUIRED:
NS-2
THEORY:
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.
PROCEDURE:
The Dijkstra algorithm follows four steps to discover what is called the shortest path
tree(routing table) for each router:The algorithm begins to build the tree by identifying its
roots. The root router’s trees the router itself. The algorithm then attaches all nodes that can
be reached from the root. The algorithm compares the tree’s temporary arcs and identifies the
arc with the lowest cumulative cost. This arc and the node to which it connects are now a
permanent part of the shortest path tree. The algorithm examines the database and identifies
every node that can be reached from its chosen node. These nodes and their arcs are added
temporarily to the tree.
The last two steps are repeated until every node in the network has become a permanent part
of the tree.
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)
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029
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 nr [open thro.tr w]
$ns trace-all $nr
set nf [open thro.nam w]
$ns namtrace-all $nf
proc finish { } {
global ns nr nf
$ns flush-trace
close $nf
close $nr
exec nam thro.nam &
exit 0
}
for { set i 0 } { $i < 12} { incr i 1 } { set n($i) [$ns node]}
for {set i 0} {$i < 8} {incr i} {
$ns duplex-link $n($i) $n([expr $i+1]) 1Mb 10ms DropTail }
$ns duplex-link $n(0) $n(8) 1Mb 10ms DropTail
$ns duplex-link $n(1) $n(10) 1Mb 10ms DropTail
$ns duplex-link $n(0) $n(9) 1Mb 10ms DropTail
$ns duplex-link $n(9) $n(11) 1Mb 10ms DropTail
$ns duplex-link $n(10) $n(11) 1Mb 10ms DropTail
$ns duplex-link $n(11) $n(5) 1Mb 10ms DropTail
set udp0 [new Agent/UDP]
$ns attach-agent $n(0) $udp0
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0 set null0 [new Agent/Null]
$ns attach-agent $n(5) $null0
$ns connect $udp0 $null0
set udp1 [new Agent/UDP]
$ns attach-agent $n(1) $udp1
set cbr1 [new Application/Traffic/CBR]
$cbr1 set packetSize_ 500
$cbr1 set interval_ 0.005
$cbr1 attach-agent $udp1 set null0 [new Agent/Null]
$ns attach-agent $n(5) $null0
$ns connect $udp1 $null0
$ns rtproto LS
$ns rtmodel-at 10.0 down $n(11) $n(5)
$ns rtmodel-at 15.0 down $n(7) $n(6)
$ns rtmodel-at 30.0 up $n(11) $n(5)
$ns rtmodel-at 20.0 up $n(7) $n(6)
$udp0 set fid_ 1
$udp1 set fid_ 2
$ns color 1 Red
$ns color 2 Green
$ns at 1.0 "$cbr0 start"
$ns at 2.0 "$cbr1 start"
$ns at 45 "finish"
$ns run
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029

RESULT:
Thus the Link State Routing Algorithm was Simulated and studied.
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029

EX NO:10
DATE:
PERFORMANCE COMPARISON OF AODV,
DSDV AND DSR ROUTING PROTOCOL

AIM:
To write an NS2 program to compare the performance of AODV DSDV and DSR Routing
protocols.
ALGORITHM:
Step 1: Start the program.
Step 2: Define the necessary definition for defining AODV, DSDV and DSR Routing
protocol. Step 3: Execute the program.
Step 4: Compare the throughput of the routing protocols by running the awk file each
protocol for number of runs.
Step 5: Conclude the best routing protocol based on the result or by drawing the graph in
excel by using throughput values.
Step 6: Stop the program.
PROGRAM:
# Define options
set val(chan) Channel/WirelessChannel ;# channel type
set val(prop) Propagation/TwoRayGround ;
# radio-propagation model
set val(netif) Phy/WirelessPhy ;
# network interface type
set val(mac) Mac/802_11 ;
# MAC type
set val(ifq) Queue/DropTail/PriQueue ;
# interface queue type set val(ll) LL ;
# link layer type
set val(ant) Antenna/OmniAntenna ;
# antenna model
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029
set val(ifqlen) 50;
# max packet in ifq
set val(nn) 3 ;# number of mobilenodes set val(rp) AODV ;# routing
protocol
set val(x) 500 ;# X dimension of topography
set val(y) 400 ;# Y dimension of topography
set val(stop) 150 ;# time of simulation end set ns_ [new Simulator]
$ns_ use-newtrace
set tracefd [open simple.tr w]
set windowVsTime2 [open win.tr w] set namtrace [open simple.nam w]
$ns_ trace-all $tracefd
$ns_ namtrace-all-wireless $namtrace $val(x) $val(y) # set up topography object
set topo [new Topography]
$topo load_flatgrid $val(x) $val(y) create-god $val(nn)
# Create nn mobilenodes [$val(nn)] and attach them to the channel.
# configure the nodes
$ns_ node-config -adhocRouting $val(rp) \
-llType $val(ll) \
-macType $val(mac) \
-ifqType $val(ifq) \
-ifqLen $val(ifqlen) \
-antType $val(ant) \
-propType $val(prop) \
-phyType $val(netif) \
-channelType $val(chan) \
-topoInstance $topo \
-agentTrace ON \
-routerTrace ON \
-macTrace ON \
-movementTrace ON
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029

for {set i 0} {$i < $val(nn) } { incr i } { set node_($i) [$ns_ node]
}
# Provide initial location of mobilenodes
$node_(0) set X_ 5.0
$node_(0) set Y_ 5.0
$node_(0) set Z_ 0.0
$node_(1) set X_ 490.0
$node_(1) set Y_ 285.0
$node_(1) set Z_ 0.0
$node_(2) set X_ 150.0
$node_(2) set Y_ 240.0
$node_(2) set Z_ 0.0
# Generation of movements
$ns_ at 10.0 "$node_(0) setdest 250.0 250.0 3.0"
$ns_ at 15.0 "$node_(1) setdest 45.0 285.0 5.0"
$ns_ at 110.0 "$node_(0) setdest 480.0 300.0 5.0"
# Set a TCP connection between node_(0) and node_(1) set tcp [new Agent/TCP/Newreno]
$tcp set class_ 2
set sink [new Agent/TCPSink]
$ns_ attach-agent $node_(0) $tcp
$ns_ attach-agent $node_(1) $sink
$ns_ connect $tcp $sink
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ns_ at 10.0 "$ftp start"
# Printing the window size
proc plotWindow {tcpSource file} { global ns_
set time 0.01
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029
set now [$ns_ now]
set cwnd [$tcpSource set cwnd_] puts $file "$now $cwnd"
$ns_ at [expr $now+$time] "plotWindow $tcpSource $file" }
$ns_ at 10.1 "plotWindow $tcp $windowVsTime2"

# Define node initial position in nam for {set i 0} {$i < $val(nn)} { incr i } { # 30 defines the
node size for nam
$ns_ initial_node_pos $node_($i) 30
}
# Telling nodes when the simulation ends for {set i 0} {$i < $val(nn) } { incr i } {
$ns_ at $val(stop) "$node_($i) reset";
}
# ending nam and the simulation
$ns_ at $val(stop) "$ns_ nam-end-wireless $val(stop)"
$ns_ at $val(stop) "stop"
$ns_ at 150.01 "puts \"end simulation\" ; $ns_ halt" proc stop {} {
global ns_ tracefd namtrace
$ns_ flush-trace close $tracefd close $namtrace
}
PDR.awk
BEGIN {
recvdSize = 0
startTime = 400
stopTime = 0
}
{
event = $1 time = $3 node_id = $41 pkt_size = $37 level = $19
# Store start time
if (level == "AGT" && event == "s" && pkt_size >= 512) { if (time < startTime) {
startTime = time
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029
}
}
# Update total received packets' size and store packets arrival time if (level == "AGT" &&
event == "r" && pkt_size >= 512) {
if (time > stopTime) { stopTime = time
}
# Rip off the header hdr_size = pkt_size % 512 pkt_size -= hdr_size
# Store received packet's size recvdSize += pkt_size
}
}
END {
printf("Average Throughput[kbps] = %.2f\t\t StartTime=%.2f\tStopTime=%.2f\n",
(recvdSize/(stopTime-
startTime))*(8/1000),startTime,stopTime)
}
$ns_ run
SAMPLE OUTPUT:
AODV:
Average Throughput[kbps]: 340
Average Throughput[kbps]: 320
Average Throughput[kbps]: 360 DSDV:
Average Throughput[kbps]: 320
Average Throughput[kbps]: 310
Average Throughput[kbps]: 300 DSR:
Average Throughput[kbps]: 280
Average Throughput[kbps]: 270
Average Throughput[kbps]: 275

RESULT:
Thus the performance comparison of AODV, DSDV and DSR routing protocol was evauated
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029

EX.NO:11 IMPLEMENTATION OF CRC USING RAW SOCKETS


DATE:

AIM:
To write a program to establish connection between client and server using CRC
ALGORITHM:
CRC SERVER
Step 1: Start the program.
Step 2: Create an object for CRC 32.
Step 3: Declare s and create object for server socket. Step 4: For string tokenizer create an
object st.
Step 5: To update message use update command. Step 6: If s1 and s2 are equal then print a
message. Step 7: Catch the exception
Step 8 : stop the program
CRC CLIENT:-
Step 1: Start the program.
Step 2: Create an object for Inet Address and CRC 32, buffer. Step 3: Get the lang value for
server.
Step 4: Create object for DataInputStream. Step 5: Read the message line using str object.
Step 6: Now acknowledge will be received from object. Step 7: Catch the exception
Step 8: Stop the program.
PROGRAM
//crcserver.java
import java.io.*;
import java.net.*;
import java.util.zip.*;
import java.util.*;
class crcserver
{
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029
public static void main(String ar[])
{
try
{
CRC32 c= new CRC32();
ServerSocket ss= new ServerSocket(8000);
Socket s;
String str;
String sis[]=new String[500]; while(true)
{
s=ss.accept();
DataInputStream dis=new DataInputStream(s.getInputStream());
str=dis.readLine();
System.out.println("The message with the CRC value received is \n");
System.out.println(str);
StringTokenizer st= new StringTokenizer(str,"//");
int n=st.countTokens();
System.out.println("Number of token:"+n);
System.out.println("The token received are:");
for(int i=0;i<n;i++)
{
sis[i]=st.nextToken();
System.out.println(sis[i]);
}
long val1=Long.parseLong(sis[n-1]);
String s1=Long.toString(val1);
System.out.println("The calculate crc value is\n");
System.out.println(val1);
c.update(sis[0].getBytes());
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029
long val=c.getValue();
String s2=Long.toString(val);
if(s1.equals(s2))
{
String s3="Good Messsage";
PrintStream ps=new PrintStream(s.getOutputStream());
ps.println(s3);
}
System.out.println("The message from Client is accepted");
}
}
catch(Exception e)
{
System.out.println(e);}}}
//crcclient.java
import java.net.*;
import java.io.*;
import java.util.zip.*;
class crcclient
{
public static void main(String ar[])
{
try
{
InetAddress ia=InetAddress.getLocalHost();
CRC32 cc=new CRC32();
System.out.println("Please enter a message");
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
String s=br.readLine();
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029
Socket ss= new Socket(ia,8000);
cc.update(s.getBytes());
long val= cc.getValue();
ps=new PrintStream(ss.getOutputStream());
m=s+"//"+val;
System.out.println("The message and crc value is \n");
System.out.println(m);
ps.println(m);
DataInputStream dis= new DataInputStream(ss.getInputStream());
String str=dis.readLine();
System.out.println("The Acknowlegement received from serveris \n");
System.out.println(str);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
OUTPUT:
>javac crcclient.java
>java crcclient
Please enter a message
>Welcome
The message and crc value is Welcome // 936075699
The acknowledgement received from server is Good Message
RESULT:
Thus the Simulation of error correction code was done.
PANIMALAR ENGINEERING COLLEGE
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
REGISTER NO:211421244029

You might also like