0% found this document useful (0 votes)
19 views63 pages

Computer Network Lab Record New

The document outlines the CS3591 Computer Network Laboratory Record Note, detailing various experiments related to computer networking, including the use of commands like tcpdump, netstat, and nslookup, as well as programming tasks like creating an HTTP web client and echo server using TCP sockets. Each experiment includes the date, experiment name, and instructions for execution. The document serves as a practical guide for students in the Computer Science branch to learn and apply networking concepts.

Uploaded by

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

Computer Network Lab Record New

The document outlines the CS3591 Computer Network Laboratory Record Note, detailing various experiments related to computer networking, including the use of commands like tcpdump, netstat, and nslookup, as well as programming tasks like creating an HTTP web client and echo server using TCP sockets. Each experiment includes the date, experiment name, and instructions for execution. The document serves as a practical guide for students in the Computer Science branch to learn and apply networking concepts.

Uploaded by

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

Department of Computer Science and Engineering

CS3591 – Computer Network Laboratory Record Note

Name : __________________________________________

Roll No. : ______________ Register No. ________________

Semester: V Branch: Computer Science


LIST OF EXPERIMENTS

Sl.No. Date Experiment Name Page No. Signature

Learn to use commands like tcpdump, netstat, ifconfig,


1 11.08.22 nslookup and traceroute. Capture ping and traceroute
PDUs using a network protocol analyzer and examine.

Write a HTTP web client program to download a web


2 26.08.22
page using TCP sockets.

Applications using TCP sockets like Echo Client and


3 02.09.22
Echo Server

4 09.09.22 Simulation of DNS using UDP sockets.

Simulation of Address Resolution Protocol (ARP) using


5a 16.09.22
TCP

Simulation of Reverse Address Resolution Protocol


5b 23.09.22
(RARP) using UDP

6a 30.09.22 Study of network simulator (NS).

6b 7.10.22 Simulation of Congestion Control Algorithms using NS.

7 14.10.22 Study of TCP/UDP performance using simulation tool

Simulation of Distance Vector/Link State Routing


8 21.10.22
Algorithms

9 28.10.22 Simulation of Error Correction Code (CRC)

Use a tool like Wireshark to capture packets and


10 04.11.22 examine the packets
Ex. No:1 Learn to use commands like tcpdump, netstat, ipconfig, nslookup and
traceroute. Capture ping and traceroute PDUs using a network protocol analyzer and
examine

Aim:

To learn commands like tcpdump, netstat, ipconfig, nslookup, traceroute and ping. Tcpdump

tcpdump offers interesting insights into network behavior. To have a quick look into the network
traffic passing by the network interface of a computer, tcpdump is a good choice. It dumps packets
directly from the network interface and displays it human-friendly in the terminal. In the
ComNetsEmu, there are several examples and situations where GUI-programs cannot be used to
display the traffic between the emulated hosts, so tcpdump can be useful for those scenarios. To be
able to capture all traffic and not only traffic destined for the current computer network interfaces,
the listening interface has to support the so-called monitoring (promiscuous) mode, which has to
be established beforehand. For a first quick look, we can startwithout any parameters. It will
monitor the default interface for connecting to the Internet. Most common used parameters for
capture include:

-#
A packet number is printed on every line.
-c
Exit the dump after the specified number of packets.
-D
Print all available interfaces for capture.
-e
Print also the link-layer header of a packet (e.g., to see the vlan tag).
-i
Interface to dump from (e.g., eth0 or in the example enp0s31f6).
-n
Do not resolve the addresses to names (e.g., IP reverse lookup).
-q
Shorter output (for small terminals).
-v
Be a little bit verbose to see more packet information.
-w
Write the captured traffic to a file.
Netstat

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). Used without parameters,
this command displays active TCP connections.
Syntax

netstat [-a] [-b] [-e] [-n] [-o] [-p <Protocol>] [-r] [-s] [<interval>]

Parameters
Parameter Description
-a Displays all active TCP connections and the TCP and UDP ports on which the
computer is listening.
-b Displays the executable involved in creating each connection or listening port. In some
cases well-known executables host multiple independent components, and in these cases
the sequence of components involved in creating the connection or listening port is
displayed. In this case the executable name is in [] at the bottom, on top is the component
it called, and so forth until TCP/IP was reached. Note that this option can be
timeconsuming and will fail unless you have sufficient permissions.
-e Displays Ethernet statistics, such as the number of bytes and packets sent and received.
This parameter can be combined with -s.
-n Displays active TCP connections, however, addresses and port numbers are expressed
numerically and no attempt is made to determine names.
-o Displays active TCP connections and includes the process ID (PID) for each connection.
You can find the application based on the PID on the Processes tab in Windows Task
Manager. This parameter can be combined with -a, -n, and -p.
-p <Protocol> Shows connections for the protocol specified by Protocol. In this case, the Protocol can
be tcp, udp, tcpv6, or udpv6. If this parameter is used with -s to display statistics by
protocol, Protocol can be tcp, udp, icmp, ip, tcpv6, udpv6, icmpv6, or ipv6.
-s Displays statistics by protocol. By default, statistics are shown for the TCP, UDP, ICMP,
and IP protocols. If the IPv6 protocol is installed, statistics are shown for the TCP over
IPv6, UDP over IPv6, ICMPv6, and IPv6 protocols. The -p parameter can be used to
specify a set of protocols.
-r Displays the contents of the IP routing table. This is equivalent to the route print
command.
<interval> Redisplays the selected information every interval seconds. Press CTRL+C to stop the
redisplay. If this parameter is omitted, this command prints the selected information only
once.
/? Displays help at the command prompt.
Remarks

•The netstat command provides statistics for the following:


Parameter Description
Proto The name of the protocol (TCP or UDP).
Local The IP address of the local computer and the port number being used. The name of the
address local computer that corresponds to the IP address and the name of the port is shown
unless the -n parameter is specified. If the port is not yet established, the port number is
shown as an asterisk (*).
Foreign The IP address and port number of the remote computer to which the socket is connected.
address The names that corresponds to the IP address and the port are shown unless the -n
parameter is specified. If the port is not yet established, the port number is shown as an
asterisk (*).
State Indicates the state of a TCP connection, including:
o
CLOSE_WAIT o
CLOSED o
ESTABLISHED o
FIN_WAIT_1 o
FIN_WAIT_2
Parameter Description
o LAST_ACK o
LISTEN o
SYN_RECEIVED o
SYN_SEND o
TIMED_WAIT

