0% found this document useful (0 votes)
65 views66 pages

CS3591-CN Lab Manual

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)
65 views66 pages

CS3591-CN Lab Manual

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/ 66

Loyola INSTITUTE OF TECHNOLOGY AND SCIENCE, THOVALAI

DEPARTMENT OF ARTIFICIAL INTELLEGENCE AND DATA SCIENCE

ACADEMIC YEAR 2024-2025 (ODD SEMESTER)

LAB MANUAL
CS3591–COMPUTER NETWORKS

Nameof the Faculty:

Year/Semester: III/ V

Credit of this course: 4

CourseCategory: Theory with Laboratory

Preparedby Verifiedby ApprovedBy


Loyola Institute of Technology and Science
Loyola Nagar, Thovalai–Rajavoor Road, Thovalai Post–629 302, Kanyakumari
Dist.,

Tamilnadu. Mobile: 9244775545 / 55 / 44 / 11 Website : www.lites.edu.in

Email – [email protected],[email protected], [email protected]

Vision of the Institute Mission of the Institute


Empowering the rural and less privileged IM 1. To enlighten the rural students.
students with value based technical knowledge, IM 2. To provide quality technical education of
forming them as responsible citizens. societal development and entrepreneurship
IM 3. To instill interpersonal skills and shape
the students to become good leaders to serve
the society.

Vision of the Department Mission of the Department


To be a reputed center producing socially M1: To build Computer Engineers with
committed Computer Engineers with leadership professional ethics and entrepreneurship skills.
qualities to serve the rural society. M2: To inculcate problem solving and team
. building skills to promote lifelong learning with
the sense of social responsibilities.
M3: To produce effective Computer Engineers
with exposure to current industrial
advancements through higher education and
serve the common people through their
expertise.
Program Educational Objectives (PEOs)
1. PROFESSIONAL CAREER: The graduates will be able to pursue higher education
and research to have a successful career in Computer Science industries or as
entrepreneurs.
2. LEADERSHIP QUALITIES AND TEAM SPIRIT: The graduates will be able to
performefficiently while working in teams.
3. LIFE LONG LEARNING: The graduates will be empowered through emerging
technical
Knowledge and inspired with life-long learning to serve the society.

Program Outcomes (POs)

Engineering Graduates will be able to:

1. Engineering knowledge: Apply the knowledge of mathematics, science,


engineering fundamentals and an engineering specialization to the solution of complex
engineering problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze
complex engineering problems reaching substantiated conclusions using first principles
of mathematics, natural sciences, and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering
problems and design system components or processes that meet the specified needswith
appropriate consideration for the public health and safety, and the cultural, societal, and
environmental considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and
research methods including design of experiments, analysis and interpretation of data,
and synthesis of the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge
to assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional
engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member
or leader in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities
with the engineering community and with society at large, such as, being able to
comprehend and write effective reports and design documentation, make effective
presentations, and give and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of
the engineering and management principles and apply these to one‘s own work, as a
member and leader in a team, to manage projects and in multidisciplinary
environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability
to engage in independent and life-long learning in the broadest context of technological
change.

PROGRAM SPECIFIC OBJECTIVES (PSOs)


PSO 1: To analyze, design and develop computing solutions by applying foundational
concepts of Computer Science and Engineering.
PSO 2: To apply software engineering principles and practices for developing
quality software for scientific and business applications.
PSO 3: To adapt to emerging Information and Communication Technologies (ICT) to
innovate ideas and solutions to existing/novel problem
PRACTICAL EXERCISES

1. Learn to use commands like tcpdump, netstat, ifconfig, nslookup and traceroute. Capture ping
and trace route PDUs using a network protocol analyzer and examine.

2. Write a HTTP web client program to download a web page using TCP sockets.

3. Applications using TCP sockets like: a) Echo client and echo server b) Chat

4. Simulation of DNS using UDP sockets.

5. Use a tool like Wireshark to capture packets and examine the packets

6. Write a code simulating ARP /RARP protocols.

7. Study of Network simulator (NS) and Simulation of Congestion Control Algorithms using NS.

8. Study of TCP/UDP performance using Simulation tool.

9. Simulation of Distance Vector/ Link State Routing algorithm.

10. Simulation of an error correction code (like CRC)

COURSE OUTCOMES: At the end of this course, the students will be able to:

CO 1: Learn TCP Dump, Netstat, if config,Nslookup commands.

CO 2: Simulate applications using TCP and UDP sockets.

CO 3: Study TCP / UDP performance and network simulator

