You are on page 1of 56

IMS ENGINEERING COLLEGE

COMPUTER NETWORKS LAB


(KCS-653)

B.TECH – III YEAR


(EVEN SEM 2022-2023)

Name

Roll No.

Section-Batch

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

IMS ENGINEERING COLLEGE


(Affiliated to Dr A P J Abdul Kalam Technical University, Lucknow)
Approved by AICTE - Accredited by NAAC – ‘A’ Grade
NH-24, Adhyatmik Nagar, Ghaziabad, UP, India
www.imsec.ac.in
VISION OF THE INSTITUTE

To make IMSEC an Institution of Excellence for empowering students through technical


education coupled with incorporating values and developing engineering acumen for
innovations and leadership skills for the betterment of society.

MISSION OF THE INSTITUTE

 To promote academic excellence by continuous learning in core and emerging


Engineering areas using innovative teaching and learning methodologies.

 To inculcate values and ethics among the learners.

 To promote industry interactions and produce young entrepreneurs.

 To create a conducive learning and research environment for life-long learning to


develop the students as technology leaders and entrepreneurs for addressing societal
needs.

VISION OF THE DEPARTMENT


To provide globally competent professionals in the field of Computer Science & Engineering
embedded with sound technical knowledge, aptitude for research and innovation with ethical
values to cater to the industrial & societal needs.

MISSION OF THE DEPARTMENT

M1: To provide quality undergraduate education in both the theoretical & applied
foundations of Computer Science Engineering.

M2: Conduct research to advance the state of the art in Computer Science & Engineering
and integrate the research results as innovations.

M3: To inculcate team building skills and promote life-long learning with a high societal
and ethical values.

2
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

PROGRAMME EDUCATIONAL OBJECTIVES (PEOs)

Graduate Will:

PEO1: Possess knowledge to enable continued professional development.

PEO2: Engage in life-long learning to foster personal & organization


growth.

PEO3: Work productively as successful professionals in diverse career


paths.

PEO4: Effectively communicate ideas to promote collaboration in accordance with societal


standards & ethical practices.

PROGRAMME SPECIFIC OUTCOME (PSOs)

PSO1: To apply standard software engineering practices & strategies in real-time software
project development.

PSO2: To apply latest programming languages in creating innovative career opportunitie

3
Department of Computer Science and Engineering

Course Name: Computer Network Lab Course Code: KCS-653


Semester / Year: 6th /3rd NBA Code: C 321

Bloom’s
COURSE OUTCOMES
Level
CO321.1 Simulate different network topologies. K3,K4
CO321.2 Implement various framing methods of Datalink Layer. K3,K4
CO321.3 Implement various Error and flow control techniques. K3,K4
CO321.4 Implement network routing and addressing techniques. K3,K4
CO321.5 Implement transport and security mechanisms. K3,K4

CO-PO Matrix

Course
PO 1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2
Outcome

CO321.1 3 3 3 3 3 1 1 2 3 3 1 3 1 1

CO321.2 3 3 3 2 3 1 1 2 3 3 1 3 1 1

CO321.3 3 3 3 3 3 1 1 2 3 3 1 3 1 1

CO321.4 3 3 3 3 3 1 1 2 3 3 1 3 1 1

CO321.5 3 3 3 3 3 1 1 2 3 3 1 3 1 1

C321 3.0 3.0 3.0 2.8 3.0 1.0 1.0 2.0 3.0 3.0 1.0 3.0 1.0 1.0

4
DETAILS OF THE EXPERIMENTS CONDUCTED

S.No TITLE OF THE EXPERIMENT DATE OF FACULTY


SUBMISSION SIGNATURE

1 To learn handling and configuration of networking hardware like


RJ-45 connector, CAT-6cable, crimping tool, etc.

2 Configuration of router, hub, switch etc. (using real devices or


simulators)

3 Running and using services/commands like ping, traceroute, ns


lookup, Arp, telnet, ftp, etc.

4 Network packet analysis and simulation using tools like


Wireshark, tcpdump, Cisco Packet Tracker, NetSim, OMNeT++,
NS2,NS3,etc.
5 Write a code simulating Ping and Trace-route commands

6 Implement Subnetting to generate Range of IP Addresses.

7 Implement Cyclic Redundancy Check at Sender and Receiver Site

8 Implement Hamming Code at Sender and Receiver Site.

9 Implement RSA Algorithm.

10 Implement Diffie Hellman Algorithm.

11 Implementation of Stop and Wait Protocol and Sliding Window


Protocol

12 To perform case study for different routing algorithms to select


the network path using LINK STATE ROUTING b) FLOODING
c) DISTANCE VECTOR.

5
EXPERIMENT NO. - 1

AIM: To learn handling and configuration of networking hardware like


RJ-45 connector, CAT-6cable, crimping tool, etc.

1. Strip the cable back 1 inch (25 mm) from the end. Insert the cable into the stripper
section of the tool and squeeze it tight. Then, rotate the crimping tool around the cable in a
smooth and even motion to create a clean cut. Keep the tool clamped and pull away towards the
end of the wire to remove the sheathing.
 The stripping section is a round hole near the handle of the tool.
 The sheathing should come off cleanly, leaving the wires exposed.

2. Untwist and straighten the wires inside of the cable. Inside of the cable you’ll see a
bunch of smaller wires twisted together. Separate the twisted wires and straighten them out so
they’re easier to sort into the right order.
 Cut off the small plastic wire separator or core so it’s out of the way.
 Don’t cut off or remove any of the wires or you won’t be able to crimp them into the
connector.
3. Arrange the wires into the right order. Use your fingers to put the wires in the correct
order so they can be properly crimped. The proper sequence is as follows from left to right:
Orange/White, Orange, Green/White, Blue, Blue/White, Green, Brown/White, Brown.
 There are 8 wires in total that need to be arranged in the right sequence.
 Note that the wires labeled Orange/White or Brown/White indicate the small wires that
have 2 colors.
4. Cut the wires into an even line 1⁄2 inch (13 mm) from sheathing. Hold the
wires with your thumb and index finger to keep them in order. Then, use the cutting section of the
crimping tool to cut them into an even line.
 The cutting section of the tool will resemble wire cutters.
 The wires must be in an even line to be crimped into the RJ-45 connector properly. If you
cut them in an uneven line, move further down the wires and cut them again.

6
5. Insert the wires into the RJ-45 connector. Hold the RJ-45 connector so the clip is on
the underside and the small metal pins are facing up. Insert the cable into the connector so that each
of the small wires fits into the small grooves in the connector.
 The sheathing of the cable should fit just inside of the connector so it’s past the base.
 If any of the small wires bend or don’t fit into a groove correctly, take the cable out and
straighten the wires with your fingers before trying again.
 The wires must be inserted in the correct order and each wire must fit into a groove before you
crimp the connector.
6. Stick the connector into the crimping part of the tool and squeeze twice. Insert
the connector in the crimping section of the tool until it can’t fit any further. Squeeze the handles to
crimp the connector and secure the wires. Release the handles, then squeeze the tool again to make
sure all of the pins are pushed down.
 The crimping tool pushes small pins in the grooves down onto the wires to hold and connect
them to the RJ-45 connector.

7. Remove the cable from the tool and check that all of the pins are down. Take
the connector out of the tool and look at the pins to see that they’re all pushed down inan even line.
Lightly tug at the connector to make sure it’s attached to the cable.
 If any of the pins aren’t pushed down, put the wire back into the crimping tool and crimp it