Examples

To display both the Ethernet statistics and the statistics for all protocols, type: netstat

-e -s

To display the statistics for only the TCP and UDP protocols, type: netstat

-s -p tcpudp

To display active TCP connections and the process IDs every 5 seconds, type:

netstat -o 5

To display active TCP connections and the process IDs using numerical form, type:

netstat -n -o
Ipconfig

Displays all current TCP/IP network configuration values and refreshes Dynamic Host
Configuration Protocol (DHCP) and Domain Name System (DNS) settings. Used without
parameters, ipconfig displays Internet Protocol version 4 (IPv4) and IPv6 addresses, subnet mask,
and default gateway for all adapters.

To display the basic TCP/IP configuration for all adapters, type: ipconfig

To display the full TCP/IP configuration for all adapters, type:


ipconfig /all nslookup

The main use of nslookup is for troubleshooting DNS related problems or for security
reasons. Such reasons include guard against phishing attacks, in which a domain name is altered -
for example, by substituting the numeral 1 for a lowercase l -- to make an unfriendly site look
friendly and familiar (joes1owerprices.com vs. joeslowerprices.com).

DNS, or nslookup, also helps deter cache poisoning, in which data is distributed to
caching resolvers, posing as an authoritative origin server.

Nslookup can be use in interactive and non-interactive mode.

Using Nslookup

To illustrate the use of nslookup we are going to use it to:

• Find the IP address of a host.


• Find the domain name of an IP address.
• Find mail servers for a domain.

These are probably the most common usage scenarios.

Finding The IP Address of an Host-

To find the ip address of a host e.g. www.google.com type:

nslookup www.google.com
To use in non-interactive mode type nslookup options at the command prompt.
To use in interactive mode type nslookup at the command line and hit return.

Reverse Lookup IP address to domain name

Type nslookup IP address tracert

The traceroute command attempts to trace the route an IP packet follows to an Internet host by
launching UDP probe packets with a small maximum time-to-live (Max_ttl variable), then listening
for an ICMP TIME_EXCEEDED response from gateways along the way. Probes are started with
a Max_ttl value of one hop, which is increased one hop at a time until anICMP
PORT_UNREACHABLE message is returned.

The ICMP PORT_UNREACHABLE message indicates either that the host has been located or
the command has reached the maximum number of hops allowed for the trace.

The traceroute command sends three probes at each Max_ttl setting to record the following:

• Max_ttl value
• Address of the gateway
• Round-trip time of each successful probe
• Ping
• Usage: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS] [-r count] [-s
count] [[-j hostlist] | [-k host-list]] [-w timeout] [-R] [-S srcaddr] [-c
compartment] [-p] [-4] [-6] target_name
• Options:
• -t Ping the specified host until stopped.
• To see statistics and continue - type Control-Break;
• To stop - type Control-C.
• -a Resolve addresses to hostnames.
• -n count Number of echo requests to send.
• -l size Send buffer size.
• -f Set Don't Fragment flag in packet (IPv4-only).
• -i TTL Time To Live.
• -v TOS Type Of Service (IPv4-only. This setting has been deprecated •
and has no effect on the type of service field in the IP
• Header).
• -r count Record route for count hops (IPv4-only).
• -s count Timestamp for count hops (IPv4-only).
• -j host-list Loose source route along host-list (IPv4-only).
• -k host-list Strict source route along host-list (IPv4-only).
• -w timeout Timeout in milliseconds to wait for each reply.
• -R Use routing header to test reverse route also (IPv6-only).
• Per RFC 5095 the use of this routing header has been
deprecated. Some systems may drop echo requests if this header is used.
-S srcaddr Source address to use.
-c compartment Routing compartment identifier.
-p Ping a Hyper-V Network Virtualization provider address.
-4 Force using IPv4.
-6 Force using IPv6.
Ping is a computer network administration software utility used to test the reachability of a
host on an Internet Protocol (IP) network. It is available for virtually all operating systems that
have networking capability, including most embedded network administration software.
Ping measures the round-trip time for messages sent from the originating host to a
destination computer that are echoed back to the source. The name comes from active sonar
terminology that sends a pulse of sound and listens for the echo to detect objects under water.
Ping operates by means of Internet Control MessageProtocol(ICMP) packets. Pinging
involves sending an ICMP echo request to the target host and waiting for an ICMP echo reply.
The program reports errors, packet loss, and a statistical summary of the results, typically including
the minimum, maximum, the mean round-trip times, and standard deviation of the mean.
The command-line options of the ping utility and its output vary between the numerous
implementations. Options may include the size of the payload, count of tests, limits for the number
of network hops (TTL) that probes traverse, interval between the requests and time to wait for a
response. Many systems provide a companion utility ping6, for testing on Internet Protocol version
6 (IPv6) networks, which implement ICMPv6.

Result:
Thus the commands like tcpdump, netstat, ipconfig, nslookup, tracert and ping was learnt and
used successfully.
Ex. No: 2 Write a HTTP web client program to download a web page using TCP
sockets