CO 4: Simulate different routing algorithms.

CO 5: Install and implement wire shark.

CO’s-PO’s&PSO’sMAPPING

PO’s PSO’s
CO’s 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3
1 3 1 2 3 - - - - 1 1 3 1 3 2 1
2 3 2 1 2 2 - - - 2 2 2 1 3 2 3
3 2 2 3 2 1 - - - 3 3 1 2 1 1 3
4 1 3 1 3 1 - - - 1 2 1 1 1 3 1
5 3 3 1 1 2 - - - 2 2 2 2 2 2 2
AVG 2 2 2 2 2 - - - 2 2 2 1 2 2 2
1-low,2-medium,3-high,‘-'-nocorrelation
LIST OF EXPERIMENTS

Sl.No. Experiment Name

Learn to use commands like tcpdump, netstat, ifconfig, nslookup and


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

Write a HTTP web client program to download a web page using TCP
2
sockets.

3 Applications using TCP sockets like Echo Client and Echo Server

4 Simulation of DNS using UDP sockets.

5a Simulation of Address Resolution Protocol (ARP) using TCP

5b Simulation of Reverse Address Resolution Protocol (RARP) using UDP

6a Study of network simulator (NS).

6b Simulation of Congestion Control Algorithms using NS.

7 Study of TCP/UDP performance using simulation tool

8 Simulation of Distance Vector/Link State Routing Algorithms

9 Simulation of Error Correction Code (CRC)

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

Implementation of encryption and decryption algorithms


(i) Ceaser cipher
11
(ii) Hill Cipher
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 start
without 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
time-consuming 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
address connected. 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
host-list] | [-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 ns-2, 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, pointto-
point 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)


# stop and wait protocol in normal situation
# features : labeling, annotation, nam-graph, and window size monitoring
set ns [new Simulator]
set n0 [$ns node]
set n1 [$ns node]
$ns at 0.0 "$n0 label Sender"
$ns at 0.0 "$n1 label Receiver"
set nf [open stop.nam w]
$ns namtrace-all $nf
set f [open stop.tr w]
$ns trace-all $f
$ns duplex-link $n0 $n1 0.2Mb 200ms DropTail
$ns duplex-link-op $n0 $n1 orient right
$ns queue-limit $n0 $n1 10
Agent/TCP set nam_tracevar_ true
set tcp [new Agent/TCP]
$tcp set window_ 1
$tcp set maxcwnd_ 1
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink]
$ns attach-agent $n1 $sink
$ns connect $tcp $sink
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ns add-agent-trace $tcp tcp
$ns monitor-agent-trace $tcp
$tcp tracevar cwnd_
$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"
$ns at 0.0 "$ns trace-annotate \"Stop and Wait with normal operation\""
$ns at 0.05 "$ns trace-annotate \"FTP starts at 0.1\""
$ns at 0.11 "$ns trace-annotate \"Send Packet_0\""
$ns at 0.35 "$ns trace-annotate \"Receive Ack_0\""
$ns at 0.56 "$ns trace-annotate \"Send Packet_1\""
$ns at 0.79 "$ns trace-annotate \"Receive Ack_1\""

$ns at 0.99 "$ns trace-annotate \"Send Packet_2\""


$ns at 1.23 "$ns trace-annotate \"Receive Ack_2 \""
$ns at 1.43 "$ns trace-annotate \"Send Packet_3\""
$ns at 1.67 "$ns trace-annotate \"Receive Ack_3\""
$ns at 1.88 "$ns trace-annotate \"Send Packet_4\""
$ns at 2.11 "$ns trace-annotate \"Receive Ack_4\""
$ns at 2.32 "$ns trace-annotate \"Send Packet_5\""
$ns at 2.55 "$ns trace-annotate \"Receive Ack_5 \""
$ns at 2.75 "$ns trace-annotate \"Send Packet_6\""
$ns at 2.99 "$ns trace-annotate \"Receive Ack_6\""
$ns at 3.1 "$ns trace-annotate \"FTP stops\""
proc finish {} {
global ns nf
$ns flush-trace
close $nf
puts "running nam..."
exec nam stop.nam &
exit 0
}
$ns run
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)

# sliding window mechanism with some features