again.

7
EXPERIMENT NO. - 2

AIM: Configuration of router, hub, switch etc. (using real devices or simulators)

1. HUB: An Ethernet hub, active hub, network hub, repeater hub, hub or concentrator is a
device for connecting multiple twisted pair or fiber optic Ethernet devices together and
making them act as a single network segment. Hubs work at the physical layer (layer 1) of the
OSI model. The device is a form of multiport repeater. Repeater hubs also participate in
collision detection, forwarding a jam signal to all ports if it detects a collision.

2. BRIDGE: A network bridge connects multiple network segments at the data link layer
(Layer 2) of the OSI model. In Ethernet networks, the term bridge formally means a device that
behaves according to the IEEE 802.1D standard. A bridge and switch are very much alike; a
switch being a bridge with numerous ports. Switch or Layer 2 switch is often used
interchangeably with bridge. Bridges can analyze incoming data packets to determine if the
bridge is able to send the given packet to another segment of the network.

3. SWITCH: A network switch or switching hub is a computer networking device that


connects network segments. The term commonly refers to a network bridge that processes and
routes data at the data link layer (layer 2) of the OSI model. Switches that additionally process
data at the network layer (layer 3 and above) are often referred to as Layer 3 switches or
multilayer switches.

8
4. ROUTER: A router is an electronic device that interconnects two or more computer
networks, and selectively interchanges packets of data between them. Each data packet
contains address information that a router can use to determine if the source and destination are
on the same network, or if the data packet must be transferred from one network to another.
Where multiple routers are used in a large collection of interconnected networks, the routers
exchange information about target system addresses, so that each router can build up a table
showing the preferred paths between any two systems on the interconnected networks.

Network Topology

Physical topology is the geometric representation of all the nodes in a network. There are six types
of network topology which are Bus Topology, Ring Topology, Tree Topology, Star Topology, Mesh
Topology, and Hybrid Topology.

1) Bus Topology

9
o The bus topology is designed in such a way that all the stations are connected through a single
cable known as a backbone cable.
o Each node is either connected to the backbone cable by drop cable or directly connected to the
backbone cable.
o When a node wants to send a message over the network, it puts a message over the network.
All the stations available in the network will receive the message whether it has been
addressed or not.
o The bus topology is mainly used in 802.3 (ethernet) and 802.4 standard networks.
o The configuration of a bus topology is quite simpler as compared to other topologies.
o The backbone cable is considered as a "single lane" through which the message is broadcast
to all the stations.
o The most common access method of the bus topologies is CSMA (Carrier Sense Multiple
Access).

CSMA: It is a media access control used to control the data flow so that data integrity is
maintained, i.e., the packets do not get lost. There are two alternative ways of handling the
problems that occur when two nodes send the messages simultaneously.

o CSMA CD: CSMA CD (Collision detection) is an access method used to detect the collision.
Once the collision is detected, the sender will stop transmitting the data. Therefore, it works on
"recovery after the collision".
o CSMA CA: CSMA CA (Collision Avoidance) is an access method used to avoid the collision
by checking whether the transmission media is busy or not. If busy, then the sender waits until
the media becomes idle. This technique effectively reduces the possibility of the collision. It
does not work on "recovery after the collision".

Advantages of Bus topology:


o Low-cost cable: In bus topology, nodes are directly connected to the cable without passing
through a hub. Therefore, the initial cost of installation is low.
o Moderate data speeds: Coaxial or twisted pair cables are mainly used in bus-based networks
that support upto 10 Mbps.
o Familiar technology: Bus topology is a familiar technology as the installation and
troubleshooting techniques are well known, and hardware components are easily available.

10
o Limited failure: A failure in one node will not have any effect on other nodes.

Disadvantages of Bus topology:


o Extensive cabling: A bus topology is quite simpler, but still it requires a lot of cabling.
o Difficult troubleshooting: It requires specialized test equipment to determine the cable faults.
If any fault occurs in the cable, then it would disrupt the communication for all the nodes.
o Signal interference: If two nodes send the messages simultaneously, then the signals of both
the nodes collide with each other.
o Reconfiguration difficult: Adding new devices to the network would slow down the network.
o Attenuation: Attenuation is a loss of signal leads to communication issues. Repeaters are
used to regenerate the signal.

2) Ring Topology

o Ring topology is like a bus topology, but with connected ends.


o The node that receives the message from the previous computer will retransmit to the next
node.
o The data flows in one direction, i.e., it is unidirectional.
o The data flows in a single loop continuously known as an endless loop.
o It has no terminated ends, i.e., each node is connected to other node and having no termination
point.
o The data in a ring topology flow in a clockwise direction.
o The most common access method of the ring topology is token passing.
o Token passing: It is a network access method in which token is passed from one node
to another node.
o Token: It is a frame that circulates around the network.

Working of Token passing


o A token moves around the network, and it is passed from computer to computer until it reaches
the destination.
o The sender modifies the token by putting the address along with the data.

11
o The data is passed from one device to another device until the destination address matches.
Once the token received by the destination device, then it sends the acknowledgment to the
sender.
o In a ring topology, a token is used as a carrier.

Advantages of Ring topology:


o Network Management: Faulty devices can be removed from the network without bringing the
network down.
o Product availability: Many hardware and software tools for network operation and monitoring
are available.
o Cost: Twisted pair cabling is inexpensive and easily available. Therefore, the installation cost is
very low.
o Reliable: It is a more reliable network because the communication system is not dependent on
the single host computer.

Disadvantages of Ring topology:


o Difficult troubleshooting: It requires specialized test equipment to determine the cable faults.
If any fault occurs in the cable, then it would disrupt the communication for all the nodes.
o Failure: he breakdown in one station leads to the failure of the overall network.
o Reconfiguration difficult: Adding new devices to the network would slow down the network.
o Delay: Communication delay is directly proportional to the number of nodes. Adding new
devices increases the communication delay.

3) Star Topology

o Star topology is an arrangement of the network in which every node is connected to the central
hub, switch or a central computer.
o The central computer is known as a server, and the peripheral devices attached to the server
are known as clients.
o Coaxial cable or RJ-45 cables are used to connect the computers.
o Hubs or Switches are mainly used as connection devices in a physical star topology.
o Star topology is the most popular topology in network implementation.

12
Advantages of Star topology
o Efficient troubleshooting: Troubleshooting is quite efficient in a star topology as compared to
bus topology. In a bus topology, the manager has to inspect the kilometers of cable. In a star
topology, all the stations are connected to the centralized network. Therefore, the network
administrator has to go to the single station to troubleshoot the problem.
o Network control: Complex network control features can be easily implemented in the star
topology. Any changes made in the star topology are automatically accommodated.
o Limited failure: As each station is connected to the central hub with its own cable, therefore
failure in one cable will not affect the entire network.
o Familiar technology: Star topology is a familiar technology as its tools are cost-effective.
o Easily expandable: It is easily expandable as new stations can be added to the open ports on
the hub.
o Cost effective: Star topology networks are cost-effective as it uses inexpensive coaxial cable.
o High data speeds: It supports a bandwidth of approx 100Mbps. Ethernet 100BaseT is one of
the most popular Star topology networks.

Disadvantages of Star topology


o A Central point of failure: If the central hub or switch goes down, then all the connected
nodes will not be able to communicate with each other.
o Cable: Sometimes cable routing becomes difficult when a significant amount of routing is
required.

