231CS42B Networks Laboratory
231CS42B Networks Laboratory
LAB MANUAL
COURSE CODE : 231CS42B
COURSE NAME : NETWORKS LABORATORY
YEAR/SEM : II/IV
PREPARED BY,
J.CINDHAMANI, M.Tech(SoftTech).,
J.JAYALAKSHMI, M.E(CSE).,
DEPT OF AI&DS
VISION
To promote centre of excellence through effectual Teaching and Learning, imparting the contemporary
knowledge centric education through innovative research in multidisciplinary fields.
MISSION
M1 - To impart quality technical skills through practicing, knowledge updating in recent technology
and produce professionals with multidisciplinary and leadership skills.
M2 - To promote innovative thinking for design and development of software products of varying
complexity with intelligence to fulfill the global standards and demands
M3 - To inculcate professional ethics among the graduates and to adapt the changing technologies
through lifelong learning
PROGRAMME OUTCOMES (POs)
POs Programme Outcomes (POs)
Problem Analysis: Identify, formulate, review research literature and analyze complex engineering
problems reaching substantiated conclusions with consideration for sustainable development. (WK1
PO2
to WK4)
Design/Development of Solutions: Design creative solutions for complex engineering problems and
design/develop systems/components/processes to meet identified needs with consideration for the public
PO3 health and safety, whole-life cost, net zero carbon, culture, society and environment as required. (WK5)
Engineering Tool Usage: Create, select and apply appropriate techniques, resources and modern
PO5 engineering & IT tools, including prediction and modelling recognizing their limitations to solve complex
engineering problems. (WK2 and WK6)
The Engineer and The World: Analyze and evaluate societal and environmental aspects while solving
PO6 complex engineering problems for its impact on sustainability with reference to economy, health, safety,
legal framework, culture and environment. (WK1, WK5, and WK7).
Ethics: Apply ethical principles and commit to professional ethics, human values, diversity and inclusion;
PO7 adhere to national & international laws. (WK9)
Individual and Collaborative Team work: Function effectively as an individual, and as a member or leader
PO8
in diverse/multi-disciplinary teams.
Communication: Communicate effectively and inclusively within the engineering community and
society at large, such as being able to comprehend and write effective reports and design documentation,
PO9 make effective presentations considering cultural, language, and learning differences
Project Management and Finance: Apply knowledge and understanding of engineering management
PO10 principles and economic decision-making and apply these to one’s own work, as a member and leader in
a team, and to manage projects and in multidisciplinary environments.
Life-Long Learning: Recognize the need for, and have the preparation and ability for i)
Independent and life-long learning ii) Adaptability to new and emerging technologies
PO11 and iii)Critical thinking in the broadest context of technological change. (WK8)
COURSE OBJECTIVES
The student should be made to:
• Understand the techniques of network commands and Learn socket programming.
• Implement problems using and analyze various network protocols
• Know how to apply simulation tools
LIST OF EXPERIMENTS
Ex.
NAME OF THE EXERCISE(s) CO
No.
LEARN TO USE COMMANDS LIKE TCPDUMP,
NETSTAT, IFCONFIG, NSLOOKUP AND TRACE
1 ROUTE. CAPTURE PING AND TRACE ROUTE CO1
PDUS USING A NETWORK PROTOCOL
ANALYZER AND EXAMINE.
WRITE A HTTP WEB CLIENT PROGRAM TO
2 DOWNLOAD A WEB PAGE USING TCP SOCKETS. CO2
Course
CO Statements
Outcome
Identify the basic network tools and packet analyzers to monitor and
CO1
troubleshoot networks.
CO2 Apply the socket programs to simulate network protocols and services.
Simulate and evaluate network protocols using simulation tools.
CO3
CO-PO/PSO MAPPING
Course
Outco
me
CO1 3 3 2 - - - - 1 - - 1 3 2 -
CO2 3 3 2 - - 2 1 - - - 1 3 2 1
CO3 3 3 2 - - 2 1 - - - 1 3 2 1
CO 3 3 2 - - 2 1 1 - - 1 3 2 1
Aim:
To use commands like tcpdump, netstat, ifconfig, nslookup and trace route. Capture ping and
trace route PDUs using a network protocol analyzer and examine.
1. Tcpdump
Tcpdump is a command line utility that allows you to capture and analyze network traffic going
through your system.
Procedure
Check if tcpdump is installed on your system
$ which tcpdump
/usr/sbin/tcpdump
Iftcpdump is not installed,
$ sudo apt install tcpdump
To get Supervisor Privilege
$ su
(and password 123456)
$ sudo –i to change #
($ is changed to # and the commands can be executed in supervisor)
Capturing packets with tcpdump
Use the command tcpdump -D to see which interfaces are available for capture.
[root@localhost cse]# tcpdump -D
1.nflog (Linux netfilter log (NFLOG) interface)
2.nfqueue (Linux netfilter queue (NFQUEUE) interface)
3.usbmon1 (USB bus number 1)
4. enp2s0
5. usbmon2 (USB bus number 2)
6. any (Pseudo-device that captures on all interfaces)
7.lo [Loopback]
Capture all packets in any interface by running this command:
[root@localhost cse]# tcpdump -i any2
06:03:58.258143 ARP, Request who-has 172.16.51.87 tell 172.16.22.25, length 46
06:03:58.258225 ARP, Request who-has 172.16.51.88 tell 172.16.22.25, length 46
06:03:58.260828 ARP, Request who-has 172.16.51.122 tell 172.16.22.25, length 46
06:03:58.260903 ARP, Request who-has 172.16.51.123 tell 172.16.22.25, length 46
^C
5244 packets captured
1
59636 packets received by filter
54378 packets dropped by kernel
(Press ctrl+C to stop execution)
Filter packets based on the source or destination IP Address
[root@localhost ]#tcpdump -i any -c5 -nn src 172.16.20.138
6:10:30.712414 ARP, Request who-has 172.16.16.16 tell 172.16.20.138, length 28
06:10:31.483765 IP 172.16.20.138.47997 > 51.158.186.98.123: NTPv4, Client, length 48
5 packets captured
5 packets received by filter
0 packets dropped by kernel
[root@localhost ]#tcpdump -i any -c5 -nn dst 172.16.20.139
6:10:30.712414 ARP, Request who-has 172.16.16.16 tell 172.16.20.138, length 28
06:10:31.483765 IP 172.16.20.138.47997 > 51.158.186.98.123: NTPv4, Client, length 48
5 packets captured
5 packets received by filter
0 packets dropped by kernel
Ping command:
2. netstat
netstat (network statistics) is a command line tool for monitoring network connections both
incoming
and outgoing as well as viewing routing tables, interface statistics etc.
2
3.
3.ifconfig:
In Windows, ipconfig is a console application designed to run from the Windows command
prompt. This utility allows you to get the IP address information of a Windows computer.
It also allows some control over active TCP/IP connections. Ipconfig replaced the older winipcfg
utility.
Using ipconfig From the command prompt, type ipconfig to run the utility with default options.
The output of the default command contains the IP address, network mask, and gateway for all
physical and virtual network adapter
4. nslookup
nslookup (stands for “Name Server Lookup”) is a useful command for getting information from
DNS server. It is a network administration tool for querying the Domain Name System (DNS) to
obtain undertakes from its source to its destination.
3
5. Traceroute:
RESULT:
Thus the commands like tcpdump, netstat, ifconfig, nslookup and trace route are examined
successfully.
4
EXP:NO:2
WRITE A HTTP WEB CLIENT PROGRAM TO DOWNLOAD A WEB PAGE USING
TCP SOCKET
AIM:
To Write a HTTP web client program to download a web page using TCP sockets.
ALGORITHM:
CLIENT SIDE:
1) Start the program.
2) Create a socket which binds the Ip address of server and the port address to acquire
service.
3) After establishing connection send the url to server.
4) Open a file and store the received data into the file.
5) Close the socket.
6) End the program.
SERVER SIDE:
1) Start the program.
2) Create a server socket to activate the port address.
3) Create a socket for the server socket which accepts the connection.
4) After establishing connection receive url from client.
5) Download the content of the url received and send the data to client.
6) Close the socket.
7) End the program.
PROGRAM:
SERVER:
import java.net.*;
import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.*;
class Server {
5
System.out.println("Client connected.");
InputStream in = socket.getInputStream();
DataInputStream dis = new DataInputStream(in);
int len = dis.readInt();
System.out.println("Image Size: " + len/1024 + "KB");
byte[] data = new byte[len];
dis.readFully(data);
dis.close();
in.close();
InputStream ian = new ByteArrayInputStream(data);
BufferedImage bImage = ImageIO.read(ian); JFrame f =
new JFrame("Server"); ImageIcon icon = new
ImageIcon(bImage);
JLabel l = new JLabel();
l.setIcon(icon);
f.add(l);
f.pack();
f.setVisible(true); }}
CLIENT:
import java.net.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
try {
// Establishing connection to the server
soc = new Socket("localhost", 4000);
System.out.println("Client is running. Connected to server.");
6
}
img = ImageIO.read(imageFile);
System.out.println("Reading image from disk.");
// Close streams
dos.close();
out.close();
} catch (IOException e) {
System.out.println("Exception: " + e.getMessage());
} finally {
// Ensure the socket is closed
try {
if (soc != null && !soc.isClosed()) {
soc.close();
System.out.println("Connection closed.");
}
} catch (IOException e) {
System.out.println("Error closing socket: " + e.getMessage());
}
}
}
7
OUTPUT:
SERVER:
CLIENT:
RESULT:
Thus the program to write a HTTP web client to download a web page using TCP sockets
has been executed and verified successfully
8
EXP:NO:3A
APPLICATIONS USING TCP SOCKETS LIKE: A) ECHO CLIENT AND ECHO
SERVER
AIM:
ALGORITHM:
CLIENT SIDE
2. Create a socket which binds the Ip address of server and the port address to acquire
service.
SERVER SIDE
3. Create a socket for the server socket which accepts the connection.
9
PROGRAM:
ECHO CLIENT:
import java.io.*;
import java.net.*;
public class eclient
{
public static void main(String args[])
{
Socket c=null;
String line;
DataInputStream is,is1;
PrintStream os;
try
{
c=new Socket("localhost",8080);
}
catch(IOException e)
{
System.out.println(e);
}
try
{
os=new PrintStream(c.getOutputStream());
is=new DataInputStream(System.in);
is1=new DataInputStream(c.getInputStream());
do
{
System.out.println("client");
line=is.readLine();
os.println(line);
if(!line.equals("exit"))
System.out.println("server:"+is1.readLine());
}while(!line.equals("exit"));
}
catch(IOException e)
{
System.out.println("socket closed");
}}}
ECHO SERVER:
import java.io.*;
import java.net.*;
import java.lang.*;
public class eserver
10
{
public static void main(String args[])throws IOException
{
ServerSocket s=null;
String line;
DataInputStream is;
PrintStream ps;
Socket c=null;
try
{
s=new ServerSocket(8080);
}
catch(IOException e)
{
System.out.println(e);
}
try
{
c=s.accept();
is=new DataInputStream(c.getInputStream());
ps=new PrintStream(c.getOutputStream());
while(true)
{
line=is.readLine();
System.out.println("msg received and sent back to client");
ps.println(line);
}
}
catch(IOException e)
{
System.out.println(e);
}
}
}
OUTPUT:
ECHO SERVER:
11
ECHO CLIENT:
RESULT:
Thus the program to write a socket program for implementation of echo client and server has
been executed and verified successfully.
12
EXP:NO:3B
APPLICATIONS USING TCP SOCKETS LIKE: CHAT
AIM:
ALGORITHM:
CLIENT
5. The client accept the connection and to send the data from client to server.
6. The client communicates the server to send the end of the message
SERVER
5. The server accept the connection and to send the data from server to client and
6. vice versa
7. The server communicate the client to send the end of the message.
13
PROGRAM:
TCP SERVER1:
import java.net.*;
import java.io.*;
System.out.println("Client connected!");
String line;
do {
line = clientInput.readLine(); // Read from client
if (line == null) break; // Handle client disconnection
} while (!line.equalsIgnoreCase("quit"));
System.out.println("Connection closed.");
}
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
TCP CLIENT1:
import java.net.*;
import java.io.*;
14
public static void main(String[] args) {
try (Socket socket = new Socket("192.168.23.196", 9999);
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
BufferedReader serverInput = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter serverOutput = new PrintWriter(socket.getOutputStream(), true)) {
do {
System.out.print("Client: ");
line = userInput.readLine(); // Read user input
if (serverResponse == null) {
System.out.println("Server disconnected.");
break;
}
System.out.println("Connection closed.");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
15
OUTPUT:
TCPSERVER1:
TCPCLIENT1:
RESULT:
Thus the program to write a client-server application for chat using TCP has been executed and
verified successfully.
16
EXP:NO:3C
APPLICATIONS USING TCP SOCKETS LIKE: FILE TRANSFER
EXP:NO:3C
APPLICATIONS USING TCP SOCKETS LIKE: FILE TRANSFER
AIM:
ALGORITHM:
CLIENT SIDE
1. Start.
5. After getting approval from the server ,the client either get file from the server or send
SERVER SIDE
1. Start.
3. Server reads the filename and sends the data stored in the file for the‘get’ request.
4. It reads the data from the input stream and writes it to a file in theserver for the ‘put’
instruction.
6. Stop.
17
PROGRAM:
SERVER:
import java.net.*;
import java.io.*;
public class FileServer
{
public static void main (String [] args ) throws IOException {
ServerSocket servsock = new ServerSocket(13267);
while (true)
{
System.out.println("Waiting..."); Socket sock =
servsock.accept(); System.out.println("Accepte connection : " + sock);
File myFile = new File("source.pdf");
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
sock.close();
}}}
CLIENT:
import java.net.*;
import java.io.*;
18
bytesRead = is.read(mybytearray, 0, mybytearray.length);
current = bytesRead;
OUTPUT:
SERVER:
CLIENT:
19
RESULT:
Thus the program to Perform File Transfer in Client & Server Using TCP/IP has been executed
and verified successfully.
20
EXP:NO:4
SIMULATION OF DNS USING UDP SOCKET
AIM:
ALGORITHM:
5.If your frames reach the server it will send ACK signal to client otherwise it will
PROGRAM:
SERVER:
import java.io.*;
import java.net.*;
public class udpdnsserver
{
private static int indexOf(String[] array, String str)
{
str = str.trim();
for (int i=0; i < array.length; i++)
{
21
if (array[i].equals(str)) return i;
}
return -1;
}
public static void main(String arg[])throws IOException
{
String[] hosts = {"yahoo.com", "gmail.com","cricinfo.com", "facebook.com"};
String[] ip = {"68.180.206.184", "209.85.148.19","80.168.92.140", "69.63.189.16"};
System.out.println("Press Ctrl + C to Quit");
while (true){
DatagramSocket serversocket=new DatagramSocket(1362);
byte[] senddata = new byte[1021];
byte[] receivedata = new byte[1021];
DatagramPacket recvpack = new DatagramPacket(receivedata, receivedata.length);
serversocket.receive(recvpack);
String sen = new String(recvpack.getData()); InetAddress ipaddress =
recvpack.getAddress(); int port = recvpack.getPort();
String capsent;
System.out.println("Request for host " + sen);
if(indexOf (hosts, sen) != -1) capsent = ip[indexOf
(hosts, sen)]; else capsent = "Host Not Found";
senddata = capsent.getBytes();
DatagramPacket pack = new DatagramPacket (senddata, senddata.length,ipaddress,port);
serversocket.send(pack);
serversocket.close();
}
}
22
}
CLIENT:
import java.io.*; import java.net.*;
public class udpdnsclient
{
public static void main(String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientsocket = new DatagramSocket();
InetAddress ipaddress;
if (args.length == 0)
ipaddress = InetAddress.getLocalHost();
else
ipaddress = InetAddress.getByName(args[0]);
byte[] senddata =new byte[1024];
byte[] receivedata = new byte[1024];
int portaddr = 1362;
System.out.print("Enter the hostname : ");
String sentence = br.readLine();
senddata = sentence.getBytes();
DatagramPacket pack = new DatagramPacket(senddata,senddata.length, ipaddress,portaddr);
clientsocket.send(pack);
DatagramPacket recvpack =new DatagramPacket(receivedata,receivedata.length);
clientsocket.receive(recvpack);
String modified = new String(recvpack.getData());
System.out.println("IP Address: " + modified);
clientsocket.close();
23
}
}
OUTPUT:
SERVER:
CLIENT:
RESULT:
Thus the program perform to Simulation of DNS using UDP sockets has been executed and
verified successfully.
24
EXP:NO:5
USE A TOOL LIKE WIRESHARK TO CAPTURE PACKETS AND EXAMINE THE
PACKETS
Aim :
To implement the code to capture packets and examine the packets using wireshark.
Procedure:
1. A network packet analyzer will try to capture network packets and tries to display that packet
data as detailed as possible.
Step 2:
Start the Wireshark application. When Wireshark is first run, a default, or blank window is
shown. To list the available network interfaces, select the Capture->Interfaces menu option.
25
Generate some network traffic with a Web Browser, such as Internet Explorer or Chrome. Your
Wireshark window should show the packets, and now look something like.
To stop the capture, select the Capture->Stop menu option, Ctrl+E, or the Stop toolbar button.
What you have created is a Packet Capture or ‘pcap’, which you can now view and analyse using
the Wireshark interface, or save to disk to analyse later.
1. Packet List Panel – this is a list of packets in the current capture. It colours the packets based
on the protocol type. When a packet is selected, the details are shown in the two panels below.
26
2. Packet Details Panel – this shows the details of the selected packet. It shows the different
protocols making up the layers of data for this packet. Layers include Frame, Ethernet, IP,
TCP/UDP/ICMP, and application protocols such as HTTP.
3. Packet Bytes Panel – shows the packet bytes in Hex and ASCII encodings. To select more
detailed options when starting a capture, select the Capture->Options menu option, or Ctrl+K, or
the Capture Options button on the toolbar (the wrench).
27
Make sure the MAC name resolution is selected. Start the capture, and generate some Web
traffic
again, then stop the capture.
Wireshark automatically generates a Display Filter, and applies it to the capture. The filter is
shown in the Filter Bar, below the button toolbar. Only packets captured with a Source Port of
the value selected should be displayed. The window should be similar to that shown in Figure 6.
This same process can be performed on most fields within Wireshark, and can be used to include
or exclude traffic.
Step 4:By using this we can capture the http ,So we can find the User name and login
28
29
RESULT:
Thus the implemention of code to capture packets and examine the packets using wireshark has
done successfully.
30
EXP:NO:6
WRITE A CODE SIMULATING ARP/RARP PROTOCOL
Aim:
Algorithm:
Step 2 : In Client
Step 3: In Server
c.Server maintains the table in which IP and corresponding MAC addresses are stored.
e.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[])
{
31
try
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
Socket clsct=new Socket("127.0.0.1",5604);
DataInputStream din=new DataInputStream(clsct.getInputStream());
DataOutputStream dout=new
DataOutputStream(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
{
ServerSocket obj=new
ServerSocket(5604);
Socket obj1=obj.accept();
while(true)
{
DataInputStream din=new DataInputStream(obj1.getInputStream());
DataOutputStream dout=new
DataOutputStream(obj1.getOutputStream()); String str=din.readLine();
String ip[]={"165.165.80.80","165.165.79.1"};
String mac[]={"6A:08:AA:C2","8A:BC:E3:FA"};
for(int i=0;i<ip.length;i++)
{
32
if(str.equals(ip[i]))
{
dout.writeBytes(mac[i]+'\n');
break;
}
}
obj.close();
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
OUTPUT:
RESULT:
Thus the program in java to simulate ARP protocols has been executed and verified successfully.
33
EXP:NO:7A
STUDY OF NETWORK SIMULATOR (NS)
AIM:
INTRODUCTION :
Network Simulator (Version 2), widely known as NS2, is simply an eventdriven 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 InterNetwork Testbed (VINT) project currently
the National Science Foundation (NSF) has joined the ride in development. Last but not the least,
the group of Researchers and developers in the community are constantly working to keep NS2
strong and versatile.
BASIC ARCHITECTURE
Figure shows the basic architecture of NS2. NS2 provides users with executable command ns
which take on input argument, the name of a Tcl simulation scripting file. Users are feeding the
34
name of a Tcl simulation script (which sets up a simulation) as an input argument of an NS2
executable command ns.
In most cases, a simulation trace file is created, and is used to plot graph and/or to create
animation. NS2 consists of two key languages: C++ and Object-oriented Tool Command
Language (OTcl). While the C++ defines the internal mechanism (i.e., a backend) of the simulation
objects, the OTcl sets up simulation by assembling and configuring the objects as well as
scheduling discrete events (i.e., a frontend).
The C++ and the OTcl are linked together using TclCL. Mapped to a C++ object, variables in the
OTcl domains are sometimes referred to as handles. Conceptually, a handle (e.g., n as a Node
handle) is just a string (e.g., _o10) in the OTcl domain, and does not contain any functionality.
Instead, the functionality (e.g., receiving a packet) is defined in the mapped C++ object (e.g., of
class Connector). In the OTcl domain, a handle acts as a frontend which interacts with users and
other OTcl objects. It may define 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. NS2 provides a large number of built-in C++
objects.
It is advisable to use these C++ objects to set up a simulation using a Tcl simulation script.
However, advance users may find these objects insufficient. They need to develop their own C++
objects, and use a OTcl configuration interface to put together these objects. After simulation, NS2
outputs either text-based or animation-based simulation results. To interpret these results
graphically and interactively, tools such as NAM (Network AniMator) and XGraph are used. To
analyze a particular behavior of the network, users can extract a relevant subset of text-based data
and transform it to a more conceivable presentation.
CONCEPT OVERVIEW :
ns uses two languages because simulator has two different kinds of things it needs to do. On one
hand, detailed simulations of protocols require 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,
35
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 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.
Nodes
36
}
Link failures
Post-Processing Procedures
proc finish {}
global ns nf
$ns flush-trace
close $nf
exit 0
Schedule Events
37
Call ‘finish’
$ns run
RESULT:
38
EXP:NO:7B
SIMULATION OF CONGESTION CONTROL ALGORITHMS USING NS
Aim:
Algorithm
a. Queuetype : Droptail
d. Queue size: 10
39
c. Nam file: sliding.nam
d. Click done
Program:
# Create nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
# Create links
$ns duplex-link $n0 $n1 10Mb 10ms DropTail
$ns duplex-link $n1 $n3 10Mb 10ms DropTail
$ns duplex-link $n2 $n1 10Mb 10ms DropTail
40
$ftp attach-agent $tcp
# Start applications
$ns at 0.0 "$ftp start"
$ns at 0.0 "$cbr start"
# End simulation
$ns at 5.0 "finish"
# Run simulation
$ns run
41
OUTPUT:
RESULT:
Thus the program to perform simulation of Congestion Control Algorithms (sliding window) using
NS has been done successfully.
42
EXP:NO:8
STUDY OF TCP/UDP PERFORMANCE USING SIMULATION TOOL
Aim :
Algorithm :
2. The duplex links between n0 and n2, and n1 and n2 have 2 Mbps of bandwidth and 10
ms of delay.
3. The duplex link between n2 and n3 has 1.7 Mbps of bandwidth and 20 ms of delay.
4. Each node uses a DropTail queue, of which the maximum size is 10.
5. A "tcp" agent is attached to n0, and a connection is established to a tcp "sink" agent
attached to n3.
6. As default, the maximum size of a packet that a "tcp" agent can generate is 1KByte.
7. A tcp "sink" agent generates and sends ACK packets to the sender (tcp agent) and
10. A "ftp" and a "cbr" traffic generator are attached to "tcp" and "udp" agents
respectively, and the "cbr" is configured to generate 1 KByte packets at the rate of 1
Mbps.
11. The "cbr" is set to start at 0.1 sec and stop at 4.5 sec, and "ftp" is set to start at 1.0 sec
43
Program
44
#Setup a TCP connection
set tcp [new Agent/TCP]
$tcp set class_ 2
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink]
$ns attach-agent $n3 $sink
$ns connect $tcp $sink
$tcp set fid_ 1
#Setup a FTP over TCP connection
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ftp set type_ FTP
#Setup a UDP connection
set udp [new Agent/UDP]
$ns attach-agent $n1 $udp
set null [new Agent/Null]
$ns attach-agent $n3 $null
$ns connect $udp $null
$udp set fid_ 2
45
OUTPUT:
46
RESULT:
Thus study of the performance of TCP/UDP using Simulation Tool (NS2) has been executed
and verified successfully.
47
EXP:NO:9A
SIMULATION OF DISTANCE VECTOR ROUTING ALGORITHM
Aim:
ALGORITHM:
3. Open a nam trace file and define finish procedure then close the trace file, and execute
9. Choose distance vector routing protocol to transmit data from sender to receiver.
proc finish { } {
global ns nr nf
$ns flush-trace
48
close $nf
close $nr
exit 0
49
$ns attach-agent $n(1) $udp1
$ns rtproto DV
$ns at 45 "finish"
$ns run
50
OUTPUT:
RESULT:
Thus the program to perform Simulation of Distance Vector Routing algorithmhas been executed
and verified successfulluy.
51
EXP:NO:9B
SIMULATION OF LINK STATE ROUTING ALGORITHM
Aim:
Algorithm:
3. Open a nam trace file and define finish procedure then close the trace file, and execute
nam
on trace file.
9. Choose Link state routing protocol to transmit data from sender to receiver.
proc finish { } {
global ns nr nf
52
$ns flush-trace
close $nf
close $nr
exit 0
53
$ns connect $udp0 $null0
$ns rtproto LS
$ns at 45 "finish"
$ns run
54
OUTPUT:
RESULT:
Thus the program to perform Simulation of Link State Routing algorithm has been executed and
verified successfully.
55
EXP:NO:10
SIMULATION OF AN ERROR CORRECTION CODE (LIKE CRC)
Aim :
Algorithm :
At sender side
2. Read the number of bits to be sent. Let n be the Number of bits in data to be sent from
sender side.
3. Read the number of bits in the divisor. Let k be the Number of bits in the divisor (key
4. The binary data is first increased by adding k-1 zeros in the end of the data
5. Use modulo-2 binary division to divide binary data by the divisor and store remainder
of division.
6. Append the remainder at the end of the data to form the encoded data and send the
same
At receiver side
1. Perform modulo-2 division again and if remainder is 0, then there are no errors.
Modulo 2 division
In each step, a copy of the divisor (or data) is XORed with the k bits of the dividend.
The result of the XOR operation (remainder) is (n-1) bits, which is used for the next
When there are no bits left to pull down, we have a result. The (n-1)-bit remainder
56
Program
import java.util.Scanner;
scanner.close();
}
57
private static int checkError(String received) {
int[] r = new int[11];
for (int i = 0; i < 11; i++) r[i] = Character.getNumericValue(received.charAt(i));
return p1 * 1 + p2 * 2 + p4 * 4 + p8 * 8;
}
OUTPUT:
58
RESULT:
Thus the program in Java to implement the Simulation of Error Correction Code has been
executed and verified successfully.
59
EXP:NO:11
IMPLEMENTATIONS OF STOP AND WAIT PROTOCOL AND SLIDING WINDOW
PROTOCOL
Aim :
To write a program in Java to Implementations of Stop and Wait Protocol and Sliding Window
Protocol
Algorithm :
Program:
import java.util.Random;
class SAP {
public static void main(String[] args) {
int[] frames = {1, 2, 3, 4, 5}; // Example frames
Random rand = new Random();
60
Output :
RESULT:
Thus the program in Java to Implementations of Stop and Wait Protocol and Sliding Window
Protocol has been executed and verified successfully.
61
EXP:NO:12
WRITE A CODE SIMULATING GO BACK N ARQ.
Aim :
To write a program in Java to Write a code simulating Go Back N ARQ.
ALGORITHM:
PROGRAM:
import java.util.Random;
class SWP {
static int WINDOW_SIZE = 3;
if (ackReceived) {
System.out.println("Acknowledgment received for frames: " + printFrames(frames,
base, end));
62
base += WINDOW_SIZE;
} else {
System.out.println("ACK lost, resending from Frame " + frames[base]);
}
System.out.println("-------------------");
}
}
Output :
RESULT:
Thus the program in Java for code simulating Go Back N ARQ has been executed and verified
successfully
63