# such as labeling, annotation, nam-graph, and window size monitoring
set ns [new Simulator]
set n0 [$ns node]
set n1 [$ns node]
$ns at 0.0 "$n0 label Sender"
$ns at 0.0 "$n1 label Receiver"
set nf [open sliding.nam w]
$ns namtrace-all $nf
set f [open sliding.tr w]
$ns trace-all $f
$ns duplex-link $n0 $n1 0.2Mb 200ms DropTail
$ns duplex-link-op $n0 $n1 orient right
$ns queue-limit $n0 $n1 10
Agent/TCP set nam_tracevar_ true
set tcp [new Agent/TCP]
$tcp set windowInit_ 4
$tcp set maxcwnd_ 4

$ns attach-agent $n0 $tcp

set sink [new Agent/TCPSink]


$ns attach-agent $n1 $sink
$ns connect $tcp $sink
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ns add-agent-trace $tcp tcp
$ns monitor-agent-trace $tcp
$tcp tracevar cwnd_
$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"
$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\""
proc finish {} {
global ns
$ns flush-trace
# close $nf
puts "running nam..."
exec nam sliding.nam &
exit 0
}
$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:

setns[newSimulator]

$nscolor0Blue

$nscolor1Red

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

setf[opentcpout.trw]

$nstrace-all$f

setnf[opentcpout.namw]

$nsnamtrace-all$nf

$nsduplex-link$n0$n25Mb2msDropTail

$nsduplex-link$n1$n25Mb2msDropTail

$nsduplex-link$n2$n31.5Mb10msDropTail
$nsduplex-link-op$n0$n2orientright-up

$nsduplex-link-op$n1$n2orientright-down

$nsduplex-link-op$n2$n3orientright

$nsduplex-link-op$n2$n3queuePos0.5 set tcp [new Agent/TCP]

$tcpsetclass_1

setsink[newAgent/TCPSink]

$nsattach-agent$n1$tcp

$nsattach-agent$n3$sink

Output:
$nsconnect$tcp$sink

setftp[newApplication/FTP]

$ftpattach-agent$tcp

$nsat1.2"$ftpstart"

$nsat1.35"$nsdetach-agent$n1$tcp;$ns detach-agent$n3$sink"