4) Tree topology

o Tree topology combines the characteristics of bus topology and star topology.
o A tree topology is a type of structure in which all the computers are connected with each other
in hierarchical fashion.
o The top-most node in tree topology is known as a root node, and all other nodes are the
descendants of the root node.
o There is only one path exists between two nodes for the data transmission. Thus, it forms a
parent-child hierarchy.

13
Advantages of Tree topology
o Support for broadband transmission: Tree topology is mainly used to provide broadband
transmission, i.e., signals are sent over long distances without being attenuated.
o Easily expandable: We can add the new device to the existing network. Therefore, we can say
that tree topology is easily expandable.
o Easily manageable: In tree topology, the whole network is divided into segments known as
star networks which can be easily managed and maintained.
o Error detection: Error detection and error correction are very easy in a tree topology.
o Limited failure: The breakdown in one station does not affect the entire network.
o Point-to-point wiring: It has point-to-point wiring for individual segments.

Disadvantages of Tree topology


o Difficult troubleshooting: If any fault occurs in the node, then it becomes difficult to
troubleshoot the problem.
o High cost: Devices required for broadband transmission are very costly.
o Failure: A tree topology mainly relies on main bus cable and failure in main bus cable will
damage the overall network.
o Reconfiguration difficult: If new devices are added, then it becomes difficult to reconfigure.

5) Mesh topology

o Mesh technology is an arrangement of the network in which computers are interconnected with
each other through various redundant connections.
o There are multiple paths from one computer to another computer.
o It does not contain the switch, hub or any central computer which acts as a central point of
communication.
o The Internet is an example of the mesh topology.

14
o Mesh topology is mainly used for WAN implementations where communication failures are a
critical concern.
o Mesh topology is mainly used for wireless networks.
o Mesh topology can be formed by using the formula:
Number of cables = (n*(n-1))/2;

Where n is the number of nodes that represents the network.

Mesh topology is divided into two categories:

o Fully connected mesh topology


o Partially connected mesh topology

o Full Mesh Topology: In a full mesh topology, each computer is connected to all the computers
available in the network.
o Partial Mesh Topology: In a partial mesh topology, not all but certain computers are
connected to those computers with which they communicate frequently.

Advantages of Mesh topology:

Reliable: The mesh topology networks are very reliable as if any link breakdown will not affect
the communication between connected computers.

Fast Communication: Communication is very fast between the nodes.

Easier Reconfiguration: Adding new devices would not disrupt the communication between
other devices.

Disadvantages of Mesh topology


o Cost: A mesh topology contains a large number of connected devices such as a router and
more transmission media than other topologies.
o Management: Mesh topology networks are very large and very difficult to maintain and
manage. If the network is not monitored carefully, then the communication link failure goes
undetected.
o Efficiency: In this topology, redundant connections are high that reduces the efficiency of the
network.

15
6) Hybrid Topology

o The combination of various different topologies is known as Hybrid topology.


o A Hybrid topology is a connection between different links and nodes to transfer the data.
o When two or more different topologies are combined together is termed as Hybrid topology and
if similar topologies are connected with each other will not result in Hybrid topology. For
example, if there exist a ring topology in one branch of ICICI bank and bus topology in another
branch of ICICI bank, connecting these two topologies will result in Hybrid topology.

Advantages of Hybrid Topology


o Reliable: If a fault occurs in any part of the network will not affect the functioning of the rest of
the network.
o Scalable: Size of the network can be easily expanded by adding new devices without affecting
the functionality of the existing network.
o Flexible: This topology is very flexible as it can be designed according to the requirements of
the organization.
o Effective: Hybrid topology is very effective as it can be designed in such a way that the
strength of the network is maximized and weakness of the network is minimized.

Disadvantages of Hybrid topology


o Complex design: The major drawback of the Hybrid topology is the design of the Hybrid
network. It is very difficult to design the architecture of the Hybrid network.
o Costly Hub: The Hubs used in the Hybrid topology are very expensive as these hubs are
different from usual Hubs used in other topologies.
o Costly infrastructure: The infrastructure cost is very high as a hybrid network requires a lot of
cabling, network devices, etc.

16
EXPERIMENT NO - 3

AIM: Running and using services/commands like ping, traceroute, nslookup,


arp, telnet, ftp, etc.

1. PING : Ping is used to testing a network host capacity to interact with another host. Just
enter the command Ping, followed by the target host’s name or IP address. The ping utilities
seem to be the most common network tool. This is performed by using the Internet Control
Message Protocol, which allows the echo packet to be sent to the destination host and a
listening mechanism. If the destination host reply to the requesting host, that means the host is
reachable. This utility usually gives a basic image of where there may be a specific networking
issue.

2. TRACE ROUTE : 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. The traceroute command is used to determine the path between two
connections. Often a connection to another device will have to go through multiple routers. The
traceroute command will return the names or IP addresses of all the routers between two
devices.

3. NS LOOKUP : The Nslookup, which stands for name server lookup command, is a
network utility command used to obtain information about internet servers. It provides name
server information for the DNS (Domain Name System), i.e. the default DNS server’s name

17
and IP Address. The nslookup command queries internet domain name servers in two modes.
Interactive mode allows you to query name servers for information about various hosts and
domains, or to print a list of the hosts in a domain. In noninteractive mode, the names and
requested information are printed for a specified host or domain.

4. ARP : ARP stands for Address Resolution Protocol. Although network communications can
readily be thought of as an IP address, the packet delivery depends ultimately on the media
access control (MAC). This is where the protocol for address resolution comes into effect. You
can add the remote host IP address, which is an arp -a command, in case you have issues to
communicate with a given host. The ARP command provides information like Address, Flags,
Mask, IFace, Hardware Type, Hardware Address, etc.

5. TELNET : TELNET is commonly used by terminal emulation programs that allow you to
log into a remote host. However, TELNET can also be used for terminal-to-terminal
communication and interprocess communication. TELNET is also used by other protocols (for
example, FTP) for establishing a protocol control channel. Telnet provides users with a
bidirectional interactive text-oriented communication system utilizing a virtual terminal
connection over 8 byte. User data is interspersed in-band with telnet control information over
the transmission control protocol (TCP).

6. FTP : The ftp command uses the File Transfer Protocol (FTP) to transfer files between the
local host and a remote host or between two remote hosts. Remote execution of the ftp
command is not recommended. The FTP protocol allows data transfer between hosts that use
dissimilar file systems.

18
EXPERIMENT NO - 4

AIM: Running and using services/commands like ping, traceroute, ns lookup, Arp,
telnet, ftp, etc. Network packet analysis and simulation using tools like Wireshark,
tcpdump, Cisco Packet Tracer, NetSim, OMNeT++, NS2, NS3, etc.

1. WIRESHARK : Wireshark is a free and open-source packet analyzer. Wireshark


development project, started by Gerald Combs in 1998, is today’s world’s foremost and
widely-used network protocol analyzer. It is used for network troubleshooting, interpretation,
review, protocol development, and education. Wireshark will also help you see what’s
happening on your network at a microscopic level.

2. TCPDUMP : Tcpdump is a command line utility that allows you to capture and analyze
network traffic going through your system. It is often used to help troubleshoot network issues,
as well as a security tool.A powerful and versatile tool that includes many options and filters,
tcpdump can be used in a variety of cases. Since it's a command line tool, it is ideal to run in
remote servers or devices for which a GUI is not available, to collect data that can be analyzed
later. It can also be launched in the background or as a scheduled job using tools like cron.