Aim:
To write a HTTP web client program to download a web page using TCP sockets.
Algorithm:
1. Start the program.
2. Get the frame size from the user
3. To create the frame based on the user request.
4. To send frames to server from the client side.
5. If your frames reach the server it will send ACK signal to client otherwise it will send
NACK signal to client.
6. Stop the program Program:
import java.io.*; import
java.net.*;
public class SocketHTTPClient
{
public static void main(String[] args)
{
String hostName = "www.martinbroadhurst.com";
int portNumber = 80; try{
Socket socket = new Socket (hostName, portNumber);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in =new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println("GET / HTTP/1.1\nHost: www.martinbroadhurst.com\n\n"); String inputLine;
while((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
} catch(UnknownHostException e) {
System.err.println("Don't know about host "+ hostName);
System.exit(1);
} catch(IOException e) {
System.err.println("Couldn't get I/O for the connection to "+
hostName); System.exit(1);
}
}}
Output :

Result:
Thus the HTTP web client program was executed successfully for downloading a webpage.
Ex. No: 3 Applications using TCP sockets like Echo client and Echo server

Aim:
To write a java program for applications using TCP sockets like Echo client and Echo
server.

Algorithm:

1. Start the program.


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

Program:

EchoServer.Java:
import java.io.*; import
java.net.*;
public class EchoServer
{
public EchoServer(int portnum)
{ try
{
server = new ServerSocket(portnum);
}
catch (Exception err)
{
System.out.println(err);
}
}
public void serve()
{ try {
while
(true) {
Socket client = server.accept();
BufferedReader r = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter w = new PrintWriter(client.getOutputStream(), true);
w.println("Welcome to the Java EchoServer. Type 'bye' to close.");
String line; do {
line = r.readLine(); if
( line != null )
w.println("Got: "+ line); System.out.println
(line);
}
while ( !line.trim().equals("bye") ); client.close();
}
}
catch (Exception err)
{
System.err.println(err);
}
}
public static void main(String[] args)
{
EchoServer s = new EchoServer(9999);
s.serve(); }
private ServerSocket server;
}

EchoClient.java :
import java.io.*; import
java.net.*;
public class EchoClient
{
public static void main(String[] args)
{ try
{
Socket s = new Socket("127.0.0.1", 9999);
BufferedReader r = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter w = new PrintWriter(s.getOutputStream(), true);
BufferedReader con = new BufferedReader(new InputStreamReader(System.in));
String line; do {
line = r.readLine();
if ( line != null )
System.out.println(line);
line = con.readLine();
w.println(line); }
while ( !line.trim().equals("bye") );} catch
(Exception err)
{
System.err.println(err);
}
}
}

Output :

Result:
Thus the java program to concurrently communicate using TCP Sockets was executed
successfully.
Ex.No:4 Simulation of DNS using UDP sockets

Aim:

To write java program Simulation of DNS using UDP Sockets.

Algorithm:

1. Start the program.


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

Program:
#UDP DNS Server
import java.io.*; import
java.net.*;
public class dnsserver
{
private static int indexOf(String[] array, String str)
{
str = str.trim();
for (int i=0; i<array.length; i++)
{
if (array[i].equals(str)) return i;
}
return -1;
}
public static void main(String arg[])throws IOException
{
String[] hosts = {"zoho.com", "gmail.com","google.com", "facebook.com"};

String[] ip= {"172.28.251.59", "172.217.11.5","172.217.11.14", "31.13.71.36"};


System.out.println("Press Ctrl + C to Quit"); while
(true)
{
DatagramSocketserversocket=new DatagramSocket(1362);
byte[] senddata = new byte[1021]; byte[]
receivedata = new byte[1021];
DatagramPacketrecvpack = new DatagramPacket(receivedata, receivedata.length);
serversocket.receive(recvpack);
String sen = new String(recvpack.getData());
InetAddressipaddress = recvpack.getAddress(); int
port = recvpack.getPort();
String capsent;
System.out.println("Request for host " + sen);
if(indexOf (hosts, sen) != -1) capsent =
ip[indexOf (hosts, sen)]; else
capsent = "Host Not Found"; senddata = capsent.getBytes();
DatagramPacket pack = new DatagramPacket (senddata,
senddata.length,ipaddress,port); serversocket.send(pack);
serversocket.close();
}
}
}

//UDP DNS Client –


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

Result: Thus the DNS application program was executed.


Ex. No:5 (i) Simulation of Address Resolution Protocol (ARP) using TCP

Aim:
To write a java program for simulating ARP protocols using TCP
Algorithm: Client
1. Start the program
2. Using socket connection is established between client and server.
3. Get the IP address to be converted into MAC address.
4. Send this IP address to server.
5. Server returns the MAC address to client.
Server

1. Start the program


2. Accept the socket which is created by the client.
3. Server maintains the table in which IP and corresponding MAC addresses are stored.
4. Read the IP address which is send by the client.
5. Map the IP address with its MAC address and return the MAC address to client.
Program:

Client:

import java.io.*;
import java.net.*;
import java.util.*; class
Clientarp
{
public static void main(String args[])
{ try
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
Socket clsct=new Socket("127.0.0.1",5604);
DataInputStream din=new DataInputStream(clsct.getInputStream());
DataOutputStreamdout=newDataOutputStream(clsct.getOutputStream());
System.out.println("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);
clsct.close();
}
catch (Exception e) {
System.out.println(e);
}
}
}
Server:

import java.io.*; import


java.net.*; import
java.util.*;
class Serverarp
{
public static void main(String args[])
{ try
{
ServerSocketobj=new ServerSocket(5604);
Socket obj1=obj.accept(); while(true)
{
DataInputStream din=new DataInputStream(obj1.getInputStream());
DataOutputStreamdout=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<ip.length;i++)
{

if(str.equals(ip[i]))
{
dout.writeBytes(mac[i]+'\n'); break;
} }
obj.close();
}
}
catch(Exception e)
{
System.out.println(e);
}
}}

Result:Thus the ARP protocol using TCP Sockets program was executed successfully.
Ex. No:5(ii) Simulation of Reverse Address Resolution Protocol (RARP) using UDP

Aim:
To write a java program for simulating RARP protocols using UDP.

Algorithm:

Client
1. Start the program
2. Using datagram sockets UDP function is established.
3. Get the MAC address to be converted into IP address.
4. Send this MAC address to server.
5. Server returns the IP address to client.

Server
1. Start the program.
2. Server maintains the table in which IP and corresponding MAC addresses are stored.
3. Read the MAC address which is send by the client.
4. Map the IP address with its MAC address and return the IP address to client.

Program:

Client
import java.io.*;
import java.net.*;
import java.util.*; class
Clientrarp
{
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 Physical address (MAC):");
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("The Logical Address is(IP): "+s.trim()); client.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Server:
import java.io.*;
import java.net.*;
import java.util.*; class
Serverrarp
{
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
mac[]={"6A:08:AA:C2","8A:BC:E3:FA"}; for(int
i=0;i<ip.length;i++)
{
if(s.equals(mac[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);
}
}
}

Result:

Thus the RARP program using UDP was executed.


Ex.No:6(i) Study of network simulator (NS)

Aim:
To study the network simulator (NS).

Introduction:

NS (from network simulator) is a name for series of discrete event network simulators,
specifically ns-1, ns-2 and ns-3. All of them are discrete-event network simulator, primarily used
in research and teaching. ns-3 is free software, publicly available under the GNU GPLv2 license
for research, development, and use.
The goal of the ns-3 project is to create an open simulation environment for networking
research that will be preferred inside the research community
• It should be aligned with the simulation needs of modern networking research.
• It should encourage community contribution, peer review, and validation of the software.

Since the process of creation of a network simulator that contains a sufficient number of High
quality validated, tested and actively maintained models requires a lot of work, ns-3 project spreads
this workload over a large community of users and developers.

ns-1
The first version of ns, known as ns-1, was developed at VJ,GEEKLIME, Madurai (LBNL)
in the 1995-97 timeframe by Steve McCanne, Sally Floyd, Kevin Fall, and other contributors. This
was known as the LBNL Network Simulator, and derived from an earlier simulator known as
REAL by S. Keshav. The core of the simulator was written in C++, with Tcl-based scripting of
simulation scenarios. Long-running contributions have also come from Sun Microsystems, the UC
Berkeley Daedelus, and Carnegie Mellon Monarch projects.it used.
ns-2
In 1996-97, ns version 2 (ns-2) was initiated based on a refactoring by Steve McCanne. Use
of Tcl was replaced by MIT's Object Tcl (OTcl), an object-oriented dialect Tcl. The core of ns-2
is also written in C++, but the C++ simulation objects are linked to shadow objects in OTcl and
variables can be linked between both language realms. Simulation scripts are written in the OTcl
language, an extension of the Tcl scripting language. Presently, ns-2 consists of over 300,000 lines
of source code, and there is probably a comparable amount of contributed code that is not integrated
directly into the main distribution (many forks of ns-2 exist, both maintained and unmaintained).
It runs on GNU/Linux, FreeBSD, Solaris, Mac OS X and Windows versions that support Cygwin.
It is licensed for use under version 2 of the GNU General Public License.
ns-3
A team led by Tom Henderson, George Riley, Sally Floyd, and Sumit Roy, applied for and
received funding from the U.S. National Science Foundation (NSF) to build a replacement for ns2,
called ns-3. This team collaborated with the Planete project of INRIA at Sophia Antipolis, with
Mathieu Lacage as the software lead, and formed a new open source project.In the process of
developing ns-3, it was decided to completely abandon backwardcompatibility with ns-2. The new
simulator would be written from scratch, using the C++ programming language. Development of
ns-3 began in July 2006. A framework for generating Python bindings (pybindgen) and use of the
Waf build system were contributed by Gustavo Carneiro. The first release, ns-3.1 was made in
June 2008, and afterwards the project continued making quarterly software releases, and more
recently has moved to three releases per year. ns-3 made its eighteenth release (ns-3.18) in the third
quarter of 2013.

Current status of the three versions is:


 ns-1 is no longer developed nor maintained,
 ns-2 build of 2009 is not actively maintained (and is not being accepted for journal
publications)
 ns-3 is actively developed (but not compatible for work done on ns-2).

Design

ns-3 is built using C++ and Python with scripting capability. The ns-3 library is wrapped
to python. Thanks to the pybindgen library which delegates the parsing of the ns-3 C++ headers to
gccxml and pygccxml to generate automatically the corresponding C++ binding glue. These
automatically generated C++ files are finally compiled into the ns-3 python module to allow users
to interact with the C++ ns-3 models and core through python scripts. The ns-3 simulator features
an integrated attribute-based system to manage default and per-instance values for simulation
parameters. All of the configurable default values for parameters are managed by this system,
integrated with command-line argument processing, Doxygen documentation, and an XML-based
and optional GTK-based configuration subsystem. x The large majority of its users focuses on
wireless simulations which involve models for Wi-Fi, WiMAX, or LTE for layers 1 and 2 and
routing protocols such as OLSR and AODV.

Components
ns-3 is split over couple dozen modules containing one or more models for real-world
network devices and protocols. ns-3 has more recently integrated with related projects: the Direct
Code Execution extensions allowing the use of C or C++-based applications and Linux kernel code
in the simulations.

Simulation workflow
The general process of creating a simulation can be divided into several steps:
1. Topology definition: to ease the creation of basic facilities and define their
interrelationships, ns-3 has a system of containers and helpers that facilitates this
process.
2. Model development: models are added to simulation (for example, UDP, IPv4,
pointtopoint devices and links, applications); most of the time this is done using helpers.
3. Node and link configuration: models set their default values (for example, the size of
packets sent by an application or MTU of a point-to-point link); most of the time this is
done using the attribute system.
4. Execution: simulation facilities generate events, data requested by the user is logged.
5. Performance analysis: after the simulation is finished and data is available as a time
stamped event trace. This data can then be statistically analysed with tools like R to
draw conclusions.

6. Graphical Visualization: raw or processed data collected in a simulation can be graphed


using tools like Gnuplot, matplotlib or XGRAPH.

Examples of network simulators

There are many both free/open-source and proprietary network simulators.

Examples of notable network simulation software are, ordered after how often they are
mentioned in research papers:
1. ns (open source)
2. OPNET (proprietary software)
3. NetSim (proprietary software)

Uses of network simulators


Network simulators serve a variety of needs. Compared to the cost and time involved in
setting up an entire test bed containing multiple networked computers, routers and data links,
network simulators are relatively fast and inexpensive. They allow engineers, researchers to test
scenarios that might be particularly difficult or expensive to emulate using real hardware – for
instance, simulating a scenario with several nodes or experimenting with a new protocol in the
network.
Network simulators are particularly useful in allowing researchers to test new networking
protocols or changes to existing protocols in a controlled and reproducible environment. A typical
network simulator encompasses a wide range of networking technologies and can help the users to
build complex networks from basic building blocks such as a variety of nodes and links.
With the help of simulators, one can design hierarchical networks using various types of
nodes like computers, hubs, bridges, routers, switches, links, mobile units etc. Various types of
Wide Area Network (WAN) technologies like TCP, ATM, IP etc. and Local Area Network (LAN)
technologies like Ethernet, token rings etc., can all be simulated with a typical simulator and the
user can test, analyze various standard results apart from devising some novel protocol or strategy
for routing etc. Network simulators are also widely used to simulate battlefield networks in
Network-centric warfare

Packet loss:
When one or more packets of data travelling across a computer network fail to reach their
destination. Packet loss is distinguished as one of the three main error types encountered in digital
communications; the other two being bit error and spurious packets caused due to noise. Packets
can be lost in a network because they may be dropped when a queue in the network node overflows.
The amount of packet loss during the steady state is another important property of a congestion
control scheme. The larger the value of packet loss, the more difficult it is for transport layer
protocols to maintain high bandwidths, the sensitivity to loss of individual packets, as well as to
frequency and patterns of loss among longer packet sequences is strongly dependent on the
application itself.

Throughput:

This is the main performance measure characteristic, and most widely used. In
communication networks, such as Ethernet or packet radio, throughput or network throughput is
the average rate of successful message delivery over a communication channel. The throughput is
usually measured in bits per second (bit/s or bps), and sometimes in data packets per second or
data packets per time slot This measure how soon the receiver is able to get a certain amount of
data send by the sender. It is determined as the ratio of the total data received to the end to end
delay. Throughput is an important factor which directly impacts the network performance.

Delay:

Delay is the time elapsed while a packet travels from one point e.g., source premise or
network ingress to destination premise or network degrees. The larger the value of delay, the more
difficult it is for transport layer protocols to maintain high bandwidths. We will calculate end to
end delay

Queue Length:

A queuing system in networks can be described as packets arriving for service, waiting for
service if it is not immediate, and if having waited for service, leaving the system after being
served. Thus queue length is very important characteristic to determine that how well the active
queue management of the congestion control algorithm has been working.

Result:
Thus the study of Network simulator (NS2) was studied.
Ex.No:6(ii) Simulation of Congestion Control Algorithms using NS

Aim: To Simulate Congestion Control protocols.

Stop and Wait Protocol:

Theory:
Stop and Wait is a reliable transmission flow control protocol. This protocol works only in
Connection Oriented (Point to Point) Transmission. The Source node has window size of ONE.
After transmission of a frame the transmitting (Source) node waits for an Acknowledgement from
the destination node. If the transmitted frame reaches the destination without error, the destination
transmits a positive acknowledgement. If the transmitted frame reaches the Destination with error,
the receiver destination does not transmit an acknowledgement. If the transmitter receives a
positive acknowledgement it transmits the next frame if any. Else if its acknowledgement receive
timer expires, it retransmits the same frame.
1. Start with the window size of 1 from the transmitting (Source) node
2. After transmission of a frame the transmitting (Source) node waits for a reply
(Acknowledgement) from the receiving (Destination) node.
3. If the transmitted frame reaches the receiver (Destination) without error, the receiver
(Destination) transmits 4. Positive Acknowledgement.
5. If the transmitted frame reaches the receiver (Destination) with error, the receiver
(Destination) do not transmit acknowledgement.
6. If the transmitter receives a positive acknowledgement it transmits the next frame if
any. Else if the transmission timer expires, it retransmits the same frame again.
7. If the transmitted acknowledgment reaches the Transmitter (Destination) without error,
the Transmitter (Destination) transmits the next frame if any.
8. If the transmitted frame reaches the Transmitter (Destination) with error, the
Transmitter (Destination) transmits the same frame.
9. This concept of the Transmitting (Source) node waiting after transmission for a reply
from the receiver is known as STOP and WAIT.

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 two nodes that forms a network numbered 0 and 1
5. Create duplex links between the nodes to form a STAR Topology
6. Setup TCP Connection between n(1) and n(3)
7. Apply CBR Traffic over TCP
8. Schedule events and run the program.

PROGRAM: (Stop and Wait Protocol)

set ns [new Simulator]


$ns color 1 Blue
# set nam output file
set nf [open out.nam w]
$ns namtrace-all $nf

# destructor
proc finish {} {
global ns nf
$ns flush-trace
close $nf
exec nam out.nam &
exit 0
}

# create two new nodes and create labels for them


set n0 [$ns node]
set n1 [$ns node]
$ns at 0.0 "$n0 label \" Sender \" "
$ns at 0.0 "$n1 label \"Receiver\" "

# set up a new duplex link


$ns duplex-link $n0 $n1 1Mb 200ms DropTail
$ns duplex-link-op $n0 $n1 orient right

# create a new TCP agent


set tcp [new Agent/TCP]
# attach the agent to first node
$ns attach-agent $n0 $tcp
$tcp set fid_ 1
$tcp set window_ 1
$tcp set maxcwnd_ 1
$ns add-agent-trace $tcp tcp
$ns monitor-agent-trace $tcp
set tcpsink [new Agent/TCPSink]
$ns attach-agent $n1 $tcpsink

$ns connect $tcp $tcpsink


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

$ns at 0.5 "$ftp start"


$ns at 3.0 "$ns detach-agent $n0 $tcp ; $ns detach-agent $n1 $tcpsink "
$ns at 1.0 "$ns trace-annotate \"send packet 1\""
$ns at 1.4 "$ns trace-annotate \"recieve ack 1\""
$ns at 2.0 "$ns trace-annotate \"send packet 2\""
$ns at 2.5 "$ns trace-annotate \"receive ack 2\""
$ns at 3.2 "$ns trace-annotate \"send packet 3\""
$ns at 3.5 "$ns trace-annotate \"receive ack 3\""
$ns at 3.8 "$ns trace-annotate \"send packet 4\""
$ns at 4.0 "finish"
$ns run
Output:

Sliding Window Protocol:

Theory:
A sliding window protocol is a feature of packet-based data transmission protocols. Sliding
window protocols are used where reliable in-order delivery of packets is required, such as in the
Data Link Layer (OSI model) as well as in the Transmission Control Protocol (TCP).
Conceptually, each portion of the transmission (packets in most data link layers, but bytes
in TCP) is assigned a unique consecutive sequence number, and the receiver uses the numbers to
place received packets in the correct order, discarding duplicate packets and identifying missing
ones. The problem with this is that there is no limit on the size of the sequence number that can be
required.
By placing limits on the number of packets that can be transmitted or received at any given
time, a sliding window protocol allows an unlimited number of packets to be communicated using
fixed-size sequence numbers. The term "window" on the transmitter side represents the logical
boundary of the total number of packets yet to be acknowledged by the receiver. The receiver
informs the transmitter in each acknowledgment packet the current maximum receiver buffer size
(window boundary).
The TCP header uses a 16 bit field to report the receive window size to the sender.
Therefore, the largest window that can be used is 216 = 64 kilobytes. In slow-start mode, the
transmitter starts with low packet count and increases the number of packets in each transmission
after receiving acknowledgment packets from receiver. For every ack packet received, the window
slides by one packet (logically) to transmit one new packet. When the window threshold is reached,
the transmitter sends one packet for one ack packet received.
If the window limit is 10 packets then in slow start mode the transmitter may start
transmitting one packet followed by two packets (before transmitting two packets, one packet ack
has to be received), followed by three packets and so on until 10 packets. But after reaching 10
packets, further transmissions are restricted to one packet transmitted for one ack packet received.
In a simulation this appears as if the window is moving by one packet distance for every
ack packet received. On the receiver side also the window moves one packet for every packet
received. The sliding window method ensures that traffic congestion on the network is avoided.
The application layer will still be offering data for transmission to TCP without worrying about
the network traffic congestion issues as the TCP on sender and receiver side implement sliding
windows of packet buffer. The window size may vary dynamically depending on network traffic.
For the highest possible throughput, it is important that the transmitter is not forced to stop
sending by the sliding window protocol earlier than one round-trip delay time (RTT). The limit on
the amount of data that it can send before stopping to wait for an acknowledgment should be larger
than the bandwidth-delay product of the communications link. If it is not, the protocol will limit
the effective bandwidth of the link.

Program: (Sliding Window Protocol)

# Create a simulator instance


set ns [new Simulator]

# Create nodes
set n0 [$ns node]
set n1 [$ns node]

# Label nodes
$ns at 0.0 "$n0 label Sender"
$ns at 0.0 "$n1 label Receiver"

# Enable tracing
set tracefile [open sliding.tr w]
set namfile [open sliding.nam w]
$ns trace-all $tracefile
$ns namtrace-all $namfile

# Configure duplex link


$ns duplex-link $n0 $n1 0.2Mb 200ms DropTail
$ns duplex-link-op $n0 $n1 orient right
$ns queue-limit $n0 $n1 10

# Configure TCP agent


Agent/TCP set nam_tracevar_ true
set tcp [new Agent/TCP]
$tcp set windowInit_ 4
$tcp set maxcwnd_ 4
$ns attach-agent $n0 $tcp

# Configure TCP Sink agent


set sink [new Agent/TCPSink]
$ns attach-agent $n1 $sink
$ns connect $tcp $sink

# Attach FTP application to TCP agent


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

# Enable agent monitoring


$ns add-agent-trace $tcp tcp
$ns monitor-agent-trace $tcp
$tcp tracevar cwnd_
# Schedule events
$ns at 0.1 "$ftp start"
$ns at 3.0 "$ns detach-agent $n0 $tcp ; $ns detach-agent $n1 $sink"
$ns at 3.5 "finish"

# Add annotations
$ns at 0.0 "$ns trace-annotate \"Sliding Window with window size 4 (normal operation)\""
$ns at 0.05 "$ns trace-annotate \"FTP starts at 0.1\""
$ns at 0.11 "$ns trace-annotate \"Send Packet_0,1,2,3\""
$ns at 0.34 "$ns trace-annotate \"Receive Ack_0,1,2,3\""
$ns at 0.56 "$ns trace-annotate \"Send Packet_4,5,6,7\""
$ns at 0.79 "$ns trace-annotate \"Receive Ack_4,5,6,7\""
$ns at 0.99 "$ns trace-annotate \"Send Packet_8,9,10,11\""
$ns at 1.23 "$ns trace-annotate \"Receive Ack_8,9,10,11\""
$ns at 1.43 "$ns trace-annotate \"Send Packet_12,13,14,15\""
$ns at 1.67 "$ns trace-annotate \"Receive Ack_12,13,14,15\""
$ns at 1.88 "$ns trace-annotate \"Send Packet_16,17,18,19\""
$ns at 2.11 "$ns trace-annotate \"Receive Ack_16,17,18,19\""
$ns at 2.32 "$ns trace-annotate \"Send Packet_20,21,22,23\""
$ns at 2.56 "$ns trace-annotate \"Receive Ack_24,25,26,27\""
$ns at 2.76 "$ns trace-annotate \"Send Packet_28,29,30,31\""
$ns at 3.00 "$ns trace-annotate \"Receive Ack_28\""
$ns at 3.1 "$ns trace-annotate \"FTP stops\""

# Define finish procedure


proc finish {} {
global ns tracefile namfile
$ns flush-trace
close $tracefile
close $namfile
puts "Running NAM..."
exec nam sliding.nam &
puts "Simulation completed."
exit 0
}

# Run the simulation


$ns run

Result:Thus the Congestion Control Algorithms were simulated successfully.


Ex.No:7 Study of TCP/UDP performance using Simulation tool

Aim:
To simulate the performance of TCP/UDP using NS2.

TCP Performance

Algorithm:

1. Create a Simulator object.


2. Set routing as dynamic.
3. Open the trace and namtrace files.
4. Define the finish procedure.
5. Create nodes and the links between them.
6. Create the agents and attach them to the nodes.
7. Create the applications and attach them to the tcp agent.
8. Connect tcp and tcp sink.
9. Run the simulation.

Program:

# Create a simulator instance


set ns [new Simulator]

# Enable tracing
set tracefile [open tcpout.tr w]
set namfile [open tcpout.nam w]
$ns trace-all $tracefile
$ns namtrace-all $namfile

# Create network nodes


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

# Create duplex links


$ns duplex-link $n0 $n2 5Mb 2ms DropTail
$ns duplex-link $n1 $n2 5Mb 2ms DropTail
$ns duplex-link $n2 $n3 31.5Mb 10ms DropTail

# Set link orientations for NAM


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

# Create TCP agent and attach to node n1


set tcp [new Agent/TCP]
$tcp set class_ 1
$ns attach-agent $n1 $tcp

# Create TCP Sink agent and attach to node n3


set sink [new Agent/TCPSink]
$ns attach-agent $n3 $sink

# Connect TCP agent to sink


$ns connect $tcp $sink

# Create FTP application and attach to TCP agent


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

# Schedule events
$ns at 1.2 "$ftp start"
$ns at 1.35 "$ns detach-agent $n1 $tcp; $ns detach-agent $n3 $sink"
$ns at 3.0 "finish"

# Define finish procedure


proc finish {} {
global ns tracefile namfile
$ns flush-trace
close $tracefile
close $namfile
puts "Running NAM..."
exec nam tcpout.nam &
puts "Simulation completed."
exit 0
}

# Run the simulation


$ns run
Output:

UDP Performance

Algorithm:

1. Create a Simulator object.


2. Set routing as dynamic.
3. Open the trace and namtrace files.
4. Define the finish procedure.
5. Create nodes and the links between them.
6. Create the agents and attach them to the nodes.
7. Create the applications and attach them to the UDP agent.
8. Connect udp and null agents.
9. Run the simulation.
Program:
# Create a simulator instance
set ns [new Simulator]

# Create trace and NAM files


set tracefile [open udpout.tr w]
set namfile [open udpout.nam w]
$ns trace-all $tracefile
$ns namtrace-all $namfile

# Define colors for NAM visualization


$ns color 0 Blue
$ns color 1 Red
$ns color 2 Yellow

# Create nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]

# Create duplex links


$ns duplex-link $n0 $n2 5Mb 2ms DropTail
$ns duplex-link $n1 $n2 5Mb 2ms DropTail
$ns duplex-link $n2 $n3 31.5Mb 10ms DropTail

# Set link orientations for NAM


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

# Configure UDP agents


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

set udp1 [new Agent/UDP]


$ns attach-agent $n3 $udp1

# Configure Null agents


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

set null1 [new Agent/Null]


$ns attach-agent $n1 $null1

# Connect UDP agents to Null agents


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

# Configure CBR applications


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

set cbr1 [new Application/Traffic/CBR]


$cbr1 attach-agent $udp1
$cbr1 set packetSize_ 512
$cbr1 set interval_ 0.1

# Schedule events
$ns at 1.0 "$cbr0 start"
$ns at 1.1 "$cbr1 start"
$ns at 3.0 "finish"

# Finish procedure
proc finish {} {
global ns tracefile namfile
$ns flush-trace
close $tracefile
close $namfile
puts "Running NAM..."
exec nam udpout.nam &
puts "Simulation completed."
exit 0
}

# Run the simulation


$ns run
Output:

Result:Thus the study of TCP/UDP performance is done successfully.


Ex.No:8 Simulation of Distance Vector / Link State Routing algorithm Aim:

To simulate the Distance vector and link state routing protocols using NS2.

Algorithm:

1. Create a Simulator object.


2. Set routing as dynamic.
3. Open the trace and namtrace files.
4. Define the finish procedure.
5. Create nodes and the links between them.
6. Create the agents and attach them to the nodes.
7. Create the applications and attach them to the udpagent.
8. Connect udp and null..
9. At 1sec the link between node1 and 2 is broken.
10. At 2sec the link is up again.
11. Run the simulation.

Link state routing algorithm

Program:

# Create a new simulator instance

set ns [new Simulator]

# Enable link-state routing protocol

$ns rtproto LS

# Create trace and NAM files

set tracefile [open linkstate.tr w]

set namfile [open linkstate.nam w]

$ns trace-all $tracefile

$ns namtrace-all $namfile


# Define finish procedure

proc finish {} {

global ns tracefile namfile

$ns flush-trace

close $tracefile

close $namfile

puts "Running NAM..."

exec nam linkstate.nam &

puts "Simulation completed."

exit 0

# Create nodes

for {set i 0} {$i < 7} {incr i} {

set n($i) [$ns node]

# Create circular duplex links

for {set i 0} {$i < 7} {incr i} {

$ns duplex-link $n($i) $n([expr ($i + 1) % 7]) 1Mb 10ms DropTail

# Configure UDP agent and CBR application

set udp0 [new Agent/UDP]

$ns attach-agent $n(0) $udp0


set cbr0 [new Application/Traffic/CBR]

$cbr0 set packetSize_ 500

$cbr0 set interval_ 0.005

$cbr0 attach-agent $udp0

# Configure Null agent

set null0 [new Agent/Null]

$ns attach-agent $n(3) $null0

# Connect UDP agent to Null agent

$ns connect $udp0 $null0

# Schedule events

$ns at 0.5 "$cbr0 start"

$ns rtmodel-at 1.0 down $n(1) $n(2) ;# Link between n(1) and n(2) goes down

$ns rtmodel-at 2.0 up $n(1) $n(2) ;# Link between n(1) and n(2) comes back up

$ns at 4.5 "$cbr0 stop"

$ns at 5.0 "finish"

# Run the simulation

$ns run
Output:
Distance Vector Routing Algorithm

Algorithm:

1. Create a simulator object


2. Set routing protocol to Distance Vector routing
3. Trace packets on all links on to NAM trace and text trace file
4. Define finish procedure to close files, flush tracing and run NAM
5. Create eight nodes
6. Specify the link characteristics between nodes
7. Describe their layout topology as a octagon
8. Add UDP agent for node n1
9. Create CBR traffic on top of UDP and set traffic parameters.
10. Add a sink agent to node n4
11. Connect source and the sink
12. Schedule events as follows:
1. Start traffic flow at 0.5
2. Down the link n3-n4 at 1.0
3. Up the link n3-n4 at 2.0
4. Stop traffic at 3.0
5. Call finish procedure at 5.0
13. Start the scheduler
14. Observe the traffic route when link is up and down
15. View the simulated events and trace file analyze it
16. Stop

Program:

# Create a simulator object


set ns [new Simulator]

# Use distance vector routing


$ns rtproto DV

# Open NAM trace file


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

# Open trace file


set tracefile [open trace.tr w]
$ns trace-all $tracefile

# Define 'finish' procedure


proc finish {} {
global ns tracefile namfile
$ns flush-trace
close $namfile
close $tracefile
puts "Running NAM..."
exec nam -a out.nam &
puts "Simulation completed."
exit 0
}

# Create 8 nodes
for {set i 1} {$i <= 8} {incr i} {
set n($i) [$ns node]
}

# Specify link characteristics


$ns duplex-link $n(1) $n(2) 1Mb 10ms DropTail
$ns duplex-link $n(2) $n(3) 1Mb 10ms DropTail
$ns duplex-link $n(3) $n(4) 1Mb 10ms DropTail
$ns duplex-link $n(4) $n(5) 1Mb 10ms DropTail
$ns duplex-link $n(5) $n(6) 1Mb 10ms DropTail
$ns duplex-link $n(6) $n(7) 1Mb 10ms DropTail
$ns duplex-link $n(7) $n(8) 1Mb 10ms DropTail
$ns duplex-link $n(8) $n(1) 1Mb 10ms DropTail

# Specify layout as an octagon


$ns duplex-link-op $n(1) $n(2) orient left-up
$ns duplex-link-op $n(2) $n(3) orient up
$ns duplex-link-op $n(3) $n(4) orient right-up
$ns duplex-link-op $n(4) $n(5) orient right
$ns duplex-link-op $n(5) $n(6) orient right-down
$ns duplex-link-op $n(6) $n(7) orient down
$ns duplex-link-op $n(7) $n(8) orient left-down
$ns duplex-link-op $n(8) $n(1) orient left

# Create a UDP agent and attach it to node n(1)


set udp0 [new Agent/UDP]
$ns attach-agent $n(1) $udp0
# Create a CBR traffic source and attach it to udp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0

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


set null0 [new Agent/Null]
$ns attach-agent $n(4) $null0

# Connect the traffic source with the traffic sink


$ns connect $udp0 $null0

# Schedule events for the CBR agent and network dynamics


$ns at 0.0 "$n(1) label Source"
$ns at 0.0 "$n(4) label Destination"
$ns at 0.5 "$cbr0 start"
$ns rtmodel-at 1.0 down $n(3) $n(4) ;# Link between n(3) and n(4) goes down
$ns rtmodel-at 2.0 up $n(3) $n(4) ;# Link between n(3) and n(4) comes back up
$ns at 4.5 "$cbr0 stop"

# Call the finish procedure after 5 seconds of simulation time


$ns at 5.0 "finish"

# Run the simulation


$ns run
Output:
$ nsdistvect.tcl
Result:
Thus the simulation for Distance vector and link state routing protocols was done using
NS2.
Ex.No:9 Simulation of Error Correction Code (CRC)

Aim:

To implement the error correction code using CRC.

Algorithm:

1. Import the necessary packages.

2. Open the editor and type the program for error detection

3. Get the input in the form of bits.

4. Append the redundancy bits.

5. Divide the appended data using a divisor polynomial.

6. The resulting data should be transmitted to the receiver.

7. At the receiver the received data is entered.

8. The same process is repeated at the receiver.

9. If the remainder is zero there is no error otherwise there is some error in the received bits.

10. Run the program

Cyclic redundancy check (CRC)

Unlike checksum scheme, which is based on addition, CRC is based on binary division.

n CRC, a sequence of redundant bits, called cyclic redundancy check bits, are appended
to the end of data unit so that the resulting data unit becomes exactly divisible by a
second, predetermined binary number.

At the destination, the incoming data unit is divided by the same number. If at this step
there is no remainder, the data unit is assumed to be correct and is therefore accepted.

A remainder indicates that the data unit has been damaged in transit and therefore must be
rejected.
Program:

import java.io.*;

class CRC

{ public static void main(String args[]) throws IOException

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter Generator:");

String gen = br.readLine();

System.out.println("Enter Data:");

String data = br.readLine(); String code = data;

while(code.length() < (data.length() + gen.length() -

1)) code = code + "0"; code = data +

div(code,gen);

System.out.println("The transmitted Code Word is: " + code);

System.out.println("Please enter the received Code

Word: "); String rec = br.readLine();

if(Integer.parseInt(div(rec,gen)) == 0)

System.out.println("The received code word contains no errors.");

else
System.out.println("The received code word contains errors.");

} static String div(String num1,String

num2)

{ int pointer = num2.length();


String result = num1.substring(0,

pointer); String remainder = "";

for(int i = 0; i < num2.length(); i++) {

if(result.charAt(i) == num2.charAt(i))

remainder += "0";

else
remainder +=
"1"

} while(pointer <

num1.length())

if(remainder.charAt(0) == '0')

{ remainder = remainder.substring(1, remainder.length());

remainder = remainder +

String.valueOf(num1.charAt(pointer)); pointer++;

} result = remainder; remainder =

""; for(int i = 0; i < num2.length();

i++) { if(result.charAt(i) ==

num2.charAt(i)) remainder += "0";

else remainder += "1";

}
} return remainder.substring(1,remainder.length());

}
Output:

Result:

Thus the java program for implementing CRC was executed successfully.
Ex. No:10 Use a tool like Wireshark to capture packets and examine the packets

Aim:

To Use a tool like Wireshark to capture packets and examine the packets

Procedure:
• After downloading and installing wireshark, you can launch it and click the name of an
interface under Interface List to start capturing packets on that interface.
• After downloading and installing wireshark, you can launch it and click the name of an
interface under Interface List to start capturing packets on that interface.
• For example, if you want to capture traffic on the wireless network, click your wireless
interface. You can configure advanced features by clicking Capture Options.

• As soon as you click the interface‘s name, you‘ll see the packets start to appear in real
time. Wireshark captures each packet sent to or from your system.
• If you‘re capturing on a wireless interface and have promiscuous mode enabled in your
capture options, you‘ll also see other the other packets on the network.
• Click the stop capture button near the top left corner of the window when you want to
stop capturing traffic.
• Wireshark uses colors to help you identify the types of traffic at a glance.
By default, green is TCP traffic, dark blue is DNS traffic, light blue is UDP traffic, and black
identifies TCP packets with problems — for example, they could have been deliveredout-of-
order
By typing the ip address of client in filter box at top of the window in server’s system
and ip address of server in client system we can monitor the client server communication

Result: Thus the capture packets and examine the packets was done using a tool like Wireshark.

You might also like