$nsat3.0"finish" proc finish {} {

globalnsfnf

$nsflush-trace close $f

close$nf

puts"Runningnam.."

execxgraphtcpout.tr-geometry600x800& exec namtcpout.nam&

exit0

$ns run

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:
setns[newSimulator]

$nscolor0Blue

$nscolor1Red

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

setf[openudpout.trw]

$nstrace-all$f

setnf[openudpout.namw]

$nsnamtrace-all$nf

$nsduplex-link$n0$n25Mb2msDropTail

Output:

$nsduplex-link$n1$n25Mb2msDropTail

$nsduplex-link$n2$n31.5Mb10msDropTail

$nsduplex-link-op$n0$n2orientright-up

$nsduplex-link-op$n1$n2orientright-down

$nsduplex-link-op$n2$n3orientright
$nsduplex-link-op$n2$n3queuePos0.5 set udp0 [new Agent/UDP]

$nsattach-agent$n0$udp0

setcbr0[newApplication/Traffic/CBR]

$cbr0 attach-agent $udp0 setudp1[new Agent/UDP]

$nsattach-agent$n3$udp1

udp1setclass_0

setcbr1[newApplication/Traffic/CBR]

$cbr1 attach-agent $udp1 setnull0[newAgent/Null]

$nsattach-agent$n1$null0 set null1 [new Agent/Null]

$nsattach-agent$n1$null1

$nsconnect$udp0$null0

$nsconnect$udp1$null1

$nsat1.0"$cbr0start"

$nsat1.1"$cbr1start"

puts[$cbr0setpacketSize_] puts [$cbr0 set interval_]

$nsat3.0"finish" proc finish {} {

globalnsfnf

$nsflush-trace close $f

close$nf

puts "Running nam.." execnamudpout.nam& exit 0

$ns run

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:

setns[newSimulator]

$nsrtprotoLS

setnf[openlinkstate.namw]

$nsnamtrace-all$nf

setf0[openlinkstate.trw]

$nstrace-all$f0 proc finish {} {

globalnsf0nf

$nsflush-trace close $f0

close$nf
execnamlinkstate.nam& exit 0

for{seti0}{$i<7}{incri}{ set n($i) [$ns node]

for{seti0}{$i<7}{incri}{

$nsduplex-link$n($i)$n([expr($i+1)%7])1Mb10msDropTail

setudp0[new Agent/UDP]

$nsattach-agent$n(0)$udp0

setcbr0[newApplication/Traffic/CBR]

$cbr0setpacketSize_500

$cbr0setinterval_0.005

$cbr0 attach-agent $udp0 setnull0[newAgent/Null]

$nsattach-agent$n(3)$null0

$nsconnect$udp0$null0

$nsat0.5"$cbr0start"

$nsrtmodel-at1.0down$n(1)$n(2)

$nsrtmodel-at2.0up$n(1)$n(2)

$nsat4.5"$cbr0stop"

$nsat5.0"finish"

$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:

#Distancevectorroutingprotocol–distvect.tcl #Create a simulator object


set ns[newSimulator]
#Usedistancevector routing
$nsrtprotoDV
#Openthenamtracefile set nf [open out.nam w]
$nsnamtrace-all$nf # Open tracefile
setnt[opentrace.trw]
$nstrace-all$nt
#Define'finish'procedure
procfinish{}
{

Output:
$ nsdistvect.tcl
globalnsnf

$ns flush-trace #Closethetracefile close $nf


#Executenamonthetracefile exec nam -a out.nam&
exit0
}

# Create8 nodes setn1[$nsnode] setn2[$nsnode] setn3[$nsnode] setn4[$nsnode] setn5[$nsnode]


setn6[$nsnode] setn7[$nsnode] setn8[$ns node]
#Specifylinkcharacterestics
$nsduplex-link$n1$n21Mb10msDropTail
$nsduplex-link$n2$n31Mb10msDropTail
$nsduplex-link$n3$n41Mb10msDropTail
$nsduplex-link$n4$n51Mb10msDropTail
$nsduplex-link$n5$n61Mb10msDropTail
$nsduplex-link$n6$n71Mb10msDropTail
$nsduplex-link$n7$n81Mb10msDropTail
$nsduplex-link$n8$n11Mb10msDropTail # specify layout as a octagon
$nsduplex-link-op$n1$n2orientleft-up
$nsduplex-link-op$n2$n3orientup
$nsduplex-link-op$n3$n4orientright-up
$nsduplex-link-op$n4$n5orientright
$nsduplex-link-op$n5$n6orientright-down
$nsduplex-link-op$n6$n7orientdown
$nsduplex-link-op$n7$n8orientleft-down
$ns duplex-link-op $n8 $n1 orient left #CreateaUDPagent andattachit tonoden1 set udp0 [new
Agent/UDP]
$nsattach-agent$n1 $udp0
#CreateaCBRtrafficsourceandattachittoudp0
setcbr0[newApplication/Traffic/CBR]
$cbr0setpacketSize_ 500
$cbr0set interval_0.005
$cbr0attach-agent$udp0
#CreateaNullagent (atrafficsink)andattachittonoden4 set null0 [new Agent/Null]
$nsattach-agent$n4 $null0
#Connectthetrafficsourcewiththetrafficsink
$nsconnect$udp0$null0
#ScheduleeventsfortheCBRagentandthenetwork dynamics
$nsat0.0 "$n1labelSource"
$nsat0.0"$n4labelDestination"
$nsat0.5"$cbr0start"
$nsrtmodel-at1.0down$n3$n4
$nsrtmodel-at2.0up$n3 $n4

$nsat4.5"$cbr0stop"
#Callthefinishprocedureafter 5 secondsofsimulationtime
$ns at 5.0 "finish" #Runthesimulation
$nsrun

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.
EX NO : 11 i) Implementation of encryption and decryption algorithms- Caesar Cipher
AIM :Write a C program for Caesar Cipher.
ALGORITHM :
1. Enter the plaintext to be encrypted and enter the key value.
2. Function encrypt ( ) will be invoked for encryption.
a) Take the ascii value of each plain text char and add it with the value of key % 26
b) Take the equivalent char value for the resultant value of sub-step(a)
c) Return the cipher text.
3. Function decrypt ( ) will be invoked for decryption.
a) Take the ascii value of each cipher text char and subtract the value of key % 26
from it
b) Take the equivalent char value for the resultant value of sub-step(a)
c) Return the plain text.
#include <stdio.h>
#include <ctype.h>
#define MAXSIZE 1024
void encrypt(char*);
void decrypt(char*);
int menu();
int main(void)
{
char c,
choice[2],
s[MAXSIZE];
while(1)
{
menu();
gets(choice);
if((choice[0]=='e')||(choice[0]=='E'))
{
puts("Input text to encrypt->");
gets(s);
encrypt(s);
}
else if((choice[0]=='d')||(choice[0]=='D'))
{
puts("Input text to decrypt->");
gets(s);
decrypt(s);
}
else
break;
}
return 0;
}
void encrypt(char*str)
{
int n=0;
char *p=str,
q[MAXSIZE];
while(*p)
{
if(islower(*p))
{
if((*p>='a')&&(*p<'x'))
q[n]=toupper(*p + (char)3);
else if(*p=='x')
q[n]='A';
else if(*p=='y')
q[n]='B';
else
q[n]='C';
}
else
{
q[n]=*p;
}
n++; p++;
}
q[n++]='\0';
puts(q);
}
void decrypt(char*str)
{
int n=0;
char *p=str,
q[MAXSIZE];
while(*p)
{
if(isupper(*p))
{
if((*p>='D')&&(*p<='Z'))
q[n]=tolower(*p - (char)3);
else if(*p=='A')
q[n]='x';
else if(*p=='B')
q[n]='y';
else
q[n]='z';
}
else
{
q[n]=*p;
}
n++; p++;
}
q[n++]='\0';
puts(q);
}
int menu()
{
puts("To encrypt, input e or E\n");
puts("To decrypt, input d or D\n");
puts("To exit, input any other letter\n");
puts("Your choice:->\n");
return 0;
}