19
3. Cisco Packet Tracer : Cisco Packet Tracer is a dominant network simulation tool built by
Cisco Systems. You can make a simple or complex network inside the Packet tracer to create,
plan, configure, and test your network scenarios in a completely virtual ecosystem. This
Network Simulation tool allows users to create network topologies and imitate those in modern
computer networks. Packet Tracer is one of the most famous Networks Simulation software
among networking aspirants and beginners. It is used actively during the Cisco CCNA
Certification Training.

4. NetSim : NS is a name for a series of discrete event network simulators, specifically ns- 1,
ns-2, and ns-3. The Network Simulator – NS-3 is a discrete event simulator targeted at
networking research. Network Simulator -NS3 tool provides substantial support for simulation

20
of TCP, routing, and multicast protocols over wired and wireless (local and satellite) networks.
It is publicly available for research, development, and use.

5. OMNeT++ : OMNeT++ is a modular, component-based C++ simulation library and


framework, primarily for building network simulators. OMNeT++ can be used for free for non-
commercial simulations like at academic institutions and for teaching. OMNEST is an
extended version of OMNeT++ for commercial use.

6. NS2 : Ns is a discrete event simulator targeted at networking research. Ns provides substantial


support for simulation of TCP, routing, and multicast protocols over wired and wireless (local
and satellite) networks. NS2 stands for Network Simulator Version 2. It is an open-source
event-driven simulator designed specifically for research in computer communication
networks. 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.

21
EXPERIMENT NO - 5

AIM: Write a code simulating Ping and Trace-route commands

Algorithm
Step 1: start the program.
Step 2: Include necessary package in java.
Step 3: To create a process object p to implement the pingcommand.
Step 4: declare one Buffered Reader stream class object.
Step 5: Get the details of the server
5.1 : length of the IP address.
5.2 : time required to get the details.
5.3 : send packets, receive packets and lost packets.
5.4 : minimum, maximum and average times.
Step 6: print the results.
Step 7: Stop the program.

PROGRAM

import java.io.*;
import java.net.*;
class pingserver
{
public static void main(String args[])
{
try
{
String str;
System.out.print(" Enter the IP Address to be Ping : ");BufferedReader
buf1=new BufferedReader(new InputStreamReader(System.in));
String ip=buf1.readLine();
Runtime H=Runtime.getRuntime();
Process p=H.exec("ping " + ip);
InputStream in=p.getInputStream();
BufferedReader buf2=new BufferedReader(new
InputStreamReader(in));
while((str=buf2.readLine())!=null)
{
System.out.println(" " + str);
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}

22
}
}

TRACEROUTE COMMANDS:

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class traceroutecmd


{
public static void runSystemCommand(String command)
{
try
{
Process p = Runtime.getRuntime().exec(command);
BufferedReader inputStream = new BufferedReader(
new InputStreamReader(p.getInputStream()));

String s = "";
while ((s = inputStream.readLine()) != null)
System.out.println(s);
}
catch (Exception e)
{
}
}
public static void main(String[] args)
{
// String ip = "www.google.co.in";
// String ip = "127.0.0.1";
String ip = "www.cp-algorithms.com";
runSystemCommand("tracert " + ip);
}
}
OUTPUT:

23
EXPERIMENT NO - 6

AIM: Implement Subnetting to generate Range of IP Addresses.

Description: IP(Internet Protocol) addresses are used to identify hosts on the campus Internet, a
network that ties into the Internet, a global network. If the computer is attached to the network, it
needs an IP address to be recognized as part of the campus Internet. IP addresses are constructed
according to a set of specific rules so that hosts on any part of the Internet can communicate with
each other. An IP address consists of a 32-bit binary number, which is typically presented as four
decimal numbers (one for each 8-bit byte) separated by decimal points. For example,128.253.21.58.
Host Address
The host address is the address given to the workstation, other computer, or device that is
connected to the LAN.
Subnetting
Subnetting is the process of dividing an IP network in to sub divisions called subnets. Computers
belonging to a sub network have a common group of most-significant bits in their IP addresses. So,
this would break the IP address in to two parts (logically), as the network prefix and the rest field.
Dividing an IP network in to sub divisions is subnetting. It divides an IP address into two parts as
the network (or routing prefix) and there stifled (which is used to identify a specific host). CIDR
notation is used for writing a routing prefix. This notation uses a slash (/) to separate the network
starting address and the length of the network prefix(in bits). For example in IPv4, 192.60.128.0/22
indicates that 22 bits are allocated for the network prefix and the remaining 10bits are reserved for
the host address. In addition, routing prefix can also be represented using the subnet mask
255.255.252.0
(11111111.11111111.11111100.00000000) is the subnet mask for 192.60.128.0/22. Separating the
network portion and the subnet portion of an IP address is done by performing a bitwise AND
operation between the IP address and the subnet mask. This would result in identifying the network
prefix and the host identifier.

Supernetting

Super netting combines several subnetworks, having a Class less Inter-Domain Routing (CIDR)
routing prefix. Super netting is also called route aggregation or route summarization. Super netting
is the practice of combining several IP networks with a common network prefix. Supernetting was
introduced to tackle the problem of increasing size in routing tables .Supernetting also simplifies

24
the routing process. For example, the subnetworks 192.60.2.0/24and 192.60.3.0/24 can be merged
with the supernetwork denoted by 192.60.2.0/23. In the supernet, the first 23 bits are the network
part of the address and the other 9 bits are used as the host identifier. So, one address will represent
several small networks and this would reduce the number of entries that should be integrated in the
routing table.

A Supernetted Network

A network with three levels of hierarchy (subnetted)

25
Pseudo code: Subnetting process itself described above
Input:
In order to define the range of IP addresses we need the following:
In subnetting:
The first address of the subnet+ sub netmask
In super netting:
The first address of the supernet + supernet mask
Output: Subnets for a given network.

26
EXPERIMENT NO - 7

AIM: Implement Cyclic Redundancy Check at Sender and Receiver Site

The Cyclic Redundancy Checks (CRC) is the most powerful method for Error-Detection and Correction.
It is given as a kbit message and the transmitter creates an (n – k) bit sequence called frame check
sequence. The out coming frame, including n bits, is precisely divisible by some fixed number. Modulo 2
Arithmetic is used in this binary addition with no carries, just like the XOR operation.
Redundancy means duplicacy. The redundancy bits used by CRC are changed by splitting the data unit
by a fixed divisor. The remainder is CRC.
Qualities of CRC

It should have accurately one less bit than the divisor.

Joining it to the end of the data unit should create the resulting bit sequence precisely
divisible by the divisor.
CRC generator and checker

Process
 A string of n 0s is added to the data unit. The number n is one smaller than the number of bits
in the fixed divisor.
 The new data unit is divided by a divisor utilizing a procedure known as binary division; the
remainder appearing from the division is CRC.
 The CRC of n bits interpreted in phase 2 restores the added 0s at the end of the data unit.

Example
Message D = 1010001101 (10 bits)
Predetermined P = 110101 (6 bits)
FCS R = to be calculated 5 bits
Hence, n = 15 K = 10 and (n – k) = 5
The message is generated through 25:accommodating 1010001101000
27
The product is divided by P.

The remainder is inserted to 25D to provide T = 101000110101110 that is sent.


Suppose that there are no errors, and the receiver gets T perfect. The received frame is divided by P.

Because of no remainder, there are no errors.

CODE:
// import required classes and packages
package javaTpoint.MicrosoftJava;
import java.util.*;
// create CRCExample class to demonstrate the working of Cyclic Redundancy Check
class CRCExample {
// main() method start
public static void main(String args[]) {
// create scanner class object to take input from user
Scanner scan = new Scanner(System.in);
// declare n for the size of the data
int size;
28
// take the size of the data from the user
System.out.println("Enter the size of the data array: ");
size = scan.nextInt();
// declaration of the data array
int data[] = new int[size];
// take bits of the data from the user
System.out.println("Enter data bits in the array one by one: ");
for(int i = 0 ; i < size ; i++) {
System.out.println("Enter bit " + (size-i) + ":");
data[i] = scan.nextInt();
}
// take the size of the divisor from the user
System.out.println("Enter the size of the divisor array:");
size = scan.nextInt();
// declaration of the divisor array
int divisor[] = new int[size];
System.out.println("Enter divisor bits in the array one by one: ");
for(int i = 0 ; i < size ; i++) {
System.out.println("Enter bit " + (size-i) + ":");
divisor[i] = scan.nextInt();
}
// Divide the input data by the input divisor and store the result in the rem array
int rem[] = divideDataWithDivisor(data, divisor);
// iterate rem using for loop to print each bit
for(int i = 0; i < rem.length-1; i++) {
System.out.print(rem[i]);
}
System.out.println("\nGenerated CRC code is: ");

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


System.out.print(data[i]);
}
for(int i = 0; i < rem.length-1; i++) {
System.out.print(rem[i]);
}
System.out.println();
// we create a new array that contains the original data with its CRC code
// the size of the sentData array with be equal to the sum of the data and the rem arrays length
int sentData[] = new int[data.length + rem.length - 1];
System.out.println("Enter bits in the array which you want to send: ");
for(int i = 0; i < sentData.length; i++) {
System.out.println("Enter bit " +(sentData.length - 1)+ ":");
sentData[i] = scan.nextInt();
}
receiveData(sentData, divisor);
}
// create divideDataWithDivisor() method to get CRC
static int[] divideDataWithDivisor(int oldData[], int divisor[]) {
// declare rem[] array
int rem[] = new int[divisor.length];
int i;
int data[] = new int[oldData.length + divisor.length];
29
// use system's arraycopy() method for copying data into rem and data arrays
System.arraycopy(oldData, 0, data, 0, oldData.length);
System.arraycopy(data, 0, rem, 0, divisor.length);
// iterate the oldData and exor the bits of the remainder and the divisor
for(i = 0; i < oldData.length; i++) {
System.out.println((i+1) + ".) First data bit is : "+ rem[0]);
System.out.print("Remainder : ");
if(rem[0] == 1) {
// We have to exor the remainder bits with divisor bits
for(int j = 1; j < divisor.length; j++) {
rem[j-1] = exorOperation(rem[j], divisor[j]);
System.out.print(rem[j-1]);
}
}
else {
// We have to exor the remainder bits with 0
for(int j = 1; j < divisor.length; j++) {
rem[j-1] = exorOperation(rem[j], 0);
System.out.print(rem[j-1]);
}
}
// The last bit of the remainder will be taken from the data
// This is the 'carry' taken from the dividend after every step
// of division
rem[divisor.length-1] = data[i+divisor.length];
System.out.println(rem[divisor.length-1]);
}
return rem;
}
// create exorOperation() method to perform exor data
static int exorOperation(int x, int y) {
// This simple function returns the exor of two bits
if(x == y) {
return 0;
}
return 1;
}
// method to print received data
static void receiveData(int data[], int divisor[]) {

int rem[] = divideDataWithDivisor(data, divisor);


// Division is done
for(int i = 0; i < rem.length; i++) {
if(rem[i] != 0) {
// if the remainder is not equal to zero, data is currupted
System.out.println("Currupted data received...");
return;
}
}
System.out.println("Data received without any error.");
}
}
30
Output:

