CN Pracs A 60004190053
CN Pracs A 60004190053
CN Pracs A 60004190053
Aim : To study the different networking devices and different networking topologies.
Theory :
• Networking Devices :
Hardware devices that are used to connect computers, printers, fax machines
and other electronic devices to a network are called network devices. These devices
transfer data in a fast, secure and correct way over same or different networks.
Network devices may be inter-network or intra-network. Some devices are installed
on the device, whereas some are part of the network.
1. Hub :
Hub is the most basic networking device that connects multiple computers or
other network devices together. A network hub has no routing tables or intelligence
on where to send information and broadcasts all network data across each connection.
Most hubs can detect basic network errors, such as collisions. In the past, network
hubs were popular because they were cheaper than a switch or router.
Definition : A network hub is a device that allows multiple computers to
communicate with each other over a network. It has several Ethernet ports that are
used to connect two or more network devices together. It is a Broadcasting Device.
Picture : Logical Symbol :
Networking Diagram :
Working :
When a host sends frames, the hub forwards the frames in all the ports, except
the port from which it receives data. Hubs do not separate the type of the frame, for
example, whether the frame unicast should be either multicast or broadcast. Hubs
forward all the frames into all the ports. Although a hub sends the frames to all the
ports, a computer accepts the ones, whose MAC match matches the destination MAC
address field. The rest of the frames are discarded after receiving the required
information.
Hubs perform half duplex communication. It means either a host can send or
receive data. Both works cannot be done together. Therefore frames in the hub is
pretty much crashing. This happens when someone is sending a host frame, the
second host is also sending the frame at the same time. It's called collision.
There are three types of hubs :
1. Passive Hub :
One of the types of a network hub is the so-called passive hub. It's a pass-
through that does not do anything more than just broadcast signals it receives
through its input port, then sends it out through the output port. It does not do
anything to regenerate or process the signals because it only functions as a
connector of different wires in a topology.
2. Active Hub :
An active hub works more than just a connector but also regenerates the data
bits to ensure the signals are strong. Another name for an active hub is a multiport
repeater. It provides an active participation in the network aside from acting as an
interface. It participates in the data communication, such as storing signals received
through the input ports, before forwarding them. It can monitor the data it is
forwarding and sometimes help improve signals before forwarding them to other
connections. Such a feature makes troubleshooting of network problems easier.
3. Intelligent Hub :
An intelligent hub can perform everything that the passive hub and active hub
do, and help manage the network resources effectively to ensure that the
performance of the network is highly efficient. An intelligent hub can help in
troubleshooting by pinpointing the actual location of the problem and help
identify the root cause and resolution. It is very adaptable to different technologies
without any need to change its configuration. The intelligent hub performs
different functions such as bridging, routing, switching and network management.
Applications of Hub :
1. Hubs are used in organizations for connectivity.
2. They are used for creating small home networks.
3. It is used for network monitoring.
4. You can create a device or peripheral which is available thought out the network.
Advantages of Hub :
1. It provides support for different types of Network Media.
2. It can be used by anyone as it is very cheap.
3. It can easily connect many different media types.
4. The use of a hub does not impact on the network performance.
5. Additionally, it can expand the total distance of the network.
Disadvantages of Hub :
1. It has no ability to choose the best path of the network.
2. It does not include mechanisms such as collision detection.
3. It does not operate in full-duplex mode and cannot be divided into the Segment.
4. It cannot reduce the network traffic as it has no mechanism.
5. It is not able to filter the information as it transmits packets to all the connected
segments.
6. It uses a lot of unnecessary network bandwidth.
2. Switch :
A Network Switch is a device which is used to connect multiple computers
inside Local Area Network. Network Switches operate at Layer Two (Data Link
Layer) of the OSI model. There are Network Switches that can operate at the Network
Layer (layer 3 and above) also. Network Switches operate in Layer 3 are often
referred to as Layer 3 switches or multilayer switches. Basic Function of a Network
Switch is to forward Layer 2 packets from source device to destination device. A
Network switch generally contains more intelligence than a hub.
Definition : A network switch connects devices within a network (often LAN) and
forwards data packets to and from those devices. A switch only sends data to the
single device it is intended for not to networks of multiple devices. It is a unicasting
device.
Picture : Logical Symbol :
Networking Diagram :
Working :
When a device sends a packet to another device, it enters the switch and the
switch reads its header and stores in its buffer of receiving link to determine what to
do with it. It matches the destination MAC address and sends the packet out through
the appropriate port that leads to the destination device, if the outgoing link is free.
To reduce the chance for collisions between network traffic going to and from
a switch and a connected device at the same time, most switches offer full-duplex
functionality in which packets coming from and going to a device have access to the
full bandwidth of the switch connection. Switches are usually 12,24,48 ports devices.
There are two main types of switches :
1. Unmanaged Switch :
These are the switches that are mostly used in home networks and small
businesses as they plug-in and instantly start doing their job and such switches do not
need to be watched or configured. These require only small cable connections. It
allows devices on a network to connect with each other such as a computer to a
computer or a computer to a printer in one location. They are the least expensive
switches among all categories. They dynamically find which device is connected on
which port, and accordingly forward the entering packets.
2. Managed Switch :
This type of switches have many features like the highest levels of security,
precision control and full management of the network. These are used in organisations
containing a large network and can be customized to enhance the functionality of a
certain network. These are the costliest option but their scalability makes them an
ideal option for a network that is growing. They are achieved by setting a simple
network management protocol(SNMP). They keep a record of which device is
connected to which port number and after matching destination address from the
records, forwards the packets. If a device changes its position, the record has to be
updated.
Applications of Switches :
1. In larger networks, switches are often used as a way to offload traffic for analytic
purposes. This can be important to security, where a switch can be placed in front
of a WAN router, before the traffic goes to the LAN.
2. At its most basic, however, it is the simple task for a network switch to quickly
and efficiently deliver packets from computer A to computer B, whether the
computers are located across the hallway or halfway around the world.
Advantages of Switch :
1. They increase the available bandwidth of the network.
2. They help in reducing workload on individual host PCs.
3. They increase the performance of the network.
4. Networks which use switches will have less frame collisions. This is due to the
fact that switches create collision domains for each connection.
5. Switches can be connected directly to workstations.
Disadvantages of Switch :
1. They are more expensive compare to network bridges.
2. Network connectivity issues are difficult to be traced through the network switch.
3. Broadcast traffic may be troublesome.
4. If switches are in promiscuous mode, they are vulnerable to security attacks e.g.
spoofing IP address or capturing of ethernet frames.
5. Proper design and configuration is needed in order to handle multicast packets.
6. While limiting broadcasts, they are not as good as routers.
3. Router :
Router is the basic backbone for the Internet. The main function of the router
is to connect two or more than two network and forwards the packet from one
network to another. A router connects multiple networks. This means that it has
multiple interfaces that each belong to a different IP network. Routers are very
common today in every network area, this is mainly because every network these days
connect to some other network, whether it's the Internet or some other remote site.
Routers get their name from what they do, which is route data from one network to
another. A router is used in LAN (Local Area Network) and WAN (Wide Area
Network) environments.
Definition :
The router is a physical or virtual internetworking device that is designed to
receive, analyse, and forward data packets between computer networks. A router
examines a destination IP address of a given data packet, and it uses the headers and
forwarding tables to decide the best way to transfer the packets.
Picture : Logical Symbol :
Networking Diagram :
Working :
A router examines a packet header's destination IP address and compares it
against a routing table to determine the packet's best next hop. Routing tables list
directions for forwarding data to particular network destinations, sometimes in the
context of other variables, like cost. They amount to an algorithmic set of rules that
calculate the best way to transmit traffic toward any given IP address.
A routing table often specifies a default route, which the router uses whenever
it fails to find a better forwarding option for a given packet. For example, the typical
home office router directs all outbound traffic along a single default route to its
internet service provider (ISP).
Routing tables can be static (manually configured) or dynamic. Dynamic
routers automatically update their routing tables based on network activity,
exchanging information with other devices via routing protocols.
The various types of router are as follows :
1. Wired and Wireless Router : These routers are mostly used in homes and small
offices. Wired routers share data over cables and create wired local area networks
(LANs), while wireless routers use antennas to share data and create wireless local
area networks (WLANs).
2. Edge Router : This is a wired or wireless router that distributes data packets
between one or more networks but not within a network. As their name indicates,
edge routers are placed at the edge or boundary of networks, and typically connect
to Internet service providers (ISPs) or other organizations’ networks. Their job is
to keep your network communicating smoothly with other networks.
3. Core Router : These wired or wireless routers distribute data packets within
networks, but not between multiple networks. They’re designed to become the
backbone of your network and do the heavy lifting of data transfer, which is why
they’re usually high-performance.
4. Virtual Router : Unlike physical routers, virtual routers are pieces of software
that allow computers and servers to operate like routers. They’ll share data
packets just as physical routers do. They can offer more flexibility than physical
devices since they can be scaled as the business grows; they can also help get
remote offices up and running on your network more quickly.
Applications of Router :
1. Routers are used to connect hardware equipment with remote location networks
like BSC, MGW, IN, SGSN, and other servers.
2. Internet service providers widely use routers to send the data from source to
destination in the form of e-mail, a web page, image, voice, or a video file.
Furthermore, it can send data all over the world with the help of an IP address of
the destination.
3. Routers are also used by software testers for WAN communications. For example,
the software manager of an organization is located in Agra, and its executive is
located at a different place like Pune or Bangalore. Then the router provides the
executive the method to share his software tools and other applications with the
manager with the help of routers by connecting their PCs to the router using WAN
architecture.
4. In wireless networks, by configuring VPN in routers, it can be used in the client-
server model, which allows sharing the internet, video, data, voice, and hardware
resources.
Advantages of Router :
1. Connection : The primary function of router is to share a single network
connection among different machines. Using these multiple users can be
connected to the internet so that overall productivity can be increased.
2. Security : Because connecting to the internet directly with a modem exposes your
PC to variety of security threats. Therefore, routers can be used as a
intermediately between 2 networks so that the environment is secure to some
extent.
3. Dynamic Routing : For facilitating internetwork communication, the router uses
dynamic routing techniques. Dynamic routing determines the best path available
for the internetwork. And also it creates broadcast and collision domains. This can
overall reduce the network traffic.
4. Packet Filtering : Routers filter the network using a set of filtering rules.
According to these rules the packets are either allowed or passed through.
5. NAT Usage : Routers take use of Network Address Translation (NAT). With
NAT routers can share the connection by using single public IP address and share
of UDP ports. Moreover it is almost impossible for large companies to connect to
the internet without NAT.
6. Integrations : Routers can usually be integrated with modems. This ensures that
Wireless Access Points are provided to create small networks.
Disadvantages of Router :
1. Speed : Router completely analyse the data from physical to network layer. As a
result the connection could become slow. Moreover using routers, multiple
computers can share the network for which the router undergoes a situation known
as '' Connection Wait ''. This possibly slows the connection more.
2. Cost : Routers are costly more than any other networking devices.
3. Implementation : A typical router requires lots of initial configurations and NAT
to setup. And also even for the simplest connection there should be a private IP
address assigned. If there are more services enabled it needs more configurations
as well. This in essence creates more complications in the setup.
4. Bandwidth Shortage : Dynamic routing techniques are used by the routers for the
communication purposes. This potentially causes more networking overheads.
Networking overheads consume large amount of bandwidths resulting in
bandwidth shortages. Additionally for maintaining routing tables, routers regularly
update on the network. This too can cause bandwidth consumption.
4. Bridge :
A network bridge is a device that divides a network into segments. Each segment
represent a separate collision domain, so the number of collisions on the network is
reduced. Each collision domain has its own separate bandwidth, so a bridge also
improves the network performance. A bridge works at the Data link layer (Layer 2) of
the OSI model. It inspects incoming traffic and decide whether to forward it or filter
it. Each incoming Ethernet frame is inspected for destination MAC address. If the
bridge determines that the destination host is on another segment of the network, it
forwards the frame to that segment.
Definition : A bridge is a repeater, with add on the functionality of filtering content
by reading the MAC addresses of source and destination. It is also used for
interconnecting two LANs working on the same protocol. It has a single input and
single output port, thus making it a 2-port device.
Picture : Logical Symbol :
Networking Diagram :
Working :
A network bridge device is primarily used in local area networks because they
can potentially flood and clog a large network thanks to their ability to broadcast data
to all the nodes if they don’t know the destination node's MAC address. A bridge uses
a database to ascertain where to pass, transmit or discard the data frame.
1. If the frame received by the bridge is meant for a segment that resides on the same
host network, it will pass the frame to that node and the receiving bridge will then
discard it.
2. If the bridge receives a frame whose node MAC address is of the connected
network, it will forward the frame toward it.
The various types of bridges are :
1. Transparent Bridge : A transparent bridge is invisible to the other devices on the
network. Transparent bridges perform only the function of blocking or forwarding
data based on the MAC address; the devices on the network are oblivious to these
bridges’ existence. Transparent bridges are by far the most popular types of
bridges.
2. Translational Bridge : A translational bridge can convert from one networking
system to another. It translates the data it receives. Translational bridges are useful
for connecting two different networks, such as Ethernet and Token Ring networks.
Depending on the direction of travel, a translational bridge can add or remove
information and fields from the frame as needed.
3. Source-Route Bridge : Source-route Bridge is one type of technique used for
Token Ring networks and it is designed by IBM. In this bridge, the total frame
route is embedded in one frame. So that it allows the bridge to make precise
decisions of how the frame is forwarding using the network. By using this
method, two similar network segments are connected to the data link layer. It can
be done in a distributed way wherever end-stations join within the bridging
algorithm.
Application of Bridges :
1. This networking device is used for dividing local area networks into several
segments.
2. It is used to store the address of MAC in PC used in a network and also used for
diminishing the network traffic.
Advantages of Bridges :
1. Bridges can extend a network by acting as a repeater
2. Bridges can reduce network traffic on a segment by subdividing network
communications
3. Bridges increase the available bandwidth to individual nodes because fewer nodes
share a collision domain
4. Bridges reduce collisions
5. Some bridges connect networks using different media types and architectures.
Disadvantages of Bridges :
1. Because bridges do more than repeaters by viewing MAC addresses, the extra
processing makes them slower than repeaters - and hubs.
2. Bridges forward broadcast frames indiscriminately, so they do not filter broadcast
traffic.
3. Bridges are more expensive than repeaters and hubs.
5. Repeaters :
A repeater operates at the physical layer. Its job is to regenerate the signal
over the same network before the signal becomes too weak or corrupted so as to
extend the length to which the signal can be transmitted over the same network. A
repeater is implemented in computer networks to expand the coverage area of the
network, repropagate a weak or broken signal and or service remote nodes.
Definition : A repeater is a network device that retransmits a received signal with
more power and to an extended geographical or topological network boundary than
what would be capable with the original signal.
Picture : Logical Symbol :
Networking Diagram :
Working :
The repeaters are the network devices that retransmit the data and directs the
signals for weak network access locations. As the sender sends the signals, on
reaching the repeater it gets weakened , the repeater boosts the signal and forwards it
towards the receiver. The Data transmission and receiving of the data have different
frequencies for both sender and receiver sides. The Repeater works when the sender’s
frequency and the receiver’s frequencies are matched. The data transmitted from a
sender to the receptor is called an uplink while the receptor that retransmits the same
data in the downward direction and is sent to the receiver is called a downlink.
Types of Repeaters :
According to the types of signals that they regenerate, repeaters can be classified into
two categories −
Analog Repeaters − They can only amplify the analog signal.
Digital Repeaters − They can reconstruct a distorted signal.
According to the types of networks that they connect, repeaters can be categorized
into two types −
Wired Repeaters − They are used in wired LANs.
Wireless Repeaters − They are used in wireless LANs and cellular networks.
According to the domain of LANs they connect, repeaters can be divided into two
categories −
Local Repeaters − They connect LAN segments separated by small distance.
Remote Repeaters − They connect LANs that are far from each other.
Applications of Repeater :
1. Repeaters are used to establish Ethernet network.
2. Repeaters are used to get signals from optical fibers, copper cables and coaxial
cables.
3. The repeaters have been developed to perform more important uses such as to
regenerate the microwaves from a satellite; such repeaters are named as
transponders.
Advantages of Repeaters :
1. Repeaters are simple to install and can easily extend the length or the coverage
area of networks.
2. They are cost effective.
3. Repeaters don’t require any processing overhead. The only time they need to be
investigated is in case of degradation of performance.
4. They can connect signals using different types of cables.
Disadvantages of Repeaters :
1. Repeaters cannot connect dissimilar networks.
2. They cannot differentiate between actual signal and noise, and thus boost the
noise if present.
3. They cannot reduce network traffic or congestion.
4. Most networks have limitations upon the number of repeaters that can be
deployed.
6. Gateways :
Network gateways, known as protocol translation gateways or mapping
gateways, can perform protocol conversions to connect networks with different
network protocol technologies. For example, a network gateway connects an office or
home internet to the Internet. If an office or home computer user wants to load a web
page, at least two network gateways are accessed—one to get from the office or home
network to the Internet and one to get from the Internet to the computer that serves the
web page.
Definition :
A gateway is a hardware device that acts as a "gate" between two networks. It
may be a router, firewall, server, or other device that enables traffic to flow in and out
of the network.
Picture : Logical Symbol :
Networking Diagram :
Working :
Gateways are often associated with both Routers and Switches. A Router
routes the data packets(arriving at the gateway) to the correct node in the destination
network. While a switch specifies the actual path of the data in and out of the
gateway. In general, a gateway expands the router's functionality by performing data
translation and protocol conversion.
A gateway mostly uses a packet switching technique to transmit data from one
network to another. A gateway mainly works on IP(Internet Protocol) Addresses for
dissimilar network communication. When a data packet arrives at the gateway, it first
checks the header information. After checking the destination IP address and any kind
of errors in the data packets. It performs data translation and protocol conversion of
the data packet as per the destination network needs. Finally, it forwards the data
packet to the destination IP address by setting up a specific transmission path for the
packet.
Types of Gateways :
1. Unidirectional Gateways − They allow data to flow in only one direction.
Changes made in the source node are replicated in the destination node, but not
vice versa. They can be used as archiving tools.
2. Bidirectional Gateways − They allow data to flow in both directions. They can
be used as synchronization tools.
Applications of Gateways :
1. Main application is to connect users to the Internet.
2. In enterprise networks, a network gateway usually also acts as a proxy server and
a firewall.
Advantages of Gateways :
1. It can connect the devices of two different networks having dissimilar structures.
2. It is an intelligent device with filtering capabilities.
3. It has control over both collisions as well as a broadcast domain.
4. It uses a full-duplex mode of communication.
5. It has the fastest data transmission speed amongst all network connecting devices.
6. It can perform data translation and protocol conversion of the data packet as per
the destination network's need.
7. It can encapsulate and decapsulate the data packets.
8. It has improved security than any other network connecting device.
Disadvantages of Gateways :
1. It is complex to design and implement.
2. The implementation cost is very high.
3. It requires a special system administration configuration.
• Networking Topologies :
Network topology refers to the manner in which the links and nodes of a
network are arranged to relate to each other. The ideal network topology depends on
each business’s size, scale, goals, and budget. A network topology diagram helps
visualize the communicating devices, which are modelled as nodes, and the
connections between the devices, which are modelled as links between the nodes.
• Types of Networking Topologies :
1. Bus Topology.
2. Star Topology.
3. Ring Topology.
4. Mesh Topology.
5. Tree Topology.
6. Hybrid Topology.
1. Bus Topology :
Alternatively referred to as line topology, bus topology is a network setup
where each computer and network device is connected to a single cable or backbone.
Depending on the type of computer network card, a coaxial cable or an RJ-45 network
cable is used to connect them together.
Features :
1. A bus topology consists of a main run of cable with a terminator at each end.
2. All nodes like workstations, printers, laptops, servers etc., are connected to the
linear cable.
3. The connectors used in the bus topology include BNC and T connectors.
4. The terminator is used to absorb the signal when the signal reaches the end,
preventing signal bounce.
Architecture :
Conclusion :
Networking devices are hardware devices used to connect other devices in a network.
Hubs are most basic and cheap, but they only broadcast data in a LAN. Switches are
intelligent and unicast data in a LAN, but are expensive. Bridges are used to connect two
LAN’s and reduce network traffic, but are unable to filter broadcast traffic. Routers are the
intelligent networking device, they are used to connect LAN’s & WAN’s and manage
network traffic through routing tables which are updated dynamically. Though they are
expensive as compared to others, they are reliable. Repeaters are used to boost signals so as
to increase length of transmission but in process they boost noise too. Gateways are
intelligent networking device used to communicate between two dissimilar networks.
Networking topologies refer to manner in which nodes of network are connected. Bus
topology is the simplest but cable failure leads to entire system failure. Star topology is the
best suited as it is not as expensive as other topologies and failure of cable doesn’t lead to
system failure. Ring topology performs better for traffic management but failure of cable
leads to system failure. Mesh topology provides point to point connection but is very
expensive. Tree topology is integration of Bus & Star topology, it is highly scalable but
difficult to configure. Hybrid topology is combination of any of the topology but design is
complex and is expensive.
Networking Devices & Topologies are selected on the basis of requirements, budget,
reliability and future expansion needed by the user or organization.
Experiment No 2.
2. ipconfig -all :
ipconfig -all, gives you the status, IP address information, DNS server
information, MAC address, about every adapter installed on your machine, to include
things like VPN adapters, WiFi, Bluetooth, and pretty much anything else that is
listed as a network adapter.
Output :
3. arp -a : arp -a [inet_addr] [-N if_addr] [-v]
Displays current ARP entries by interrogating the current protocol data. If
inet_addr is specified, the IP and Physical addresses for only the specified computer
are displayed. If more than one network interface uses ARP, entries for each ARP
table are displayed.
-v : Displays current ARP entries in verbose mode.
inet_addr : Specifies an internet address.
-N if_addr : Displays the ARP entries for the network interface specified by if_addr.
Output :
4. 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.
Output :
5. netstat -an :
In computing, netstat -an is a command-line network utility that displays
network connections for combination of Transmission Control Protocol(TCP) and
User Data Protocol(UDP).
-a : Displays all active TCP connections and the TCP and UDP ports on which the
computer is listening.
-n : Displays active TCP connections, however, addresses and port numbers are
expressed numerically and no attempt is made to determine names.
Output :
6. ping(id/website) :
Verifies IP-level connectivity to another TCP/IP computer by sending Internet
Control Message Protocol (ICMP) echo Request messages. The receipt of
corresponding echo Reply messages are displayed, along with round-trip times. ping
is the primary TCP/IP command used to troubleshoot connectivity, reachability, and
name resolution. Used without parameters, this command displays Help content. You
can also use this command to test both the computer name and the IP address of the
computer. We can ping either by ipaddress or by provide website name.
Output :
7. ping -t(id/website) :
It is similar to ping. ping -t specifies ping to continue sending echo Request
messages to the destination until interrupted. To interrupt and display statistics, press
CTRL+ENTER. To interrupt and quit this command, press CTRL+C. Similar to ping,
ping -t can be done either by ipaddress or website name.
Output :
8. pathping(id/website) :
Provides information about network latency and network loss at intermediate
hops between a source and destination. This command sends multiple echo Request
messages to each router between a source and destination, over a period of time, and
then computes results based on the packets returned from each router. Because this
command displays the degree of packet loss at any given router or link, you can
determine which routers or subnets might be having network problems. Used without
parameters, this command displays help. pathping can be done either by ipaddress or
website name.
Output :
9. nslookup :
Displays information that you can use to diagnose Domain Name System
(DNS) infrastructure. The nslookup command-line tool is available only if you have
installed the TCP/IP protocol.
Output :
Conclusion :
Thus, we have studied and implemented some of the various networking commands.
ipconfig gives us ipv4 & ipv6 addresses, subnet mask and default gateway for all adapters.
ipconfig -all gives all details of ipconfig, in addition it gives MAC address as well as various
details for all adapters. arp gives ARP entries for all connected networks. netstat gives all
active TCP connections whereas netstat -an gives all TCP connections as well as the TCP &
UDP ports on which computer is listening. ping checks the connectivity whereas ping -t
checks connectivity by sending echo packets infinitely. pathping provides the no of devices
between the source and destination. nslookup provides us with the DNS addresses. All these
commands are very important for networking statistics.
Experiment No 3.
Aim : To implement CRC and hamming code as error detection and correction codes.
Theory :
When data is transmitted from one device to another device, the system does not
guarantee whether the data received by the device is identical to the data transmitted by
another device. An Error is a situation when the message received at the receiver end is not
identical to the message transmitted. Error leads to inconsistency in data transmission,
therefore it is necessary to detect errors and take appropriate steps. There are various ways to
detect errors. Some of them are as follows :
1. Cyclic Redundancy Check (CRC) :
CRC is an error detection technique. In CRC, a sequence of redundant bits, called
cyclic redundancy check bits, are appended to the end of data unit. The no of redundant bits
is one less than the length of the predetermined generator function. The redundant bits are
initialized to 0 and Modulo 2 division is performed between the data concatenated with
redundant bits and the predetermined generator function. The remainder of this division
replaces the appended 0’s to the data and the data is sent to the receiver.
At the receivers end, the data received performs modulo 2 division with the same
predetermined generator function of the sender. If the remainder of this division is 0, it
indicates that the data received is error free. However any other remainder indicates that the
data has been corrupted and tells the sender to retransmit the data. Error correction is not
done in CRC.
Example :
Consider the above example, where the data to be sent is 1010000 and the generator
function is x3+1 which is 1001. Since length of generator function is 4, 3 redundant bits (n-1)
initialized to 0 are added to the data. Then Modulo 2 division is performed between data and
generator function. The remainder obtained is 011 which is then replaced with the earlier
appended 0’s and the data (1010000011) is sent to the receiver.
At the receiver end, the data received is 1010000011, this data performs Modulo 2
division with the same generator function 1001. The remainder obtained after division is 000,
which indicates that the data received is error free and the data is extracted by removing the
redundant bits. Thus the data extracted at receiving end is 1010000.
Code :
import java.util.Scanner;
class CRC
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("\n***SENDERS SIDE***");
System.out.print("\nEnter data to be sent : ");
String datastream = sc.nextLine();
System.out.print("\nEnter generator function : ");
String generator = sc.nextLine();
int data[] = new int[datastream.length() + generator.length()-1];
int divisor[] = new int[generator.length()];
for(int i=0;i<datastream.length();i++)
{
data[i] = Integer.parseInt(datastream.charAt(i)+"");
}
for(int i=0;i<generator.length();i++)
{
divisor[i] = Integer.parseInt(generator.charAt(i)+"");
}
//padding 0 at end
for(int i=datastream.length();i<data.length;i++)
{
data[i]=0;
}
//Calculate CRC
for(int i=0;i<datastream.length();i++)
{
if(data[i]==1)
{
for(int j=0;j<divisor.length;j++)
{
data[i+j] ^= divisor[j];
}
}
}
//Display CRC
System.out.print("\nCRC code calculated is: ");
for(int i=datastream.length();i<data.length;i++)
{
System.out.print(data[i]);
}
System.out.print("\n\nThe data being sent is: ");
for(int i=0;i<datastream.length();i++)
{
data[i] = Integer.parseInt(datastream.charAt(i)+"");
}
for(int i=0;i<data.length;i++)
{
System.out.print(data[i]);
}
System.out.println("\n\n***RECEIVERS SIDE***");
System.out.print("\nEnter Received CRC code:");
datastream = sc.nextLine();
System.out.print("\nEnter generator: ");
generator = sc.nextLine();
data = new int[datastream.length() + generator.length()-1];
divisor = new int[generator.length()];
for(int i=0;i<datastream.length();i++)
{
data[i] = Integer.parseInt(datastream.charAt(i)+"");
}
for(int i=0;i<generator.length();i++)
{
divisor[i] = Integer.parseInt(generator.charAt(i)+"");
}
//Calculation of remainder
for(int i=0;i<datastream.length();i++)
{
if(data[i]==1)
{
for(int j=0;j<divisor.length;j++)
{
data[i+j] ^= divisor[j];
}
}
}
System.out.print("\nRemainder is: ");
for(int i=datastream.length();i<data.length;i++)
{
System.out.print(data[i]);
}
//Display validity of data
boolean flag = true;
for(int i=datastream.length();i<data.length;i++)
{
if(data[i]==1)
{
flag = false;
break;
}
}
if(flag==true)
System.out.println("\n\nData stream is valid");
else
System.out.println("\n\nData stream is invalid");
sc.close();
}
}
Output :
2. Hamming Code :
Hamming code is a block code that is capable of detecting up to two simultaneous bit
errors and correcting single-bit errors. In this coding method, the source encodes the message
by inserting redundant bits within the message. These redundant bits are extra bits that are
generated and inserted at specific positions in the message itself to enable error detection and
correction.
At senders end. The no of parity bits are calculated from the following formula : 2P
>= P+m+1, where P is no of parity bits and m is the no of data bits. The parity bits are placed
at positions of power of 2 and the data bits in remaining positions from LSB to MSB. There
are 2 types of parities : even and odd. In even parity the no of 1’s are even whereas in odd
parity the no of 1’s are odd. The parity bits are calculated as follows : P1 is calculated by
checking 1 bit and skipping 1 bit starting from bit 1. P2 is calculated by checking 2 bits and
skipping 2 bits starting from bit 2 and so on every parity bit is calculated. The data stuffed
with parity bits is sent to the receiver.
The receiver checks the received parity from the same logic i.e., For Pi checking i bits
and skipping i bits starting from bit i. If all the parity bits are 0, then the received data is error
free. However if any parity bit is 1, the combination of parity bit calculated is converted to
decimal equivalent and the decimal equivalent bit is inverted to correct the data. The data is
extracted by skipping the parity bits from the received data.
Example :
Let us encode 11001 into even parity hamming code.
Given, number of data bits, m =5.
To find the number of redundant bits,
Let us try P=4.
24 >= 5+4+1
The equation is satisfied and so 4 redundant bits are selected.
So, total code bit = m + P = 9
The redundant bits are placed at bit positions 1, 2, 4 and 8.
Bit location table is as follows :
Bit Location 9 8 7 6 5 4 3 2 1
Bit designation D5 P4 D4 D3 D2 P3 D1 P2 P1
Information bits 1 1 0 0 1
Parity bits 1 1 0 1
For P1: Bit locations 3, 5, 7 and 9 have three 1s. To have even parity, P1 must be 1.
For P2: Bit locations 3, 6, 7 have two 1s. To have even parity, P2 must be 0.
For P3: Bit locations 5, 6, 7 have one 1s. To have even parity, P3 must be 1.
For P4: Bit locations 8, 9 have one 1s. To have even parity, P2 must be 1.
Thus the encoded 9-bit hamming code is 111001101.
Let us assume the even parity hamming code received is (110001101). Now from the
received code, let us detect and correct the error.
To detect the error, let us construct the bit location table.
Bit Location 9 8 7 6 5 4 3 2 1
Bit designation D5 P4 D4 D3 D2 P3 D1 P2 P1
Received code 1 1 0 0 0 1 1 0 1
For P1 : Check the locations 1, 3, 5, 7, 9. There is three 1s in this group, which is wrong for
even parity. Hence the bit value for P1 is 1.
For P2 : Check the locations 2, 3, 6, 7. There is one 1 in this group, which is wrong for even
parity. Hence the bit value for P2 is 1.
For P3 : Check the locations 3, 5, 6, 7. There is one 1 in this group, which is wrong for even
parity. Hence the bit value for P3 is 1.
For P4 : Check the locations 8, 9. There are two 1s in this group, which is correct for even
parity. Hence the bit value for P4 is 0.
Since all parity bits are not equal to 0. Therefore, received data has error. To correct error the
parity bits are placed from MSB to LSB, right to left.
P4 P3 P2 P1
0 1 1 1
The resultant binary word is 0111. It corresponds to the bit location 7 in the above table. The
error is detected in the data bit D4. Therefore 7th bit is inverted and changed to 1 and
corrected hamming code is 111001101. Data is extracted by removing parity bits and data
obtained is 11001.
Code :
import java.util.*;
class Hamming
{
static int noOfParityBits(int length)
{
int i;
for(i=0;i<length;i++)
{
if((int)(Math.pow(2, i)) >= i+length+1)
break;
}
return i;
}
static int calculateParity(int code[],int pbit_no)
{
int parity=0;
for(int i=((int)(Math.pow(2, pbit_no)))-1;i<code.length;i++)
{
String s = Integer.toBinaryString(i+1);
//To check bits required for calculation of value of parity
if(((Integer.parseInt(s))/((int)(Math.pow(10,
pbit_no))))%10==1)
{
if(code[i]==1)
{
parity=(parity+1)%2;
}
}
}
return parity;
}
static int[] generateHammingCode(int data[])
{
int r_bits = noOfParityBits(data.length);
int code[]=new int[data.length+r_bits];
int j=0,k=0;
for(int i=1;i<=code.length;i++)
{
if((int)(Math.pow(2, j)) == i)
{
code[i-1]=0; //Initializing Parity Bits to 0
j++;
}
else
{
code[k+j]=data[k];
k++;
}
}
for(int i=0;i<r_bits;i++)
{
code[((int)(Math.pow(2, i)))-1]=calculateParity(code,i);
}
return code;
}
static void errorCorrection(int code[])
{
int parity[] = new int[10];
String binaryErrorCode = "";
int i;
int pbit=0;
for(i=1;i<=code.length;i++)
{
if(((int)(Math.pow(2, pbit)))==i)
{
for(int j=((int)(Math.pow(2, pbit)))-1;j<code.length;j++)
{
String s = Integer.toBinaryString(j+1);
//To check bits required for calculation of value of
parity
if(((Integer.parseInt(s))/((int)(Math.pow(10,
pbit))))%10==1)
{
if(code[j]==1)
{
parity[pbit]=(parity[pbit]+1)%2;
}
}
}
binaryErrorCode=parity[pbit]+binaryErrorCode;
pbit++;
}
}
int location = Integer.parseInt(binaryErrorCode,2);
if(location != 0)
{
System.out.println("\nError is at location : " + location);
code[location-1]=(code[location-1]+1)%2;
System.out.println("\nCorrected Hamming Code : ");
for(i=code.length-1;i>=0;i--)
{
System.out.print(code[i]);
}
}
else
{
System.out.println("\nHamming Code has no Errors.");
}
System.out.println("\n\nExtracted data from Received Hamming Code
: ");
for(i=code.length;i>0;i--)
{
if(((int)(Math.pow(2, pbit-1))) != i)
{
System.out.print(code[i-1]);
}
else
{
pbit--;
}
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("------SENDER'S END------");
System.out.println("Enter data to be sent : ");
String datastream = sc.nextLine();
int data[] = new int[datastream.length()];
for(int i = 0;i<datastream.length();i++)
{
data[i]=Integer.parseInt(datastream.charAt(datastream.length()
-i-1)+""); //Taken in reverse order
}
int code[] = generateHammingCode(data);
System.out.println("\nCalculated Hamming Code : ");
for(int i=code.length-1;i>=0;i--)
{
System.out.print(code[i]);
}
System.out.println("\n\n------RECEIVER'S END------");
System.out.println("Enter received code : ");
String received = sc.nextLine();
int recCode[] = new int[received.length()];
for(int i = 0;i<received.length();i++)
{
recCode[i]=Integer.parseInt(received.charAt(received.length()-
i-1)+"");
}
errorCorrection(recCode);
sc.close();
}
}
Output :
Conclusion :
Cyclic Redundancy Check is the most efficient technique for error detection. It
detects single as well as multiple bit errors with the help of Modulo 2 division. However it
cannot correct errors. Hamming Code can detect single bit as well as 2 simultaneous bit
errors. Also it can correct single bit error with the help of parity bits. It fails when it comes to
multiple bit errors.
Experiment No 4.
Aim : To Study & implement Dijkstra’s Algorithm & Distance Vector Routing.
Theory :
A routing algorithm is a procedure that lays down the route or path to transfer data
packets from source to the destination. They help in directing Internet traffic efficiently. After
a data packet leaves its source, it can choose among the many different paths to reach its
destination. Routing algorithm mathematically computes the best path, i.e. “least – cost path”
that the packet can be routed through. Routing algorithms can be broadly categorized into
two types, adaptive (dynamic) and nonadaptive (static) routing algorithms.
1. Dijkstra’s Algorithm :
Dijkstra’s Algorithm is an algorithm for finding the shortest paths between nodes in a
graph. For a given source node in the graph, the algorithm finds the shortest path between
that node and every other. It can also be used for finding the shortest paths from a single node
to a single destination node by stopping the algorithm once the shortest path to the destination
node has been determined. It is non adaptive (static).
Algorithm :
1. Mark all nodes unvisited. Create a set of all the unvisited nodes called the unvisited set.
2. Assign to every node a tentative distance value: set it to zero for our initial node and to
infinity for all other nodes. Set the initial node as current.
3. For the current node, consider all of its unvisited neighbours and calculate their tentative
distances through the current node. Compare the newly calculated tentative distance to
the current assigned value and assign the smaller one.
4. When we are done considering all of the unvisited neighbours of the current node, mark
the current node as visited and remove it from the unvisited set. A visited node will never
be checked again.
5. If all nodes are marked visited then the algorithm terminates.
6. Otherwise, select the unvisited node that is marked with the smallest tentative distance,
set it as the new "current node", and go back to step 3.
Example :
Consider the following graph and find the shortest path to all nodes considering S as the
starting node :
Step 1 :
The following two sets are created-
Unvisited set : {S , a , b , c , d , e}
Visited set : { }
Step 2 :
The two variables Π (parent) and d (distance) are created for each vertex and initialized as-
Π[S] = Π[a] = Π[b] = Π[c] = Π[d] = Π[e] = NIL
d[S] = 0
d[a] = d[b] = d[c] = d[d] = d[e] = ∞
Step 3 :
Vertex ‘S’ is chosen. This is because shortest path estimate for vertex ‘S’ is least. The
outgoing edges of vertex ‘S’ are relaxed.
Now, d[S] + 1 = 0 + 1 = 1 < ∞ thus, d[a] = 1 and Π[a] = S
d[S] + 5 = 0 + 5 = 5 < ∞ thus, d[b] = 5 and Π[b] = S
Now, the sets are updated as-
Unvisited set : {a , b , c , d , e}
Visited set : {S}
Step 4 :
Vertex ‘a’ is chosen. This is because shortest path estimate for vertex ‘a’ is least. The
outgoing edges of vertex ‘a’ are relaxed.
Now, d[a] + 2 = 1 + 2 = 3 < ∞ thus, d[c] = 3 and Π[c] = a
d[a] + 1 = 1 + 1 = 2 < ∞ thus, d[d] = 2 and Π[d] = a
d[b] + 2 = 1 + 2 = 3 < 5 thus, d[b] = 3 and Π[b] = a
Now, the sets are updated as-
Unvisited set : {b , c , d , e}
Visited set : {S , a}
Step 5 :
Vertex ‘d’ is chosen. This is because shortest path estimate for vertex ‘d’ is least. The
outgoing edges of vertex ‘d’ are relaxed.
Now, d[d] + 2 = 2 + 2 = 4 < ∞ thus, d[e] = 4 and Π[e] = d
Now, the sets are updated as-
Unvisited set : {b , c , e}
Visited set : {S , a , d}
Step 6 :
Vertex ‘b’ is chosen. This is because shortest path estimate for vertex ‘b’ is least. Vertex ‘c’
may also be chosen since for both the vertices, shortest path estimate is least. The outgoing
edges of vertex ‘b’ are relaxed.
Now, d[b] + 2 = 3 + 2 = 5 > 2 thus, No change in d[d]
Now, the sets are updated as-
Unvisited set : {c , e}
Visited set : {S , a , d , b}
Step 7 :
Vertex ‘c’ is chosen. This is because shortest path estimate for vertex ‘c’ is least. The
outgoing edges of vertex ‘c’ are relaxed.
Now, d[c] + 1 = 3 + 1 = 4 = 4 thus, No change in d[e]
Now, the sets are updated as-
Unvisited set : {e}
Visited set : {S , a , d , b , c}
Step 8 :
Vertex ‘e’ is chosen. This is because shortest path estimate for vertex ‘e’ is least. The
outgoing edges of vertex ‘e’ are relaxed. There are no outgoing edges for vertex ‘e’.
Therefore no change.
Now, the sets are updated as-
Unvisited set : { }
Visited set : {S , a , d , b , c , e}
Now, All vertices of the graph are processed. The final shortest path of all nodes are
represented as :
Code :
import java.util.*;
class Djikstra
{
static void djikstra(int cost[][], int s, int V, int d)
{
int dist[] = new int[V];
boolean visited[] = new boolean[V];
int par[] = new int[V];
for (int i = 0; i < V; i++)
{
dist[i] = Integer.MAX_VALUE;
visited[i] = false;
}
dist[s] = 0;
for (int i = 0; i < V - 1; i++)
{
int u = minimum(dist, visited, V);
visited[u] = true;
for (int v = 0; v < V; v++)
{
if (!visited[v] && cost[u][v] != 0 && dist[u] + cost[u][v]
< dist[v])
{
dist[v] = dist[u] + cost[u][v];
par[v]=u;
}
}
}
System.out.println("\nStarting node:"+ s);
System.out.println("\nDestination node:" + d);
System.out.println("\nMinimum Cost of destination from starting
node:"+ dist[d]);
System.out.print("\nPath to reach destination: ");
System.out.print(d);
int k=d;
while(k != s)
{
System.out.print("<-"+par[k]);
k=par[k];
}
}
public static int minimum(int dist[], boolean visited[], int V)
{
int min = Integer.MAX_VALUE, index = -1;
for (int v = 0; v < V; v++)
{
if (visited[v] == false && dist[v] < min)
{
min = dist[v];
index = v;
}
}
return index;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("\nEnter no. of nodes:");
int V = sc.nextInt();
int cost[][] = new int[V][V];
System.out.println("\nEnter adjacency matrix: ");
for (int i = 0; i < V; i++)
{
for (int j = 0; j < V; j++)
{
cost[i][j] = sc.nextInt();
}
}
System.out.print("\nEnter the starting node:");
int s = sc.nextInt();
System.out.print("\nEnter the destination node:");
int d = sc.nextInt();
djikstra(cost, s, V , d);
sc.close();
}
}
Output :
Applications :
1. Digital Mapping Services in Google Maps: Many times we have tried to find the
distance in G-Maps, from one city to another, or from your location to the nearest desired
location. There encounters the Shortest Path Algorithm, as there are various routes/paths
connecting them but it has to show the minimum distance, so Dijkstra’s Algorithm is used
to find the minimum distance between two locations along the path.
2. Social Networking Applications: In many applications you might have seen the app
suggests the list of friends that a particular user may know. How do you think many
social media companies implement this feature efficiently, especially when the system
has over a billion users. The standard Dijkstra algorithm can be applied using the shortest
path between users measured through handshakes or connections among them. When the
social networking graph is very small, it uses standard Dijkstra’s algorithm along with
some other features to find the shortest paths, and however, when the graph is becoming
bigger and bigger, the standard algorithm takes a few several seconds to count and
alternate advanced algorithms are used.
3. Telephone Network: As we know, in a telephone network, each line has a bandwidth,
‘b’. The bandwidth of the transmission line is the highest frequency that that line can
support. Generally, if the frequency of the signal is higher in a certain line, the signal is
reduced by that line. Bandwidth represents the amount of information that can be
transmitted by the line. If we imagine a city to be a graph, the vertices represent the
switching stations, and the edges represent the transmission lines and the weight of the
edges represents ‘b’. So as you can see it can fall into the category of shortest distance
problem, for which the Dijkstra is can be used.
4. IP routing to find Open shortest Path First: Open Shortest Path First (OSPF) is a link-
state routing protocol that is used to find the best path between the source and the
destination router using its own Shortest Path First. Dijkstra’s algorithm is widely used in
the routing protocols required by the routers to update their forwarding table. The
algorithm provides the shortest cost path from the source router to other routers in the
network.
5. Flighting Agenda: For example, If a person needs software for making an agenda of
flights for customers. The agent has access to a database with all airports and flights.
Besides the flight number, origin airport, and destination, the flights have departure and
arrival time. Specifically, the agent wants to determine the earliest arrival time for the
destination given an origin airport and start time. There this algorithm comes into use.
6. Designate file server: To designate a file server in a LAN(local area network), Dijkstra’s
algorithm can be used. Consider that an infinite amount of time is required for
transmitting files from one computer to another computer. Therefore to minimize the
number of “hops” from the file server to every other computer on the network the idea is
to use Dijkstra’s algorithm to minimize the shortest path between the networks resulting
in the minimum number of hops.
7. Robotic Path: Nowadays, drones and robots have come into existence, some of which
are manual, some automated. The drones/robots which are automated and are used to
deliver the packages to a specific location or used for a task are loaded with this algorithm
module so that when the source and destination is known, the robot/drone moves in the
ordered direction by following the shortest path to keep delivering the package in a
minimum amount of time.
2. Distance Vector Routing :
A distance-vector routing protocol in data networks determines the best route for data
packets based on distance. Distance-vector routing protocols measure the distance by the
number of routers a packet has to pass, one router counts as one hop. Some distance-vector
protocols also take into account network latency and other factors that influence traffic on a
given route. It is adaptive (dynamic).
Algorithm :
1. A router transmits its distance vector to each of its neighbours in a routing packet. Each
router receives and saves the most recently received distance vector from each of its
neighbours.
2. A router recalculates its distance vector when:
i. It receives a distance vector from a neighbor containing different
information than before.
ii. It discovers that a link to a neighbor has gone down.
The DV calculation is based on minimizing the cost to each destination
Dx(y) = Estimate of least cost from x to y
C(x,v) = Node x knows cost to each neighbor v
Dx = [Dx(y): y ∈ N ] = Node x maintains distance vector
Node x also maintains its neighbors' distance vectors
– For each neighbor v, x maintains Dv = [Dv(y): y ∈ N ]
3. From time-to-time, each node sends its own distance vector estimate to neighbors.
4. When a node x receives new DV estimate from any neighbor v, it saves v’s distance
vector and it updates its own DV using equation:
Dx(y) = min { C(x,v) + Dv(y), Dx(y) } for each node y ∈ N
Example :
Consider the following graph :
A 0 1 3 ∞
B 1 0 1 1
C 3 1 0 4
D ∞ 1 4 0
0 1 3 ∞
Routing Table for A via B :
2 1 2 2
Routing Table for A via C :
6 4 3 7
Routing Table for A via D :
∞ ∞ ∞ ∞
New Routing Table for A :
0 1 2 2
via A via B via B via B
The new routing table changes as and when the information has changed from the
previous time or the neighbour has gone down. Thus the table gets updated dynamically.
Code :
import java.util.*;
public class DVR
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("\nEnter the no. of nodes:");
int numberOfNodes = sc.nextInt();
char nodes[] = new char[numberOfNodes];
System.out.print("\nEnter the nodes:");
for(int i=0;i<numberOfNodes;i++)
{
nodes[i]=sc.next().charAt(0);
}
System.out.print("\nEnter the node for which the new routing table
is required to be generated:");
char genNode = sc.next().charAt(0);
int genNodeIndex = 0;
for(int i=0;i<numberOfNodes;i++)
{
if(nodes[i]==genNode)
{
genNodeIndex=i;
break;
}
}
System.out.print("\nEnter the number of neighbors of " + genNode +
" : ");
int noOfNeighbors = sc.nextInt();
char neighbors[] = new char[noOfNeighbors];
System.out.print("\nEnter Neighbours of required " +genNode+ "
node: ");
for(int i=0;i<noOfNeighbors;i++)
{
neighbors[i] = sc.next().charAt(0);
}
int[][] costTableOfNeighbor = new
int[noOfNeighbors][numberOfNodes];
Random rand = new Random();
for(int i=0;i<noOfNeighbors;i++)
{
for(int j=0;j<numberOfNodes;j++)
{
if(nodes[j]==neighbors[i])
{
costTableOfNeighbor[i][j]=0;
}
else
{
costTableOfNeighbor[i][j]=rand.nextInt(100)+1;
}
}
}
int distanceOfNeighbor[]=new int[noOfNeighbors];
for(int i=0;i<noOfNeighbors;i++)
{
System.out.print("\nEnter Distance of node "+neighbors[i]+"
from "+genNode+":");
distanceOfNeighbor[i]=sc.nextInt();
}
System.out.println();
for(int i=0;i<noOfNeighbors;i++)
{
costTableOfNeighbor[i][genNodeIndex]=distanceOfNeighbor[i];
}
int generatedTable[] = new int[numberOfNodes];
char via[] = new char[numberOfNodes];
for(int i=0;i<numberOfNodes;i++)
{
if(i==genNodeIndex)
{
generatedTable[i]=0;
via[i]=genNode;
}
else
{
int minCost = Integer.MAX_VALUE;
for(int j=0;j<noOfNeighbors;j++)
{
if(minCost>(distanceOfNeighbor[j]+costTableOfNeighbor[
j][i]))
{
minCost=distanceOfNeighbor[j]+costTableOfNeighbor[
j][i];
via[i]=neighbors[j];
}
}
generatedTable[i]=minCost;
}
}
System.out.println("Routing cost tables Of neighbour nodes of
"+genNode+":");
for(int i=0;i<noOfNeighbors;i++)
{
System.out.println("Routing table of node "+neighbors[i]+":");
for(int j=0;j<numberOfNodes;j++)
{
System.out.println(nodes[j]+"\t"+costTableOfNeighbor[i][j]
);
}
}
System.out.println();
System.out.println("Generated Routing table for node "
+genNode+":");
for(int j=0;j<numberOfNodes;j++)
{
System.out.println(nodes[j]+"\t"+generatedTable[j]+" via
"+via[j]);
}
}
}
Output :
Application : It is used to route network packets to destination and helps to determine new
paths in case of a node failure so as data packets are not lost.
Conclusion :
Dijkstra Algorithm is a non-adaptive routing algorithm to find shortest path between
the source and destination nodes. Though it provides the shortest path, as it calculates for
each and every node processing time is large and being static it is not efficient compared to
adaptive routing algorithm. Distance Vector Routing is an adaptive routing algorithm, which
periodically updates routing tables and provides the shortest path between the source and
destination. Though it leads to ‘Count to Infinity’ problem it is more efficient than the static
Dijkstra’s Algorithm.
Experiment No 5.
Aim : To Study & implement different framing techniques.
Theory :
In the physical layer, data transmission involves synchronised transmission of bits
from the source to the destination. The data link layer packs these bits into frames. Data-link
layer takes the packets from the Network Layer and encapsulates them into frames. This
process is known as framing. If the frame size becomes too large, then the packet may be
divided into small sized frames. Smaller sized frames makes flow control and error control
more efficient. The various types of framing are as follow:
1. Character Count :
In Character Count, at the senders side, the length of every frame is calculated and
incremented by 1 and is placed at the starting of every frame and sent to the receiver. The
receiver reads the first character and takes it as length of the frame and discards it and then
considers length-1 characters as one frame. Similarly other frames are extracted in the same
manner. The problem with this is, if the character count is distorted by any means the receiver
loses synchronization and thus it is rarely used.
Example :
Consider the frames ‘1234’ and ‘26’ are to be sent. The length of frames are 4 and 2
respectively. Length is incremented by 1 and placed in front of frame. The frame being sent is
: 51234326.
The receiver receives 51234326. It takes the first character as length and discards it.
Length of 1st frame is 5 thus it considers the next 4 characters as Frame 1. Then it encounters
3 and takes it as length of next frame and considers the next 2 characters as Frame 2. Thus the
frames received at receivers end is 1234 and 26.
Diagram :
Code :
import java.util.*;
class CharacterCount
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("\n*****SENDER SIDE*****");
System.out.println("\nEnter the number of frames to be sent : ");
int n = sc.nextInt();
String frames[] = new String[n];
for(int i=0;i<n;i++)
{
System.out.println("\nEnter data for frame " + i + " : ");
frames[i] = sc.next();
}
int k=0; //Code Length
int code[] = new int[100];
for(int i=0;i<n;i++)
{
code[k++] = frames[i].length() + 1;
for(int j=0;j<frames[i].length();j++)
{
code[k++]=Character.getNumericValue(frames[i].charAt(j));
}
}
System.out.println("\nAfter Character Count Framing : ");
for(int i=0;i<k;i++)
{
System.out.print(code[i]);
}
System.out.println("\n\n*****RECEIVER SIDE*****");
System.out.println("\nEnter received Frame : ");
String data = sc.next();
int i=0,flag=1,countOfFrames=0;
String f[] = new String[10];
while(flag==1 && i<data.length())
{
int len = Character.getNumericValue(data.charAt(i));
if(i+len > data.length())
{
System.out.println("\nReceived frame is incorrect");
flag=0;
}
if(flag==1)
{
String s = "";
int j;
for(j=i+1;j<i+len;j++)
{
s+=data.charAt(j);
}
f[countOfFrames++]=s;
i=j;
}
}
if(flag==1)
{
for(int a=0;a<countOfFrames;a++)
{
System.out.println("\nFrame " + a + " : " + f[a]);
}
}
}
}
Output :
2. Byte Stuffing :
Character stuffing is also known as byte stuffing or character-oriented framing and
operates on bytes. In byte stuffing, special byte that is basically known as ESC (Escape
Character) that has predefined pattern is generally added to data section of the data stream or
frame when there is message or character that has same pattern as that of flag byte or if it
encounters the ESC pattern, it stuffs ESC character before the encountered ESC character.
But receiver removes this ESC and keeps next byte as data part. In simple words, we can say
that character stuffing is addition of 1 additional byte if there is presence of ESC or flag in
text.
Example :
Consider the frame, 12$#34. The flag byte is $ whereas the escape byte is #. The sender puts
the flag byte at the start and end of the frame. In data when it counters the ‘$’(flag) byte it
adds an escape byte before it. When it encounters the ‘#’(escape) byte it adds an escape byte
before it and sends $12#$##34$ to receiver.
The receiver on receiving the frame removes the start flag byte and checks for data till
it finds the end flag byte, however when it encounters a flag byte preceded by escape byte it
takes the flag byte as part of data or even when it encounters a escape byte preceded by
escape byte it takes the escape byte as part of data. Thus frame received by the receiver is
12$#34.
Diagram :
Code :
import java.util.*;
class ByteStuffing
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("\n*****SENDER SIDE*****");
System.out.println("\nEnter Flag Byte : ");
char flag = sc.next().charAt(0);
System.out.println("\nEnter Escape Byte : ");
char escape = sc.next().charAt(0);
System.out.println("\nEnter no of frames : ");
int n = sc.nextInt();
String frames[] = new String[n];
for(int i=0;i<n;i++)
{
System.out.println("\nEnter data for frame " + i + " : ");
frames[i] = sc.next();
}
String code = "";
for(int i=0;i<n;i++)
{
code+= flag;
for(int j=0;j<frames[i].length();j++)
{
if(frames[i].charAt(j) == flag || frames[i].charAt(j) ==
escape)
{
code+= "" + escape + "" + frames[i].charAt(j);
}
else
{
code+= frames[i].charAt(j);
}
}
code+= flag;
}
System.out.println("\nAfter Byte Stuffing Framing : " + code);
System.out.println("\n\n*****RECEIVER SIDE*****");
System.out.println("\nEnter received Frame : ");
code = sc.next();
String f[] = new String[10];
int i=0,countOfFrames=0;
while(i<code.length())
{
int count = 0;
String temp = "";
while(count != 2)
{
if(code.charAt(i)==flag)
{
count++;
i++;
}
else if(code.charAt(i) == escape && (code.charAt(i+1) ==
flag || code.charAt(i+1) == escape))
{
temp+= code.charAt(i+1);
i+=2;
}
else
{
temp+= code.charAt(i);
i++;
}
}
f[countOfFrames++]=temp;
}
for(int a=0;a<countOfFrames;a++)
{
System.out.println("\nFrame " + a + " : " + f[a]);
}
sc.close();
}
}
Output :
3. Bit Stuffing :
Bit stuffing is the mechanism of inserting one or more non-information bits into a
message to be transmitted, to break up the message sequence, for synchronization purpose. A
pattern of bits of arbitrary length is stuffed in the message to differentiate from the delimiter.
This is also called bit - oriented framing. In HDLC protocol the delimiter pattern is
01111110, so whenever the sender encounters 5 continuous 1’s it stuffs a 0 bit ahead to
differentiate from the delimiter pattern. On the other hand, when the receiver encounters 5
continuous 1’s it discards the next bit and continues to read data bits.
Example :
Consider the frame 111111 and flag pattern 01111110.
The sender first adds the delimiter to the start of frame and starts to read data bits on
encountering 5 continuous 1 bits it stuffs a 0 after the 5th 1 bit and continues to read data bits,
after finishing the data bits it adds the delimiter to the end of the data. The data sent is
01111110111110101111110.
The receiver on receiving the data, removes the starting delimiter and reads data bits,
on encountering 5 continuous 1 bits, it discards the next bit and continues to read data bits till
it reaches the end delimiter pattern. Thus the data received by receiver is 111111.
Diagram :
Code :
import java.util.Scanner;
class BitStuffing
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String flag = "01111110";
System.out.println("\n*****SENDER SIDE*****");
System.out.println("\nFlag Pattern : " + flag);
System.out.println("\nEnter no of frames : ");
int n = sc.nextInt();
String frames[] = new String[n];
for(int i=0;i<n;i++)
{
System.out.println("\nEnter data for frame " + i + " : ");
frames[i] = sc.next();
}
String code = "";
for(int i=0;i<n;i++)
{
code+=flag;
int countOfOnes = 0;
for(int j=0;j<frames[i].length();j++)
{
if(frames[i].charAt(j) == '1')
{
countOfOnes++;
if(countOfOnes<5)
{
code+= frames[i].charAt(j);
}
else
{
code+= "" + frames[i].charAt(j) + "" + '0';
countOfOnes=0;
}
}
else
{
code+= frames[i].charAt(j);
countOfOnes=0;
}
}
code+= flag;
}
System.out.println("\nAfter Bit Stuffing Framing : " + code);
System.out.println("\n\n*****RECEIVER SIDE*****");
System.out.println("\nEnter received Frame : ");
code = sc.next();
int i=0,countOfFrames=0;
String f[] = new String[10];
while(i<code.length())
{
code = code.substring(8); //remove start flag
int index = code.indexOf(flag); //get index of end flag
String temp = "";
int count=0,j=0;
while(j<index)
{
if(code.charAt(j) == '1')
{
count++;
temp+="" + code.charAt(j);
if(count==5)
{
j++;
count=0;
}
}
else
{
temp+="" + code.charAt(j);
count=0;
}
j++;
}
f[countOfFrames++]=temp;
code = code.substring(index+8); // remove of end flag
i=index+8;
}
for(int a=0;a<countOfFrames;a++)
{
System.out.println("\nFrame " + a + " : " + f[a]);
}
sc.close();
}
}
Output :
Conclusion :
Framing packs the data bits and transmits the data. It is used to detect the start and end
of the frames. Character Count uses length of the frame to determine the begin and end of the
frame. Byte Stuffing uses flag byte & a special character (ESC character) to differentiate flag
byte as a part of the data. Bit Stuffing is efficient as it makes use of bits to differentiate. It
makes use of stuffed bits to differentiate flag as a delimiter or flag as part of data.
Experiment No 6.
Aim : To implement socket communication in Java.
Theory :
Socket : A socket is one endpoint of a two-way communication link between two programs
running on the network. A socket is bound to a port number so that the TCP layer can
identify the application that data is destined to be sent to. An endpoint is a combination of an
IP address and a port number.
Socket Communication :
Normally, a server runs on a specific computer and has a socket that is bound to a
specific port number. The server just waits, listening to the socket for a client to make a
connection request. The client knows the hostname of the machine on which the server is
running and the port number on which the server is listening. To make a connection request,
the client tries to rendezvous with the server on the server's machine and port. The client also
needs to identify itself to the server so it binds to a local port number that it will use during
this connection. This is usually assigned by the system. If everything goes well, the server
accepts the connection. Upon acceptance, the server gets a new socket bound to the same
local port and also has its remote endpoint set to the address and port of the client. It needs a
new socket so that it can continue to listen to the original socket for connection requests
while tending to the needs of the connected client. On the client side, if the connection is
accepted, a socket is successfully created and the client can use the socket to communicate
with the server. The client and server can now communicate by writing to or reading from
their sockets.
TCP Socket Implementation in Java :
TCP is a connection-oriented protocol, which means a connection is established and
maintained until the application programs at each end have finished exchanging messages.
The java.net package in the Java platform provides a class, Socket, that implements one side
of a two-way connection between your Java program and another program on the network.
The Socket class sits on top of a platform-dependent implementation, hiding the details of
any particular system from your Java program. By using the java.net.Socket class instead of
relying on native code, your Java programs can communicate over the network in a platform-
independent fashion. Additionally, java.net includes the ServerSocket class, which
implements a socket that servers can use to listen for and accept connections to clients.
UDP Socket Implementation in Java :
User Datagram Protocol (UDP) is a Transport Layer protocol. UDP is a part of
Internet Protocol suite, referred as UDP/IP suite. Unlike TCP, it is unreliable and
connectionless protocol. So, there is no need to establish connection prior to data transfer.
DatagramSockets are Java’s mechanism for network communication via UDP instead of
TCP. Java provides DatagramSocket to communicate over UDP instead of TCP. It is also
built on top of IP. DatagramSockets can be used to both send and receive packets over the
Internet.
Socket API for TCP:
Client :
Client :
Conclusion :
TCP is communication-oriented, Client uses Socket class to create socket whereas
Server uses ServerSocket class for the port to which client request requests and Socket class
to create the 2nd endpoint of the socket for communication between Client and Server in java.
UDP is connectionless and uses DatagramSocket for both Client and Server to create socket
communication in java.
Experiment No 7.
Aim : Creation of Duplex links in ns2 between two nodes.
Theory :
NS2 stands for Network Simulator Version 2. It is an open-source event-driven
simulator designed specifically for research in computer communication networks.
Features of NS2 :
1. It is a discrete event simulator for networking research.
2. It provides substantial support to simulate bunch of protocols like TCP, FTP, UDP, https
and DSR.
3. It simulates wired and wireless network.
4. It is primarily Unix based.
5. Uses TCL as its scripting language.
6. Otcl: Object oriented support
7. Tclcl: C++ and otcl linkage
Architecture of ns2 :
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. The C++ and the OTcl are linked together using TclCL.
Duplex Links :
A duplex link is composed of two or more connected parties or devices that can
communicate with one another in both directions. Duplex systems are employed in many
communications networks, either to allow for simultaneous communication in both directions
between two connected parties or to provide a reverse path for the monitoring and remote
adjustment of equipment in the field. There are two types of duplex communication systems:
full-duplex (FDX) and half-duplex (HDX).
1. Half Duplex :
In half-duplex mode, each station can both transmit and receive, but not at the same
time. When one device is sending, the other can only receive, and vice versa. The half-duplex
mode is used in cases where there is no need for communication in both direction at the same
time. The entire capacity of the channel can be utilized for each direction. Example: Walkie-
talkie in which message is sent one at a time and messages are sent in both the directions.
2. Full Duplex :
In full-duplex mode, both stations can transmit and receive simultaneously. In full-
duplex mode, signals going in one direction share the capacity of the link with signals going
in other direction. Full-duplex mode is used when communication in both direction is
required all the time. The capacity of the channel, however must be divided between the two
directions. Example: Telephone Network in which there is communication between two
persons by a telephone line, through which both can talk and listen at the same time.
Conclusion :
Thus we have created TCP and UDP connections are in NS2. TCP is connection
oriented and receives acknowledgement for packets sent, whereas UDP is connectionless
protocol and doesn’t require any acknowledgement for packets sent and thus continuously
sends data packets. Once the queue limit between n2 and n3 is reached, the packets get stored
in the buffer of node n2 and once the buffer is full the packets start to drop. Thus it is
necessary to manage the bandwidths of the links properly.
Experiment No 9.
Aim : Creation of Stop and Wait in ns2.
Theory :
Stop and Wait Protocol :
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. The sender
starts a timer as soon as its sends the frames. In case of any interruption if the frame is lost,
after the senders timer gets over and no acknowledgement is received, the sender has to
retransmit all the frames for which acknowledgement is not received.
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.
Problems in Stop and Wait Protocol :
1. Suppose the sender sends the data and the data is lost. The receiver is waiting for the data
for a long time. Since the data is not received by the receiver, so it does not send any
acknowledgment. Since the sender does not receive any acknowledgment so it will not
send the next packet. This problem occurs due to the lost data. Thus sender waits till its
timer gets over and then retransmits the frame.
2. Suppose the sender sends the data and it has also been received by the receiver. On
receiving the packet, the receiver sends the acknowledgment. In this case, the
acknowledgment is lost in a network, so there is no chance for the sender to receive the
acknowledgment. As acknowledgement is not received the sender can’t transmit next
frame and waits till its timer gets over and then again retransmits the 1st frame.
3. Suppose the sender sends the data and it has also been received by the receiver. The
receiver then sends the acknowledgment but the acknowledgment is received after the
timeout period on the sender's side. As the acknowledgment is received late, so
acknowledgment can be wrongly considered as the acknowledgment of some other data
packet.
Representation of Stop and Wait Protocol :
WEP Encryption :
WEP uses RC4 stream cipher to encrypt data between access point and wireless
device. WEP uses 8-bit RC4 and operates on 8-bit values by creating an array with 256 8-bit
values for a lookup table (8-bits of 8-bit values).
WEP uses CRC for the data integrity. WEP performs CRC (Cyclic Redundancy Check)
checksum operation on the plaintext and generates CRC value. This CRC value is
concatenated to the plaintext. The secret key is concatenated to the Initialization Vector(IV)
and fed into the RC4. Based on the secret key and IV, RC4 generates keystream. The
keystream and plaintext + CRC message are XOR' ed together. The result is the ciphertext.
The same Initialization Vector that was used before, is prepended in clear text to the resultant
ciphertext. The IV + Ciphertext along with the frame headers are then transmitted over the
air.
Packet Tracer :
Packet Tracer is a cross-platform visual simulation tool designed by Cisco Systems
that allows users to create network topologies and imitate modern computer networks. The
software allows users to simulate the configuration of Cisco routers and switches using a
simulated command line interface. Packet Tracer makes use of a drag and drop user interface,
allowing users to add and remove simulated network devices as they see fit.
Packet Tracer can be run on Linux, Microsoft Windows, and macOS. Similar Android
and iOS apps are also available. Packet Tracer allows users to create simulated network
topologies by dragging and dropping routers, switches and various other types of network
devices. Packet Tracer supports an array of simulated Application Layer protocols, as well as
basic routing with RIP, OSPF, EIGRP, BGP, to the extents required by the current CCNA
curriculum. Packet Tracer can be useful for understanding abstract networking concepts.
Implementation of Star Topology using WEP Protocol :
If no WEP setup is made on the wireless router, then the router allows open access to
every wireless device in network. Once the WEP setup has been made the router allows
access to only those devices who have proper SSID & WEP-Key.
Before WEP Setup :
Conclusion :
Wire Shark is a free packet analyser, which is used to analyse various packets
received from various adapters of the system. It is used for network troubleshooting, analysis,
software and communications protocol development. Through Wire Shark we have learnt
about various packets like TCP,TLS,SSDP,ARP,HTTP,DNS and QUIC.