Output:
Encrypt -----e or E
Decrypt------d or D
To exit :any other letter
Choice:e
Enter the text
Hello
KHOOR
Choice:a
Exit

Result:Thus ceasar cipher was executed successfully.


EX NO : 11 ii) Implementation of encryption and decryption algorithmms- Hill Cipher

AIM :Towrite a C program toimplement Hill Cipher Technique.


ALGORITHM :
1. Enter the plain text.
2, Enter the matrix, named key matrix for encryption. The elements of the matrix will be
randomly chosen and of modulo 26.
3. Plain text characters are multiplied by the encryption matrix.
4. Display the cipher text.
5. Find the inverse of the key matrix.
6. For decryption, multiply the characters of cipher text by key matrix to get plaintext and
display it.
Program:
#include<stdio.h>
#include<math.h>
float encrypt[3][1], decrypt[3][1], a[3][3], b[3][3], mes[3][1], c[3][3];
void encryption(); //encrypts the message
void decryption(); //decrypts the message
void getKeyMessage(); //gets key and message from user
void inverse(); //finds inverse of key matrix
void main() {
getKeyMessage();
encryption();
decryption();
}
void encryption() {
int i, j, k;
for(i = 0; i < 3; i++)
for(j = 0; j < 1; j++)
for(k = 0; k < 3; k++)
encrypt[i][j] = encrypt[i][j] + a[i][k] * mes[k][j];
printf("\nEncrypted string is: ");
for(i = 0; i < 3; i++)
printf("%c", (char)(fmod(encrypt[i][0], 26) + 97));
}
void decryption() {
int i, j, k;
inverse();
for(i = 0; i < 3; i++)
for(j = 0; j < 1; j++)
for(k = 0; k < 3; k++)
decrypt[i][j] = decrypt[i][j] + b[i][k] * encrypt[k][j];
printf("\nDecrypted string is: ");
for(i = 0; i < 3; i++)
printf("%c", (char)(fmod(decrypt[i][0], 26) + 97));
printf("\n");
}
void getKeyMessage() {
int i, j;
char msg[3];
printf("Enter 3x3 matrix for key (It should be inversible):\n");
for(i = 0; i < 3; i++)
for(j = 0; j < 3; j++) {
scanf("%f", &a[i][j]);
c[i][j] = a[i][j];
}
printf("\nEnter a 3 letter string: ");
scanf("%s", msg);

for(i = 0; i < 3; i++)


mes[i][0] = msg[i] - 97;
}
void inverse() {
int i, j, k;
float p, q;
for(i = 0; i < 3; i++)
for(j = 0; j < 3; j++) {
if(i == j)
b[i][j]=1;
else
b[i][j]=0;
}
for(k = 0; k < 3; k++) {
for(i = 0; i < 3; i++) {
p = c[i][k];
q = c[k][k];
for(j = 0; j < 3; j++) {
if(i != k) {
c[i][j] = c[i][j]*q - p*c[k][j];
b[i][j] = b[i][j]*q - p*b[k][j];
}
}
}
}
for(i = 0; i < 3; i++)
for(j = 0; j < 3; j++)
b[i][j] = b[i][j] / c[i][i];
printf("\n\nInverse Matrix is:\n");
for(i = 0; i < 3; i++) {
for(j = 0; j < 3; j++)
printf("%d ", b[i][j]);
printf("\n");
}
}

OUTPUT

Result: Thus hill cipher was executed successfully.

You might also like