31
32
EXPERIMENT NO - 8

AIM: Implement Hamming Code at Sender and Receiver Site.

Hamming code is a special code in a Computer network, which is a set of error-correction codes. In
Computer Graphics, it is mainly used for detecting and correcting errors that occur at the time of data
transmission from sender to receiver. In Java, we can implement the code to detect and correct errors
using Hamming code.

CODE:

// import required classes and packages


package javaTpoint.JavaExample;
import java.util.*;

// create HammingCodeExample class to implement the Hamming Code functionality in Java


class HammingCodeExample {

// main() method start


public static void main(String args[])
{
// declare variables and array
int size, hammingCodeSize, errorPosition;
int arr[];
int hammingCode[];
// create scanner class object to take input from user
Scanner sc = new Scanner(System.in);
System.out.println("Enter the bits size for the data.");
size = sc.nextInt();
// initialize array
arr = new int[size];
// get data from user which we want to transfer
for(int j = 0 ; j < size ; j++) {
System.out.println("Enter " + (size - j) + "-bit of the data:");
// fill array with user entered data
arr[size - j - 1] = sc.nextInt();
}

// print the user entered data


System.out.println("The data which you enter is:");
for(int k = 0 ; k < size ; k++) {
System.out.print(arr[size - k - 1]);
}
System.out.println(); // for next line

// call getHammingCode() method and store its return value to the hammingCode array
hammingCode = getHammingCode(arr);
hammingCodeSize = hammingCode.length;

System.out.println("The hamming code generated for your data is:");


33
for(int i = 0 ; i < hammingCodeSize; i++) {
System.out.print(hammingCode[(hammingCodeSize - i - 1)]);
}
System.out.println(); // for next line

// The added parity bits are the difference b/w the original data and the returned hammingCode
System.out.println("For detecting error at the reciever end, enter position of a bit to alter original data
"
+ "(0 for no error):");
errorPosition = sc.nextInt();

// close Scanner class object


sc.close();

// check whether the user entered position is 0 or not.


if(errorPosition != 0) {
// alter bit of the user entered position
hammingCode[errorPosition - 1] = (hammingCode[errorPosition - 1] + 1) % 2;
}

// print sent data to the receiver


System.out.println("Sent Data is:");
for(int k = 0; k < hammingCodeSize; k++) {
System.out.print(hammingCode[hammingCodeSize - k - 1]);
}
System.out.println(); // for next line
receiveData(hammingCode, hammingCodeSize - arr.length);
}
// create getHammingCode() method that returns the hamming code for the data which we want to send

static int[] getHammingCode(int data[]) {


// declare an array that will store the hamming code for the data
int returnData[];
int size;
// code to get the required number of parity bits
int i = 0, parityBits = 0 ,j = 0, k = 0;
size = data.length;
while(i < size) {
// 2 power of parity bits must equal to the current position(number of bits traversed + number of pa
rity bits + 1).
if(Math.pow(2, parityBits) == (i + parityBits + 1)) {
parityBits++;
}
else {
i++;
}
}

// the size of the returnData is equal to the size of the original data + the number of parity bits.
returnData = new int[size + parityBits];

// for indicating an unset value in parity bit location, we initialize returnData array with '2'
34
for(i = 1; i <= returnData.length; i++) {
// condition to find parity bit location
if(Math.pow(2, j) == i) {

returnData[(i - 1)] = 2;
j++;
}
else {
returnData[(k + j)] = data[k++];
}
}
// use for loop to set even parity bits at parity bit locations
for(i = 0; i < parityBits; i++) {

returnData[((int) Math.pow(2, i)) - 1] = getParityBit(returnData, i);


}

return returnData;
}

