0% found this document useful (0 votes)
9 views62 pages

CCS Record Printout

The document outlines various networking programs and commands, including socket programming for HTTP clients, echo servers, chat applications, and file transfers. It also covers the use of network analysis tools like Wireshark and simulations of protocols such as DNS and ARP. Additionally, it provides Java code examples for implementing these networking concepts.

Uploaded by

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

CCS Record Printout

The document outlines various networking programs and commands, including socket programming for HTTP clients, echo servers, chat applications, and file transfers. It also covers the use of network analysis tools like Wireshark and simulations of protocols such as DNS and ARP. Additionally, it provides Java code examples for implementing these networking concepts.

Uploaded by

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

TABLE OF CONTENTS

S.NO. DATE PROGRAM TITLE SIGN.

1. Networking Commands

HTTP web client program to download


2. a web page using TCP sockets

3a. Socket program For Echo Client and


Echo Server

3b. Client- Server application for Chat

3c File transfer

4. Simulation of DNS using UDP sockets.

5 Use of Wireshark tool to capture and


examine packets

6a. Simulation of ARP protocol

6b. Simulation of RARP protocol

Study of Network simulator and


7 Simulation of Congestion Control
Algorithms using NS.

8 Study of TCP/UDP performance using


Simulation tool.

9a. Simulation of Distance Vector Routing


algorithm.

9b. Simulation of Link State Routing


algorithm.

10. Simulation of error correction code (like


CRC).
NETWORKING COMMANDS:

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 specific interface for analysis.

netstat
Displays active TCP connections, ports on which the computer is listening, Ethernet
statistics, IP routing table, IPv4 statistics and IPv6 statistics. It indicates state of a TCP connection.
it's a helpful tool in finding problems and determining the amount of traffic on the network as a
performance measurement.
ifconfig / ifconfig
Displays basic current TCP/IP network configuration. It is very useful to troubleshoot
networking problems. ipconfig/all is used to provide detailed information such as IP address,
subnet mask, MAC address, DNS server, DHCP server, default gateway etc. ipconfig/renew is
used to renew a DHCP assigned IP address whereas ipconfig/release is used to discard the
assigned DHCP IP address.

nslookup
It provides a command-line utility for querying DNS table of a DNS Server. It returns IP
address for the given host name.

traceroute / tracert
Displays the path taken to a destination by sending ICMP Echo Request messages to the
destination with TTL field values. The path displayed is the list of nearest router interfaces taken
along each hop in the path between source host and destination.

ping
Verifies IP-level connectivity to another TCP/IP computer by sending Internet Control
Message Protocol (ICMP) Echo Request messages. The receipt of corresponding Echo Reply
messages are displayed, along with round-trip times. Ping is the primary TCP/IP command used to
troubleshoot connectivity, reachability, and name resolution.
PROGRAM:

import java.io.*;
import java.net.*;

public class SocketHTTPClient