// create getParityBit() method that return parity bit based on the power
static int getParityBit(int returnData[], int pow) {
int parityBit = 0;
int size = returnData.length;

for(int i = 0; i < size; i++) {

// check whether returnData[i] contains an unset value or not


if(returnData[i] != 2) {

// if not, we save the index in k by increasing 1 in its value

int k = (i + 1);

// convert the value of k into binary


String str = Integer.toBinaryString(k);

//Now, if the bit at the 2^(power) location of the binary value of index is 1,
// we check the value stored at that location. If the value is 1 or 0,
// we will calculate the parity value.

int temp = ((Integer.parseInt(str)) / ((int) Math.pow(10, pow))) % 10;


if(temp == 1) {
if(returnData[i] == 1) {
parityBit = (parityBit + 1) % 2;
}
}
}
}
return parityBit;
}
35
// create receiveData() method to detect error in the received data
static void receiveData(int data[], int parityBits) {

// declare variable pow, which we use to get the correct bits to check for parity.
int pow;
int size = data.length;
// declare parityArray to store the value of parity check
int parityArray[] = new int[parityBits];
// we use errorLoc string for storing the integer value of the error location.
String errorLoc = new String();
// use for loop to check the parities
for(pow = 0; pow < parityBits; pow++) {
// use for loop to extract the bit from 2^(power)
for(int i = 0; i < size; i++) {
int j = i + 1;
// convert the value of j into binary
String str = Integer.toBinaryString(j);
// find bit by using str
int bit = ((Integer.parseInt(str)) / ((int) Math.pow(10, pow))) % 10;
if(bit == 1) {
if(data[i] == 1) {
parityArray[pow] = (parityArray[pow] + 1) % 2;
}
}
}
errorLoc = parityArray[pow] + errorLoc;
}
// This gives us the parity check equation values.
// Using these values, we will now check if there is a single bit error and then correct it.
// errorLoc provides parity check eq. values which we use to check whether a single bit error is there
or not
// if present, we correct it
int finalLoc = Integer.parseInt(errorLoc, 2);
// check whether the finalLoc value is 0 or not
if(finalLoc != 0) {
System.out.println("Error is found at location " + finalLoc + ".");
data[finalLoc - 1] = (data[finalLoc - 1] + 1) % 2;
System.out.println("After correcting the error, the code is:");
for(int i = 0; i < size; i++) {
System.out.print(data[size - i - 1]);
}
System.out.println();
}
else {
System.out.println("There is no error in the received data.");
}
// print the original data
System.out.println("The data sent from the sender:");
pow = parityBits - 1;
for(int k = size; k > 0; k--) {
if(Math.pow(2, pow) != k) {
36
System.out.print(data[k - 1]);
}
else {
// decrement value of pow
pow--;
}
}
System.out.println(); // for next line
}
}
Output:

37
EXPERIMENT NO - 9

AIM: Implement RSA Algorithm.

RSA encryption algorithm is a type of public-key encryption algorithm. To better understand


RSA, lets first understand what is public-key encryption algorithm.

Public key encryption algorithm:

Public Key encryption algorithm is also called the Asymmetric algorithm. Asymmetric algorithms
are those algorithms in which sender and receiver use different keys for encryption and
decryption. Each sender is assigned a pair of keys:

o Public key
o Private key

The Public key is used for encryption, and the Private Key is used for decryption. Decryption
cannot be done using a public key. The two keys are linked, but the private key cannot be
derived from the public key. The public key is well known, but the private key is secret and it is
known only to the user who owns the key. It means that everybody can send a message to the
user using user's public key. But only the user can decrypt the message using his private key.

The Public key algorithm operates in the following manner:

o The data to be sent is encrypted by sender A using the public key of the intended
receiver
o B decrypts the received ciphertext using its private key, which is known only to B. B
replies to A encrypting its message using A's public key.
o A decrypts the received ciphertext using its private key, which is known only to him.

38
RSA encryption algorithm:

RSA is the most common public-key algorithm, named after its inventors Rivest, Shamir, and
Adelman (RSA).

RSA algorithm uses the following procedure to generate public and private keys:

o Select two large prime numbers, p and q.


o Multiply these numbers to find n = p x q, where n is called the modulus for encryption
and decryption.
o Choose a number e less than n, such that n is relatively prime to (p - 1) x (q -1). It means
that e and (p - 1) x (q - 1) have no common factor except 1. Choose "e" such that 1<e < φ(n),e is
prime_to_φ(n)
gcd (e,d(n)) =1
o If n = p x q, then the public key is <e, n>. A plaintext message m is encrypted using
public key <e, n>. To find ciphertext from the plain text following formula is used to get
cipher_text_C.
C=me mod_n
Here, m must be less than n. A larger message (>n) is treated as a concatenation of
messages, each of which is encrypted separately.
o To determine the private key, we use the following formula to calculate the d such that:
De mod{(p-1)x(q-1)}=1
Or
De mod φ (n) = 1
o The private key is <d, n>. A ciphertext message c is decrypted using private key <d, n>.
To calculate plain text m from the ciphertext c following formula is used to get plain text
39
m.
m = cd mod n

Let's take some example of RSA encryption algorithm:

Example 1:

This example shows how we can encrypt plaintext 9 using the RSA public-key encryption
algorithm. This example uses prime numbers 7 and 11 to generate the public and private keys.

Explanation:

Step 1: Select two large prime numbers, p, and q.

p=7

q = 11

Step 2: Multiply these numbers to find n = p x q, where n is called the modulus for encryption
and decryption.

First, we calculate

n=pxq

n = 7 x 11

n = 77

Step 3: Choose a number e less that n, such that n is relatively prime to (p - 1) x (q -1). It
means that e and (p - 1) x (q - 1) have no common factor except 1. Choose "e" such that 1<e <
φ (n), e is prime to φ (n), gcd (e, d (n)) =1.

Second, we calculate

φ (n) = (p - 1) x (q-1)

φ (n) = (7 - 1) x (11 - 1)

φ (n) = 6 x 10

φ (n) = 60

Let us now choose relative prime e of 60 as 7.

Thus the public key is <e, n> = (7, 77)

Step 4: A plaintext message m is encrypted using public key <e, n>. To find ciphertext from the
plain text following formula is used to get ciphertext C.

To find ciphertext from the plain text following formula is used to get ciphertext C.
40
C = me mod n

C = 97 mod 77

C = 37

Step 5: The private key is <d, n>. To determine the private key, we use the following formula d
such that:

De mod {(p - 1) x (q - 1)} = 1

7d mod 60 = 1, which gives d = 43

The private key is <d, n> = (43, 77)

Step 6: A ciphertext message c is decrypted using private key <d, n>. To calculate plain
text m from the ciphertext c following formula is used to get plain text m.

m = cd mod n

m = 3743 mod 77

m=9

In this example, Plain text = 9 and the ciphertext = 37

Algorithm

Begin
1. Choose two prime numbers p and q.
2. Compute n = p*q.
3. Calculate phi = (p-1) * (q-1).
4. Choose an integer e such that 1 < e < phi(n) and gcd(e, phi(n)) = 1; i.e., e and phi(n) are coprime.
5. Calculate d as d ≡ e−1 (mod phi(n)); here, d is the modular multiplicative inverse of e modulo phi(n).
6. For encryption, c = me mod n, where m = original message.
7. For decryption, m = c d mod n.
End

Code :

#include<iostream>
#include<math.h>
using namespace std;
// find gcd
int gcd(int a, int b) {
int t;
while(1) {
t= a%b;
if(t==0)
return b;
a = b;
b= t;
}
41
}
int main() {
//2 random prime numbers
double p = 13;
double q = 11;
double n=p*q;//calculate n
double track;
double phi= (p-1)*(q-1);//calculate phi
//public key
//e stands for encrypt
double e=7;
//for checking that 1 < e < phi(n) and gcd(e, phi(n)) = 1; i.e., e and phi(n) are coprime.
while(e<phi) {
track = gcd(e,phi);
if(track==1)
break;
else
e++;
}
//private key
//d stands for decrypt
//choosing d such that it satisfies d*e = 1 mod phi
double d1=1/e;
double d=fmod(d1,phi);
double message = 9;
double c = pow(message,e); //encrypt the message
double m = pow(c,d);
c=fmod(c,n);
m=fmod(m,n);
cout<<"Original Message = "<<message;
cout<<"\n"<<"p = "<<p;
cout<<"\n"<<"q = "<<q;
cout<<"\n"<<"n = pq = "<<n;
cout<<"\n"<<"phi = "<<phi;
cout<<"\n"<<"e = "<<e;
cout<<"\n"<<"d = "<<d;
cout<<"\n"<<"Encrypted message = "<<c;
cout<<"\n"<<"Decrypted message = "<<m;
return 0;
}
Output
p = 13
q = 11
n = pq = 143
phi = 120
e=7
d = 0.142857
Original Message = 9
Encrypted message = 48
Decrypted message = 9

42
EXPERIMENT NO – 10

AIM: Implement Diffie Hellman Algorithm.


Description: Diffie–Hellman key exchange (D-H) is a specific method of exchanging
cryptographic keys. It is one of the earliest practical examples of key exchange implemented
within the field of cryptography. The Diffie–Hellman key exchange method allows two parties
that have no prior knowledge of each other to jointly establish a shared secret key over an
insecure communications channel. This key can then be used to encrypt subsequent
communications using a symmetric key cipher. The Diffie–Hellman problem is stated informally
as follows:
Given an element g and the values of gx and gy, what is the value of gxy?

Formally, g is a generator of some group (typically the multiplicative group of a finite field or an
elliptic curve group) and x and y are randomly chosen integers. Diffie Hellman key exchange
algorithm uses asymmetric key principles for the distribution of symmetric keys to both parties in a
communication network. Key distribution is an important aspect of conventional algorithmand the
entire safety is dependent on the distribution of key using secured channel. Diffie Hellman
utilizes the public& private key of asymmetric key cryptography to exchange the secret key.
Before going in depth of Diffie Hellman Algorithm, we define primitive root of a prime number
'p' as one whose powers generate all the integers from 1 to p-1, i.e. if 'a' is the primitive root of a
prime no 'p', then, a mod p , a2 mod p , a 3
mod p, .............. ap-1 mod p generate all distinct
integers from 1 to (p-1) in some permutation.

CODE:
import java.util.*;
// create class DiffieHellmanAlgorithmExample to calculate the key for two persons
class DiffieHellmanAlgorithmExample {
// main() method start
public static void main(String[] args)
{
long P, G, x, a, y, b, ka, kb;
// create Scanner class object to take input from user
Scanner sc = new Scanner(System.in);
System.out.println("Both the users should be agreed upon the public keys G and P");
// take inputs for public keys from the user
System.out.println("Enter value for public key G:");
G = sc.nextLong();
System.out.println("Enter value for public key P:");
P = sc.nextLong();
// get input from user for private keys a and b selected by User1 and User2
System.out.println("Enter value for private key a selected by user1:");
43
a = sc.nextLong();
System.out.println("Enter value for private key b selected by user2:");
b = sc.nextLong();

// call calculatePower() method to generate x and y keys


x = calculatePower(G, a, P);
y = calculatePower(G, b, P);
// call calculatePower() method to generate ka and kb secret keys after the exchange of x and y keys
// calculate secret key for User1
ka = calculatePower(y, a, P);
// calculate secret key for User2
kb = calculatePower(x, b, P);
// print secret keys of user1 and user2
System.out.println("Secret key for User1 is:" + ka);
System.out.println("Secret key for User2 is:" + kb);
}
// create calculatePower() method to find the value of x ^ y mod P
private static long calculatePower(long x, long y, long P)
{
long result = 0;
if (y == 1){
return x;
}
else{
result = ((long)Math.pow(x, y)) % P;
return result;
}
}
}

Output:

44
EXPERIMENT NO -11
AIM: Implementation of Stop and Wait Protocol and Sliding Window Protocol

STOP & WAIT PROTOCOL:

Here stop and wait means, whatever the data that sender wants to send, he sends the data to the
receiver. After sending the data, he stops and waits until he receives the acknowledgment from
the receiver. The stop and wait protocol is a flow control protocol where flow control is one of
the services of the data link layer.

It is a data-link layer protocol which is used for transmitting the data over the noiseless
channels. It provides unidirectional data transmission which means that either sending or
receiving of data will take place at a time. It provides flow-control mechanism but does not
provide any error control mechanism.

The idea behind the usage of this frame is that when the sender sends the frame then he waits for
the acknowledgment before sending the next frame.

Primitives of Stop and Wait Protocol

Sender side

Rule 1: Sender sends one data packet at a time.

Rule 2: Sender sends the next packet only when it receives the acknowledgment of the
previous packet.

Therefore, the idea of stop and wait protocol in the sender's side is very simple, i.e., send one
packet at a time, and do not send another packet before receiving the acknowledgment.

Receiver side

Rule 1: Receive and then consume the data packet.

Rule 2: When the data packet is consumed, receiver sends the acknowledgment to the sender.
Therefore, the idea of stop and wait protocol in the receiver's side is also very simple, i.e.,
consume the packet, and once the packet is consumed, the acknowledgment is sent. This is
known as a flow control mechanism.

45
SLIDING WINDOW PROTOCOL
The sliding window is a technique for sending multiple frames at a time. It controls the data
packets between the two devices where reliable and gradual delivery of data frames is needed. It
is also used in TCP (Transmission Control Protocol). In this technique, each frame has sent from
the sequence number. The sequence numbers are used to find the missing data in the receiver
end. The purpose of the sliding window technique is to avoid duplicate data, so it uses the
sequence number.

Types of Sliding Window Protocol

1.Go-Back-N ARQ

Go-Back-N ARQ protocol is also known as Go-Back-N Automatic Repeat Request. It is a data
link layer protocol that uses a sliding window method. In this, if any frame is corrupted or lost,
all subsequent frames have to be sent again. The size of the sender window is N in this protocol.
For example, Go-Back-8, the size of the sender window, will be 8. The receiver window size is
always 1. If the receiver receives a corrupted frame, it cancels it. The receiver does not accept a
corrupted frame. When the timer expires, the sender sends the correct rame again.

46
1. Selective Repeat ARQ
Selective Repeat ARQ is also known as the Selective Repeat Automatic Repeat Request. It is a
data link layer protocol that uses a sliding window method. The Go-back-N ARQ protocol
works well if it has fewer errors. But if there is a lot of error in the frame, lots of bandwidth loss
in sending the frames again. So, we use the Selective Repeat ARQ protocol. In this protocol,
the size of the sender window is always equal to the size of the receiver window. The size of
the sliding window is always greater than 1. Acknowledgement to the sender. The sender sends
that frame again as soon as on the receiving negative acknowledgment. There is no waiting for
any time-out to send that frame.

47
CODE:

48
49
50
51
EXPERIMENT NO – 12

AIM: To perform case study for different routing algorithms to select the
network path using LINK STATE ROUTING b) FLOODING c) DISTANCE
VECTOR.

LINK STATE ROUTING

Link State Routing Link state routing has a different philosophy from that of distance vector routing. In
link state routing, if each node in the domain has the entire topology of the domainthe list of nodes and
links, how they are connected including the type, cost (metric), and condition of the links (up or down)-the
nodecan use Dijkastra's algorithm to build a routing table.

Concept of link state routing

The figure shows a simple domain with five nodes. Each node uses the same topology to create a routing
table, but the routing table for each node is unique because the calculations are based on different
interpretations of the topology. Thisis analogous to a city map. While each person may have the same
map, each needsto take a different route to reach her specific destination.

The topology must be dynamic, representing the latest state of each node and each link. If there are
changes in any point in the network (a link is down, for example), the topology must be updated for each
node.
FLOODING

Flooding is a non-adaptive routing technique following this simple method: whena data packet arrives
at a router, it is sent to all the outgoing links except the one it has arrived on.
For example, let us consider the network in the figure, having six routers that are connected through
transmission lines.

52
Using flooding technique −
● An incoming packet to A, will be sent to B, C and D.
● B will send the packet to C and E.
● C will send the packet to B, D and F.
● D will send the packet to C and F.
● E will send the packet to F.
● F will send the packet to C and E.

Types of Flooding

Flooding may be of three types −


● Uncontrolled flooding − Here, each router unconditionally transmits the incoming data packets
to all its neigh bours.
● Controlled flooding − They use some methods to control the transmission of packets to the
neighbouring nodes. The two popular algorithms for controlled flooding are Sequence Number
Controlled Flooding (SNCF) and Reverse Path Forwarding (RPF).
● Selective flooding − Here, the routers don't transmit the incoming packets only along those paths
which are heading towards approximately in the right direction, instead of every available paths.

Advantages of Flooding

● It is very simple to setup and implement, since a router may know only its neighbours.
● It is extremely robust. Even in case of malfunctioning of a large number routers, the packets find
a way to reach the destination.
● All nodes which are directly or indirectly connected are visited. So, there are no chances for any
node to be left out. This is a main criteria in case of broadcast messages.
● The shortest path is always chosen by flooding.

Limitations of Flooding

● Flooding tends to create an infinite number of duplicate data packets, unlesssome measures are
adopted to damp packet generation.
● It is wasteful if a single destination needs the packet, since it delivers the datapacket to all nodes
irrespective of the destination.
● The network may be clogged with unwanted and duplicate data packets. This may hamper
53
delivery of other data packets.
● Distance Vector Routing

● Distance Vector Routing In distance vector routing, the least-cost route between any two nodes
is the route with minimum distance. In this protocol, as the name implies, each node maintains a
vector (table) of minimum distances to every node. The table at each node also guides the
packets to the desired node by showing the next stop in the route (next-hop routing). We can
think of nodes as the cities in an area and the lines as the roads connecting them. A table can
show a tourist the minimum distance between cities. In Figure 22.14, we show a system of five
nodeswith their corresponding tables.

● Distance vector routing tables

● The table for node A shows how we can reach any node from this node. Forexample, our least
cost to reach node E is 6. The route passes through C.

● Initialization

● Each node knows how to reach any other node and the cost. At the beginning, however, this is
not the case. Each node can know only the distance between itselfand its immediate neighbors,
those directly connected to it. So for the moment, we
● assume that each node can send a message to the immediate neighbors and find thedistance
between itself and these neighbors.

● Initialization of tables in distance vector routing.

54
Sharing

The whole idea of distance vector routing is the sharing of information between neighbors. Although
node A does not know about node E, node C does. So if node C shares its routing table with A, node A
can also know how to reach node E. On the other hand, node C does not know how to reach node D,
but node A does. If node A shares its routing table with node C, node C also knows how to reach node
D. In other words, nodes A and C, as immediate neighbors, can improve their routing tables if they help
each other. There is only one problem. How much of thetable must be shared with each neighbor? A node
is not aware of a neighbor's table.The best solution for each node is to send its entire table to the neighbor
and let theneighbor decide what part to use and what part to discard. However, the third column of a table
(next stop) is not useful for the neighbor. When the neighbor receives a table, this column needs to be
replaced with the sender's name. If any of the rows can be used, the next node is the sender of the table. A
node therefore can
send only the first two columns of its table to any neighbor. In other words, sharing here means sharing
only the first two columns.

In distance vector routing, each node shares its routing table with its immediateneighbors periodically and
when there is a change.

Updating

When a node receives a two-column table from a neighbor, it needs to update itsrouting table. Updating
takes three steps:

1. The receiving node needs to add the cost between itself and the sending node to each value in the
second column. The logic is clear. If node C claims that its distance to a destination is x mi, and the
distance between A and C is y mi, then thedistance between A and that destination, via C, is x + y
mi.

2. The receiving node needs to add the name of the sending node to each row as the third column if
the receiving node uses information from any row. The sendingnode is the next node in the route.

3. The receiving node needs to compare each row of its old table with thecorresponding row
of the modified version of the received table.

a. If the next-node entry is different, the receiving node chooses the row with thesmaller cost. If there
is a tie, the old one is kept.

b. If the next-node entry is the same, the receiving node chooses the new row. Forexample , suppose
node C has previously advertised a route to node X with distance.

3. Suppose that now there is no path between C and X; node C now advertises thisroute with a distance of
infinity. Node A must not ignore this value even though its old entry is smaller. The old route does not
exist any more . The new route has a distance of infinity.

Updating in distance vector routing

There are several points we need to emphasize here. First, as we know frommathematics, when
55
we add any number to infinity, the result is still infinity
Second, the modified table shows how to reach A from A via C. If A needs to reach itself via C, it needs
to go to C and come back, a distance of 4. Third, theonly benefit from this updating of node A is the last
entry, how to reach E. Previously, node A did not know how to reach E (distance of infinity); now it
knows that the cost is 6 via C.

Each node can update its table by using the tables received from other nodes. In a short time, if there is
no change in the network itself, such as a failure in a link, each node reaches a stable condition in which
the contents of its table remains thesame.

When to Share

The question now is, When does a node send its partial routing table (only twocolumns) to all its
immediate neighbors? The table is sent both periodically and when there is a change in the table.
Periodic Update A node sends its routing table, normally every 30 s, in a periodic update. The
period depends on the protocol that is using distance vector routing. Triggered Update A node sends its
two-column routing table to its neighbors anytime there is a change in its routing table. This is called a
triggered update. The change can result from the following.

1. A node receives a table from a neighbor, resulting in changes in its own tableafter updating.

2. A node detects some failure in the neighboring links which results in a distancechange to infinity
3.

56

You might also like