{ public static void main(String[] args)
{
try {
// Create a socket to connect to the website
Socket socket = new Socket("www.martinbroadhurst.com", 80);

// Get the output stream to send request


PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

// Send an HTTP GET request


out.println("GET /
HTTP/1.1");
out.println("Host:
www.martinbroadhurst.com"); out.println(""); //
End of the HTTP request

// Get the input stream to read the server's response


BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));

// Read and print the server's response


String responseLine;
while ((responseLine = in.readLine()) != null) {
System.out.println(responseLine);
}

// Close the streams and socket


in.close();
out.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
OUTPUT:
PROGRAM:

EchoServer

import java.io.*;
import java.net.*;
import java.util.*;
public class
ChatServer
{
public static void main(String args[])
{
try
{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new
DataOutputStream(s.getOutputStream());
Scanner input=new Scanner(System.in);
String senddata="";
String recievedata=""; while(!
recievedata.equals("stop"))
{
recievedata=din.readUTF();System.out.println("CLIENT SAYS :"+recievedata);
System.out.print("TO CLIENT :");
senddata=input.nextLine();
dout.writeUTF(senddata);
}
din.close();
dout.close();
s.close();
ss.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}

EchoClient

import java.io.*;
import java.net.*;
import java.util.*;
public class
ChatClient
{
public static void main(String args[])
{
try
{
Socket s=new Socket("localhost",6666);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new
DataOutputStream(s.getOutputStream());
Scanner input=new Scanner(System.in);
String senddata="";
String recievedata=""; while(!
senddata.equals("stop"))
{
System.out.print("TO SERVER :");
senddata=input.nextLine();
dout.writeUTF(senddata);recievedata=din.readUTF();
System.out.println("SERVER SAYS :"+recievedata);
}
din.close();
dout.close();
s.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
OUTPUT:
PROGRAM:

ChatClient.java:

import java.io.*;
import java.net.*;
import java.util.*;
public class
ChatClient
{
public static void main(String args[])
{
try
{
Socket s=new Socket("localhost",6666);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new
DataOutputStream(s.getOutputStream());
Scanner input=new Scanner(System.in);
String senddata="";
String recievedata=""; while(!
senddata.equals("stop"))
{
System.out.print("TO SERVER :");
senddata=input.nextLine();
dout.writeUTF(senddata);recievedata=din.readUTF();
System.out.println("SERVER SAYS :"+recievedata);
}
din.close();
dout.close();
s.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}

ChatServer.java:

import java.io.*;
import java.net.*;
import java.util.*;
public class
ChatServer
{
public static void main(String args[])
{
try
{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new
DataOutputStream(s.getOutputStream());
Scanner input=new Scanner(System.in);
String senddata="";
String recievedata=""; while(!
recievedata.equals("stop"))
{
recievedata=din.readUTF();System.out.println("CLIENT SAYS :"+recievedata);
System.out.print("TO CLIENT :");
senddata=input.nextLine();
dout.writeUTF(senddata);
}
din.close();
dout.close();
s.close();
ss.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
OUTPUT:
PROGRAM:

FTPServer.java

import java.io.*;
import java.net.*;
public class
FTPServer
{
public static void main(String args[]) throws Exception
{
ServerSocket ss=new ServerSocket(1024);
System.out.println("ServerSocket Generated");
Socket s=ss.accept();
System.out.println("ServerSocket Accepted");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
PrintStream p=new PrintStream(s.getOutputStream());
String fname,str;
System.out.println("Enter a File Name:");
fname=br.readLine();
File f1=new File(fname);
if(f1.exists())
{BufferedReader br1=new BufferedReader(new
FileReader(fname)); while((str=br1.readLine())!
=null)
p.println(str);
}
p.close();
}
}

FTPClient.java

import java.io.*;
import java.net.*;
public class FTPClient
{
public static void main(String asd[]) throws Exception
{
InetAddress ia=InetAddress.getLocalHost();
Socket s=new Socket(ia,1024);
String fname,str;
System.out.println("Enter a new File Name:");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
fname=br.readLine();
File f1=new File(fname);
PrintWriter p=new PrintWriter(new FileWriter(fname));
BufferedReader br1=new BufferedReader(new
InputStreamReader(s.getInputStream()));
while((str=br1.readLine())!=null)
p.println(str);
p.close();
s.close();
}
}

OUTPUT:
PROGRAM:

Server.java

import java.io.*;
import java.net.*;
import java.util.*;
class Server
{
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"};
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);
}
}
}

Client.java

import java.io.*;
import java.net.*;
import java.util.*;
class Client{
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 SERVER/DOMAIN NAME:");
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 is: "+s.trim());
client.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
OUTPUT:
EX.NO. 5. WIRESHARK TOOL TO CAPTURE AND EXAMINE PACKETS

AIM:

To capture ping and traceroute PDUs using a network protocol analyzer and examine in
detail.

WIRESHARK TOOL

When Wireshark is launched, the screen below is displayed.

To start data capture it is first necessary to go to the Capture menu and select the Options choice.
The Options dialog provides a range of settings and filters which determines which and how
much data traffic is captured.
First, it is necessary to ensure that Wireshark is set to monitor the correct interface. From the
Interface drop-down list, select the network adapter in use. Typically, for a computer this will be
the connected Ethernet Adapter. Then other Options can be set. Among those available in
Capture Options, the two highlighted below are worth examination.

Clicking on the Start button starts the data capture process and a message box displays the
progress of this process.

As data PDUs are captured, the types and number are indicated in the message box
The examples above show the capture of a ping process and then accessing a web page. When the
Stop button is clicked, the capture process is terminated and the main screen is displayed.
This main display window of Wireshark has three panes.

The PDU (or Packet) List Pane at the top of the diagram displays a summary of each packet
captured. By clicking on packets in this pane, you control what is displayed in the other two
panes. The PDU (or Packet) Details Pane in the middle of the diagram displays the packet selected
in the Packet List Pane in more detail.
The PDU (or Packet) Bytes Pane at the bottom of the diagram displays the actual data (in
hexadecimal form representing the actual binary) from the packet selected in the Packet List Pane,
and highlights the field selected in the Packet Details Pane.
Task 1: Ping PDU Capture

Step 1: After ensuring that the standard lab topology and configuration is correct, launch
Wireshark on a computer in a lab pod. Set the Capture Options as described above in the overview
and start the capture process. From the command line of the computer, ping the IP address of
another network connected and powered on end device on in the lab topology. In this case, ping
the Eagle Server at using the command ping 192.168.254.254. After receiving the successful
replies to the ping in the command line window, stop the packet capture.
Step 2: Examine the Packet List pane.
The Packet List pane on Wireshark should now look something like this:

Look at the packets listed above; we are interested in packet numbers 6, 7, 8, 9, 11, 12, 14 and 15.
Locate the equivalent packets on the packet list on your computer.
Step 3: Select (highlight) the first echo request packet on the list with the mouse. The Packet
Detail pane will now display something similar to: Click on each of the four "+" to expand the
information. The packet Detail Pane will now be similar to:
Task 2: Traceroute PDU Capture
Traceroute generates a list of each hop by entering IP of routers that traversed between source and
destination and average round-trip time. As a result hop 22 denotes entry of destination i.e.
Google DNS. In order to notice the activity of traceroute, Wireshark runs in the background.

At Wireshark the following points are notices:


▪ ICMP echo request packet is used instead of UDP to send DNS query.
▪ The packet first goes from source 192.168.1.101 to first router 192.168.1.1 having ICMP echo
request packet with TTL=1
▪ The router will drop that packet and send ICMP Time Exceeded error message to the source.
▪ All this happens 3 times before the source machine sends next packet by incrementing TTL value
by 1 i.e. TTL=2.

From this image we can observe ICMP echo reply message is sent from 8.8.8.8 (destination) to
192.168.1.101 (source) for TTL 22.
PROGRAM:

Server.java

import java.io.*;
import java.net.*;
import java.util.*;

class Server {
public static void main(String args[])
{ try {
ServerSocket obj = new ServerSocket(3636);
Socket obj1 = obj.accept();

BufferedReader din = new BufferedReader(new


InputStreamReader(obj1.getInputStream()));
DataOutputStream dout = new DataOutputStream(obj1.getOutputStream());

String[] ip = {"165.165.80.80", "165.165.79.1"};


String[] mac = {"6A:08:AA:C2", "8A:BC:E3:FA"};

while (true) {
String str = din.readLine();
if (str == null) {
break; // Exit the loop if the input is null (e.g., client disconnects)
}

boolean found = false;


for (int i = 0; i < ip.length; i++) {
if (str.equals(ip[i])) {
dout.writeBytes(mac[i] + '\n');
found = true;
break;
}
}

if (!found) {
dout.writeBytes("MAC not found\n");
}
}

obj.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

Client.java

import java.io.*;
import java.net.*;
class Client {
public static void main(String args[])
{ try {
// BufferedReader for user input
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

// Connect to the server on localhost at port 3636


Socket clsct = new Socket("127.0.0.1", 3636);

// BufferedReader to read from server input stream


BufferedReader din = new BufferedReader(new
InputStreamReader(clsct.getInputStream()));

// DataOutputStream to write to server output stream


DataOutputStream dout = new DataOutputStream(clsct.getOutputStream());

System.out.println("Enter the Logical address (IP):");


String str1 = in.readLine(); // Read user input

dout.writeBytes(str1 + '\n'); // Send IP to server

// Read the response from the server


String str = din.readLine();
System.out.println("The Physical Address is: " + str);

// Close the connection


clsct.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
OUTPUT:
PROGRAM:

Server.java

import java.io.*;
import java.net.*;

class Server {
public static void main(String args[])
{ try {
// Create a server socket on port 3000
ServerSocket obj = new ServerSocket(3000);
System.out.println("Server started, waiting for client...");

// Accept the incoming client connection


Socket obj1 = obj.accept();
System.out.println("Client connected.");

// BufferedReader to read from client input stream


BufferedReader din = new BufferedReader(new
InputStreamReader(obj1.getInputStream()));

// DataOutputStream to write to client output stream


DataOutputStream dout = new DataOutputStream(obj1.getOutputStream());

// Define IP and MAC address pairs


String[] ip = {"165.165.80.80", "165.165.79.1"};
String[] mac = {"6A:08:AA:C2", "8A:BC:E3:FA"};

while (true) {
// Read the MAC address from the client
String str = din.readLine();
if (str == null) {
break; // Exit the loop if input is null (e.g., client disconnects)
}

boolean found = false;


// Look for the corresponding IP address for the given MAC
for (int i = 0; i < mac.length; i++) {
if (str.equals(mac[i]))
{ dout.writeBytes(ip[i] + '\n');
found = true;
break;
}
}

if (!found) {
dout.writeBytes("IP not found\n");
}
}
// Close the connection
obj1.close();
obj.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

Client.java

import java.io.*;
import java.net.*;

class Client {
public static void main(String args[])
{ try {
// BufferedReader for user input
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

// Create a socket to connect to the server


Socket clsct = new Socket("127.0.0.1", 3000);

// BufferedReader to read from the server's input stream


BufferedReader din = new BufferedReader(new
InputStreamReader(clsct.getInputStream()));

// DataOutputStream to write to the server's output stream


DataOutputStream dout = new
DataOutputStream(clsct.getOutputStream());

// Prompt user to enter the MAC address


System.out.println("Enter the Physical Address (MAC):");
String str1 = in.readLine(); // Read user input
// Send the MAC address to the server
dout.writeBytes(str1 + '\n');

// Read the server's response


String str = din.readLine();
System.out.println("The Logical address is (IP): " + str);

// Close the connection


clsct.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
OUTPUT:

.
EX.NO. 7. A. STUDY OF NETWORK SIMULATOR USING NS

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 behaviors. Due to its flexibility and modular
nature, NS2 has gained constant popularity in the networking research community since its birth
in 1989. Ever since, several revolutions and revisions have marked the growing maturity of the
tool, thanks to substantial contributions from the players in the field. Among these are the
University of California and Cornell University who developed the REAL network simulator,1 the
foundation which NS is based on. Since 1995 the Defense Advanced Research Projects Agency
(DARPA) supported development of NS through the Virtual Inter Network 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.
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.
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).

BASIC ARCHITECTURE:

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.
1. 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.
• It is not necessary to declare a data type for variable prior to the usage.
2. Basics of TCL
Syntax: command arg1 arg2
arg3

3. 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]
4. Wired TCL Script
Components Create the
eventscheduler
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
5. 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.
6. Initialization and Termination of TCL Script in NS-
2 An ns simulation starts with the command
7. 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 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 $tracefile
#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
8. 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:
9. $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.
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


$ns queue-limit $n0 $n2 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:
1. 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
2. $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.


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.


EX.NO. 7.B. SIMULATION OF CONGESTION CONTROL ALGORITHM USING NS

AIM:
To simulate a link failure and observe the congestion control algorithm using NS2.

ALGORITHM:

Step 1: Create a simulation object


Step 2: Open the nam trace file
Step 3: Define a 'finish' procedure
Step 4: Create eight nodes
Step 5: Create links between the nodes
Step 6: Create a UDP agent and attach it to node n2,n1,n0
Step 7: Create a CBR traffic source and attach it to udp0,udp1,udp2
Step 8: Create a Null agent (a traffic sink) and attach it to node n5,n6,n7
Step 9: Connect the traffic sources with the traffic sink
Step 10: Define different colors for data flows
Step 11: Schedule events for the CBR agents
Step 12: Call the finish procedure after 5 seconds of simulation time
Step 13: Run the simulation

PROGRAM:

#Create a simulator object


set ns [new Simulator]

#Open the nam trace file


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

#Define a 'finish' procedure


proc finish { } {
global ns nf
$ns flush-trace
#Close the trace file
close $nf
#Execute nam on the trace file
exec nam out.nam &
exit 0
}

#Create eight
nodes set n0 [$ns
node] set n1 [$ns
node] set n2 [$ns
node] set n3 [$ns
node] set n4 [$ns
node] set n5 [$ns
node] set n6 [$ns
node] set n7 [$ns
node]

#Create links between the nodes


$ns duplex-link $n0 $n3 1Mb 10ms RED
$ns duplex-link $n1 $n3 1Mb 10ms RED
$ns duplex-link $n2 $n3 1Mb 10ms RED
$ns duplex-link $n3 $n4 1Mb 10ms RED
$ns duplex-link $n4 $n5 1Mb 10ms RED
$ns duplex-link $n4 $n6 1Mb 10ms RED
$ns duplex-link $n4 $n7 1Mb 10ms RED

$ns duplex-link-op $n0 $n3 orient right-up


$ns duplex-link-op $n3 $n4 orient middle
$ns duplex-link-op $n2 $n3 orient right-down
$ns duplex-link-op $n4 $n5 orient right-up
$ns duplex-link-op $n4 $n7 orient right-down
$ns duplex-link-op $n1 $n3 orient right
$ns duplex-link-op $n6 $n4 orient left

#Create a UDP agent and attach it to node n2


set udp0 [new Agent/UDP]
$ns attach-agent $n2 $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 (a traffic sink) and attach it to node n5


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

#Connect the traffic sources with the traffic sink


$ns connect $udp0 $null0
#Create a UDP agent and attach it to node n1
set udp1 [new Agent/UDP]
$ns attach-agent $n1 $udp1

#Create a CBR traffic source and attach it to udp1


set cbr1 [new Application/Traffic/CBR]
$cbr1 set packetSize_ 500
$cbr1 set interval_ 0.005
$cbr1 attach-agent $udp1

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


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

#Connect the traffic sources with the traffic sink


$ns connect $udp1 $null0

#Create a UDP agent and attach it to node n0


set udp2 [new Agent/UDP]
$ns attach-agent $n0 $udp2
#Create a CBR traffic source and attach it to udp2
set cbr2 [new Application/Traffic/CBR]
$cbr2 set packet size_ 500
$cbr2 set interval_ 0.005
$cbr2 attach-agent $udp2
#Create a Null agent (a traffic sink) and attach it to node n7
set null0 [new Agent/Null]
$ns attach-agent $n7 $null0

#Connect the traffic sources with the traffic sink


$ns connect $udp2 $null0

$udp0 set fid_ 1

$udp1 set fid_ 2

$udp2 set fid_ 3

#Define different colors for data flows


$ns color 1 Red
$ns color 2 Green
$ns color 2 Blue

#Schedule events for the CBR agents


$ns at 0.1 "$cbr0 start"
$ns at 0.2 "$cbr1 start"
$ns at 0.5 "$cbr2 start"
$ns at 4.0 "$cbr2 stop"
$ns at 4.2 "$cbr1 stop"
$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:

RESULT:

Thus the congestion controlling algorithm using ns2 has been executed successfully and
output got verified.
EX.NO. 8.A. STUDY OF TCP PERFORMANCE

AIM:
To study about TCP performance in detail.

Introduction :
The transmission Control Protocol (TCP) is one of the most important protocols of Internet
Protocols suite. It is most widely used protocol for data transmission in communication network
such as internet.

Features
● TCP is reliable protocol. That is, the receiver always sends either positive or negative
acknowledgement about the data packet to the sender, so that the sender always has bright
clue about whether the data packet is reached the destination or it needs to resend it.
● TCP ensures that the data reaches intended destination in the same order it was sent.
● TCP is connection oriented. TCP requires that connection between two remote points be
established before sending actual data.
● TCP provides error-checking and recovery mechanism.
● TCP provides end-to-end communication.
● TCP provides flow control and quality of service.
● TCP operates in Client/Server point-to-point mode.
● TCP provides full duplex server, i.e. it can perform roles of both receiver and sender.

Header
The length of TCP header is minimum 20 bytes long and maximum 60 bytes.
Source port address. This is a 16-bit field that defines the port number of the application
program in the host that is sending the segment.
Destination port address. This is a 16-bit field that defines the port number of the application
program in the host that is receiving the segment.

Source port address. This is a 16-bit field that defines the port number of
the application program in the host that is sending the segment.
Destination port address. This is a 16-bit field that defines the port number of the application
program in the host that is receiving the segment.
Sequence number. This 32-bit field defines the number assigned to the first byte of data
contained in this segment. TCP is a stream transport protocol. To ensure connectivity, each
byte to be transmitted is numbered. The sequence number tells the destination which byte
in this sequence is the first byte in the segment. During connection establishment each
party uses a random number generator to create an initial sequence number (ISN), which
is usually different in each direction.
Acknowledgment number. This 32-bit field defines the byte number that the receiver of the
segment is expecting to receive from the other party. If the receiver of the segment has
successfully received byte number x from the other party, it returns x + 1 as the
acknowledgment number. Acknowledgment and data can be piggybacked together.
Header length. This 4-bit field indicates the number of 4-byte words in the TCP header. The
length of the header can be between 20 and 60 bytes. Therefore, the value of this field is
always between 5 (5 × 4 = 20) and 15 (15 × 4 = 60).
Control. This field defines 6 different control bits or flags. One or more of these bits can be set
at a time. These bits enable flow control, connection establishment and termination,
connection abortion, and the mode of data transfer in TCP.
Window size. This field defines the window size of the sending TCP in bytes. Note that the
length of this field is 16 bits, which means that the maximum size of the window is 65,535
bytes. This value is normally referred to as the receiving window (rwnd) and is determined
by the receiver. The sender must obey the dictation of the receiver in this case.
Checksum. This 16-bit field contains the checksum. The calculation of the checksum for TCP
follows the same procedure as the one described for UDP. However, the use of the
checksum in the UDP datagram is optional, whereas
the use of the checksum for TCP is mandatory. The same pseudoheader, serving the same
purpose, is added to the segment. For the TCP pseudoheader, the value for the protocol
field is 6.
Urgent pointer. This 16-bit field, which is valid only if the urgent flag is set, is used when the
segment contains urgent data. It defines a value that must be added to the sequence number
to obtain the number of the last urgent byte in the data section of the segment.
Options. There can be up to 40 bytes of optional information in the TCP header.

Addressing
TCP communication between two remote hosts is done by means of port numbers (TSAPs).
Ports numbers can range from 0 – 65535 which are divided as:
● System Ports (0 – 1023)
● User Ports ( 1024 – 49151)
● Private/Dynamic Ports (49152 – 65535)

Connection Management
TCP communication works in Server/Client model. The client initiates the connection and the
server either accepts or rejects it. Three-way handshaking is used for connection management.
Establishment
Client initiates the connection and sends the segment with a Sequence number. Server
acknowledges it back with its own Sequence number and ACK of client’s segment which is one
more than client’s Sequence number. Client after receiving ACK of its segment sends an
acknowledgement of Server’s response.

Release
Either of server and client can send TCP segment with FIN flag set to 1. When the
receiving end responds it back by Acknowledging FIN, that direction of TCP communication is
closed and connection is released.

Bandwidth Management
TCP uses the concept of window size to accommodate the need of Bandwidth
management. Window size tells the sender at the remote end, the number of data byte segments
the receiver at this end can receive. TCP uses slow start phase by using window size 1 and
increases the window size exponentially after each successful communication.
For example, the client uses windows size 2 and sends 2 bytes of data. When the
acknowledgement of this segment received the windows size is doubled to 4 and next sent the
segment sent will be 4 data bytes long. When the acknowledgement of 4-byte data segment is
received, the client sets windows size to 8 and so on.
If an acknowledgement is missed, i.e. data lost in transit network or it received NACK,
then the window size is reduced to half and slow start phase starts again.
Error Control &and Flow Control
TCP uses port numbers to know what application process it needs to handover the data segment.
Along with that, it uses sequence numbers to synchronize itself with the remote host. All data
segments are sent and received with sequence numbers. The Sender knows which last data
segment was received by the Receiver when it gets ACK. The Receiver knows about the last
segment sent by the Sender by referring to the sequence number of recently received packet. If the
sequence number of a segment recently received does not match with the sequence number the
receiver was expecting, then it is discarded and NACK is sent back. If two segments arrive with
the same sequence number, the TCP timestamp value is compared to make a decision.

Multiplexing
The technique to combine two or more data streams in one session is called Multiplexing.
When a TCP client initializes a connection with Server, it always refers to a welldefined port
number which indicates the application process. The client itself uses a randomly generated port
number from private port number pools.
Using TCP Multiplexing, a client can communicate with a number of different application
process in a single session. For example, a client requests a web page which in turn contains
different types of data (HTTP, SMTP, FTP etc.) the TCP session timeout is increased and the
session is kept open for longer time so that the three-way handshake overhead can be avoided.
This enables the client system to receive multiple connection over single virtual connection.
Thesevirtual connections are not good for Servers if the timeout is too long.

Congestion Control
When large amount of data is fed to system which is not capable of handling it, congestion
occurs. TCP controls congestion by means of Window mechanism. TCP sets a window size telling
the other end how much data segment to send. TCP may use three algorithms for congestion
control:
∙ Additive increase, Multiplicative Decrease
∙ Slow Start
∙ Timeout React

Timer Management
TCP uses different types of timer to control and management various tasks:

Keep-alive timer:
∙ This timer is used to check the integrity and validity of a connection.
∙ When keep-alive time expires, the host sends a probe to check if the connection still exists.

Retransmission timer:
∙ This timer maintains stateful session of data sent.
∙ If the acknowledgement of sent data does not receive within the Retransmission time, the data
segment is sent again.

Persist timer:
∙ TCP session can be paused by either host by sending Window Size 0.
∙ To resume the session a host needs to send Window Size with some larger value. ∙ If this
segment never reaches the other end, both ends may wait for each other for infinite time.
∙ Persist Timer helps avoid deadlocks in communication.

Timed-Wait:
∙ After releasing a connection, either of the hosts waits for a Timed-Wait time to terminate the
connection completely.
∙ This is in order to make sure that the other end has received the acknowledgement of its
connection termination request. Timed-out can be a maximum of 240 seconds (4 minutes).
Crash Recovery
TCP is very reliable protocol. It provides sequence number to each of byte sent in segment.
It provides the feedback mechanism i.e. when a host receives a packet, it is bound to ACK that
packet having the next sequence number expected (if it is not the last segment).
When a TCP Server crashes mid-way communication and re-starts its process it sends
TPDU broadcast to all its hosts. The hosts can then send the last data segment which was never
unacknowledged and carry onwards.

Algorithm
1. Create a simulator object
2. Define different flows for data flows
3. Trace all events in a nam file and text file
4. Create source nodes (s1, s2, s3), gateway (G) and receiver (r)
5. Describe their layout topology
6. Specify the link between nodes
7. Define the queue size between nodes G and r as 5
8. Monitor queue on all links vertically 90°
9. Create TCP agents tcp1, tcp2, tcp3 and attach it to nodes s1, s2 and s3 respectively
10. Create three TCP sinks and attach it to node r
11. Connect traffic sources to the sink
12. Create FTP agents ftp1, ftp2, ftp3 and attach it to tcp1, tcp2 and tcp3 respectively
13. Label the nodes at start time
14. Schedule ftp1, ftp2, ftp3 to start at 0.1 and stop at 5.0 seconds
15. Call finish procedure at 5.25 seconds
16. Run the simulation
17. Execute NAM on the trace file
18. Observe the simulated events on the NAM editor and packet flow on link G to r
19. View the trace file and analyse the events
20. Stop

PROGRAM : File name - TCP.tcl


#Create a simulator object
set ns [new Simulator]

#Open trace files


set f [open droptail-queue-out.tr w]
$ns trace-all $f

#Open the nam trace file


set nf [open droptail-queue-out.nam w]
$ns namtrace-all $nf

#s1, s2 and s3 act as sources.


set s1 [$ns node]
set s2 [$ns node]
set s3 [$ns node]

#G acts as a gateway
set G [$ns node]

#r acts as a receiver
set r [$ns node]
#Define different colors for data flows
$ns color 1 red
$ns color 2 SeaGreen
$ns color 3 blue

#Create links between the nodes


$ns duplex-link $s1 $G 6Mb 10ms DropTail
$ns duplex-link $s2 $G 6Mb 10ms DropTail
$ns duplex-link $s3 $G 6Mb 10ms DropTail
$ns duplex-link $G $r 3Mb 10ms DropTail

#Define the layout of the nodes


$ns duplex-link-op $s1 $G orient right-up
$ns duplex-link-op $s2 $G orient right
$ns duplex-link-op $s3 $G orient right-down
$ns duplex-link-op $G $r orient right

#Define the queue size for the link between node G and r
$ns queue-limit $G $r 5

#Monitor the queues for links vertically


$ns duplex-link-op $s1 $G queuePos 0.5
$ns duplex-link-op $s2 $G queuePos 0.5
$ns duplex-link-op $s3 $G queuePos 0.5
$ns duplex-link-op $G $r queuePos 0.5

#Create a TCP agent and attach it to node s1


set tcp1 [new Agent/TCP/Reno]
$ns attach-agent $s1 $tcp1
$tcp1 set window_ 8
$tcp1 set fid_ 1

#Create a TCP agent and attach it to node s2


set tcp2 [new Agent/TCP/Reno]
$ns attach-agent $s2 $tcp2
$tcp2 set window_ 8
$tcp2 set fid_ 2

#Create a TCP agent and attach it to node s3


set tcp3 [new Agent/TCP/Reno]
$ns attach-agent $s3 $tcp3
$tcp3 set window_ 4
$tcp3 set fid_ 3

#Create TCP sink agents and attach them to node r


set sink1 [new Agent/TCPSink]
set sink2 [new Agent/TCPSink]
set sink3 [new Agent/TCPSink]
$ns attach-agent $r $sink1
$ns attach-agent $r $sink2
$ns attach-agent $r $sink3
#Connect the traffic sources with the traffic sinks
$ns connect $tcp1 $sink1
$ns connect $tcp2 $sink2
$ns connect $tcp3 $sink3
#Create FTP applications and attach them to agents
set ftp1 [new Application/FTP]
$ftp1 attach-agent $tcp1
set ftp2 [new Application/FTP]
$ftp2 attach-agent $tcp2
set ftp3 [new Application/FTP]
$ftp3 attach-agent $tcp3

#Define a 'finish' procedure


proc finish {} {
global ns
$ns flush-trace
puts "running nam..."
exec nam -a droptail-queue-out.nam &
exit 0
}

#Define label for nodes


$ns at 0.0 "$s1 label Sender1"
$ns at 0.0 "$s2 label Sender2"
$ns at 0.0 "$s3 label Sender3"
$ns at 0.0 "$G label Gateway"
$ns at 0.0 "$r label Receiver"

#Schedule ftp events


$ns at 0.1 "$ftp1 start"
$ns at 0.1 "$ftp2 start"
$ns at 0.1 "$ftp3 start"
$ns at 5.0 "$ftp1 stop"
$ns at 5.0 "$ftp2 stop"
$ns at 5.0 "$ftp3 stop"

#Call finish procedure after 5 seconds of simulation time


$ns at 5.25 "finish"

#Run the simulation


$ns run
OUTPUT:

RESULT:
Thus the TCP performance is studied in detail.
EX.NO.8.B. STUDY OF UDP PERFORMANCE

AIM:
To study about UDP performance in detail.

Introduction :
The User Datagram Protocol (UDP) is simplest Transport Layer communication protocol
available of the TCP/IP protocol suite. It involves minimum amount of communication
mechanism. UDP is said to be an unreliable transport protocol but it uses IP services which
provides best effort delivery mechanism.
In UDP, the receiver does not generate an acknowledgement of packet received and in
turn, the sender does not wait for any acknowledgement of packet sent. This shortcoming makes
this protocol unreliable as well as easier on processing.

Requirement of UDP
A question may arise, why do we need an unreliable protocol to transport the data? We
deploy UDP where the acknowledgement packets share significant amount of bandwidth along
with the actual data. For example, in case of video streaming, thousands of packets are forwarded
towards its users. Acknowledging all the packets is troublesome and may contain huge amount of
bandwidth wastage. The best delivery mechanism of underlying IP protocol ensures best efforts to
deliver its packets, but even if some packets in video streaming get lost, the impact is not
calamitous and can be ignored easily. Loss of few packets in video and voice traffic sometimes
goes unnoticed.

Features
∙ UDP is used when acknowledgement of data does not hold any significance.
∙ UDP is good protocol for data flowing in one direction.
∙ UDP is simple and suitable for query based communications.
∙ UDP is not connection oriented.
∙ UDP does not provide congestion control mechanism.
∙ UDP does not guarantee ordered delivery of data.
∙ UDP is stateless.
∙ UDP is suitable protocol for streaming applications such as VoIP, multimedia streaming.

UDP Header
UDP header is as simple as its function.

UDP header contains four main parameters:


∙ Source Port - This 16 bits information is used to identify the source port of the packet.
∙ Destination Port - This 16 bits information, is used identify application level service on
destination machine.
∙ Length - Length field specifies the entire length of UDP packet (including header). It is 16-bits
field and minimum value is 8-byte, i.e. the size of UDP header itself.
∙ Checksum - This field stores the checksum value generated by the sender before sending. IPv4
has this field as optional so when checksum field does not contain any value it is made 0 and all
its bits are set to zero.

UDP application
Here are few applications where UDP is used to transmit data:
∙ Domain Name Services
∙ Simple Network Management Protocol
∙ Trivial File Transfer Protocol
∙ Routing Information Protocol
∙ Kerberos

Algorithm
1. Create a simulator object
2. Define different color for data flows
3. Trace all events in a nam file.
4. Create four nodes n0, n1, n2 and n3
5. Describe their layout topology
6. Specify the link capacity between nodes
7. Monitor queue on the link n2 to n3 vertically 90°
8. Create a UDP agents udp0, udp1 and attach it to nodes n0 and n1 respectively
9. Create a CBR traffic cbr0, cbr1 and attach it to udp0 and udp1 respectively
10. Create a traffic sink and attach it to node n3
11. Connect sources to the sink
12. Label the nodes
13. Schedule cbr0 to start at 0.5 and stop at 4.5 seconds
14. Schedule cbr1 to start at 1.0 and stop at 4.0 seconds
15. Call finish procedure at 5.0 seconds
16. Run the simulation
17. Execute NAM on the trace file
18. Observe simulated events on the NAM and packet flow on link n2 to n3
19. Stop

PROGRAM : File name - UDP.tcl


#Create a simulator object
set ns [new Simulator]

#Define different colors for data flows


$ns color 1 Blue
$ns color 2 Red

#Open the nam trace file


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

#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 1Mb 10ms DropTail
$ns duplex-link $n1 $n2 1Mb 10ms DropTail
$ns duplex-link $n3 $n2 1Mb 10ms SFQ
#Specify layout of nodes
$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 the link 2ņ3 vertically


$ns duplex-link-op $n2 $n3 queuePos 0.5

#Create a UDP agent and attach it to node n0


set udp0 [new Agent/UDP]
$udp0 set class_ 1
$ns attach-agent $n0 $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 UDP agent and attach it to node n1


set udp1 [new Agent/UDP]
$udp1 set class_ 2
$ns attach-agent $n1 $udp1

# Create a CBR traffic source and attach it to udp1


set cbr1 [new Application/Traffic/CBR]
$cbr1 set packetSize_ 500
$cbr1 set interval_ 0.005
$cbr1 attach-agent $udp1

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


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

#Connect traffic sources with the traffic sink


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

#Define finish procedure


proc finish {} {
global ns nf
$ns flush-trace
#Close the trace file
close $nf
#Execute nam on the trace file
exec nam -a out.nam &
exit 0
}

#Define label for nodes


$ns at 0.0 "$n0 label Sender1"
$ns at 0.0 "$n1 label Sender2"
$ns at 0.0 "$n2 label Router"
$ns at 0.0 "$n3 label Receiver"
#Schedule events for the CBR agents
$ns at 0.5 "$cbr0 start"
$ns at 1.0 "$cbr1 start"
$ns at 4.0 "$cbr1 stop"
$ns at 4.5 "$cbr0 stop"

#Call finish procedure after 5 seconds of simulation time


$ns at 5.0 "finish"

#Run the simulation


$ns run

OUTPUT:

RESULT:
Thus the UDP performance is studied in detail.
EX.NO. 9.A. SIMULATION OF DISTANCE VECTOR ROUTING ALGORITHM

AIM:
To simulate and observe traffic route of a network using distance vector routing protocol.

ALGORITHM:
Step 1: Create a simulator object
Step 2: Set routing protocol to Distance vector routing
Step 3: Trace packets on all links on to NAM trace and text trace file.
Step 4: Define finish procedure to close files, flash tracing and run NAM
Step 5: Create 5 nodes
Step 6: Specify the link characteristics between the nodes
Step 7: Describer their layout topology as a octagon
Step 8: Add UDP agent for node n0
Step 9: Create CBR traffic on the top of UDP and set traffic parameters
Step 10: Add NULL agent to node n3
Step 11: Connect source and sink
Step 12: Schedule as follows
● Start traffic flow at 1.0
● Down the link n1 – n2 at 15.0
● Up the link n1 – n2 at 25.0
● Call finish procedure at 35.0
Step 13: Start the scheduler
Step 14: Observe the traffic route when the link is up and down
Step 15: View the simulated events and trace file analyze it
Step 16: Stop.

PROGRAM:

#Create a simulator object


set ns [new Simulator]

#Use distance vector routing


$ns rtproto DV

#Open the nam trace file


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

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

#Define 'finish' procedure


proc finish {} {
global ns nf
$ns flush-trace
#Close the trace file
close $nf
#Execute nam on the trace file
exec nam -a out.nam &
exit 0
}
# Create 8 nodes
set n1 [$ns
node] set n2
[$ns node] set
n3 [$ns node]
set n4 [$ns
node] set n5
[$ns node] set
n6 [$ns node]
set n7 [$ns
node] set n8
[$ns node]

# Specify link characterestics


$ns duplex-link $n1 $n2 1Mb 10ms DropTail
$ns duplex-link $n2 $n3 1Mb 10ms DropTail
$ns duplex-link $n3 $n4 1Mb 10ms DropTail
$ns duplex-link $n4 $n5 1Mb 10ms DropTail
$ns duplex-link $n5 $n6 1Mb 10ms DropTail
$ns duplex-link $n6 $n7 1Mb 10ms DropTail
$ns duplex-link $n7 $n8 1Mb 10ms DropTail
$ns duplex-link $n8 $n1 1Mb 10ms DropTail

# specify layout as a octagon


$ns duplex-link-op $n1 $n2 orient left-up
$ns duplex-link-op $n2 $n3 orient up
$ns duplex-link-op $n3 $n4 orient right-up
$ns duplex-link-op $n4 $n5 orient right
$ns duplex-link-op $n5 $n6 orient right-down
$ns duplex-link-op $n6 $n7 orient down
$ns duplex-link-op $n7 $n8 orient left-down
$ns duplex-link-op $n8 $n1 orient left

#Create a UDP agent and attach it to node n1


set udp0 [new Agent/UDP]
$ns attach-agent $n1 $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 (a traffic sink) and attach it to node n4


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

#Connect the traffic source with the traffic sink


$ns connect $udp0 $null0

#Schedule events for the CBR agent and the network dynamics
$ns at 0.0 "$n1 label Source"
$ns at 0.0 "$n4 label Destination"
$ns at 0.5 "$cbr0 start"
$ns rtmodel-at 1.0 down $n3 $n4
$ns rtmodel-at 2.0 up $n3 $n4
$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:
RESULT:
Thus the simulation of distance vector routing algorithm using ns2 has been executed
successfully and output got verified.
EX.NO. 9.B. SIMULATION OF LINK STATE ROUTING ALGORITHM

AIM:
To simulate and observe traffic route of a network using link state routing algorithm.

ALGORITHM:
Step 1: Create a simulator object
Step 2: Trace packets on all links on to NAM trace and text trace file.
Step 3: Define finish procedure to close files, flash tracing and run NAM
Step 4: Create 5 nodes
Step 5: Specify the link characteristics between the nodes
Step 6: Describer their layout topology as a octagon
Step 7: Add UDP agent for node n0
Step 8: Create CBR traffic on the top of UDP and set traffic parameters
Step 9: Add NULL agent to node n3
Step 10: Connect source and sink
Step 11: Set routing protocol to Distance vector routing
Step 12: Start the scheduler
Step 13: Observe the traffic route when the link is up and down
Step 14: View the simulated events and trace file analyze it
Step 15: Stop.

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
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
OUTPUT:
RESULT:
Thus the simulation of link state routing algorithm using ns2 has been executed
successfully and output got verified.
PROGRAM:

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

int main() {
int i, j, k, count, err_pos = 0, flag = 0;
char dw[20], cw[20], data[20];

printf("Enter data as binary bit stream (7 bits):\n");


scanf("%s", data);

// Generating the codeword with parity bits


for (i = 1, j = 0, k = 0; i < 12; i++) {
if (i == (int)pow(2, j)) {
dw[i] = '?'; j+
+;
} else {
dw[i] = data[k]; k+
+;
}
}

// Calculating parity bits


for (i = 0; i < 4; i++) {
count = 0;
for (j = (int)pow(2, i); j < 12; j += (int)pow(2, i) * 2)
{ for (k = 0; k < (int)pow(2, i) && j + k < 12; k++) {
if (dw[j + k] == '1') count++;
}
}
dw[(int)pow(2, i)] = (count % 2 == 0) ? '0' : '1';
}

// Printing the generated codeword


printf("Generated code word is:\n");
for (i = 1; i < 12; i++) {
printf("%c", dw[i]);
}
printf("\n\nEnter the received Hamming code:\n");
scanf("%s", cw);

// Adjusting the index for 1-based numbering


for (i = 12; i > 0; i--) {
cw[i] = cw[i - 1];
}

// Error detection
for (i = 0; i < 4; i++) {
count = 0;
for (j = (int)pow(2, i); j < 12; j += (int)pow(2, i) * 2)
{ for (k = 0; k < (int)pow(2, i) && j + k < 12; k++) {
if (cw[j + k] == '1') count++;
}
}
if (count % 2 != 0) {
err_pos = err_pos + (int)pow(2, i);
}
}

// Error correction
if (err_pos == 0) {
printf("\n\nThere is no error in the received code word.\n");
} else {
if (cw[err_pos] == dw[err_pos]) {
printf("\n\nThere are 2 or more errors in the received code...\n");
printf("Sorry...! Hamming code cannot correct 2 or more errors.\n");
flag = 1;
} else {
printf("\n\nThere is an error in bit position %d of the received code word.\n", err_pos);
if (flag == 0) {
cw[err_pos] = (cw[err_pos] == '1') ? '0' : '1'; printf("\
n\nCorrected code word is:\n");
for (i = 1; i < 12; i++)
{ printf("%c", cw[i]);
}
}
}
}
printf("\n\n");

return 0;
}
OUTPUT:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy