0% found this document useful (0 votes)
14 views108 pages

OSI Model Overview and Functions

The document outlines various networking concepts, focusing on the OSI model, its seven layers, and their functions. It also details commands for network troubleshooting, such as tcpdump, netstat, and ping, along with a program to download a webpage using TCP sockets. The document serves as a comprehensive guide for understanding network protocols and utilities.

Uploaded by

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

OSI Model Overview and Functions

The document outlines various networking concepts, focusing on the OSI model, its seven layers, and their functions. It also details commands for network troubleshooting, such as tcpdump, netstat, and ping, along with a program to download a webpage using TCP sockets. The document serves as a comprehensive guide for understanding network protocols and utilities.

Uploaded by

k.rahini2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

TABLE OF CONTENTS

PAGE
[Link] DATE TITLE MARKS SIGNATURE
NO
INTRODUCTION TO OSI
1A 1
LAYERS

1B COMMANDS 10

HTTP WEB CLIENT


PROGRAM TO
2 DOWNLOAD A WEB 20
PAGE USING TCP
SOCKET
ECHO CLIENT AND ECHO
3A SERVER USING TCP 24
SOCKETS
CHAT APPLICATION
3B 27
USING TCP SOCKETS

SIMULATION OF DNS
4 32
USING UDP SOCKETS

USING WIRESHARK TO
5 CAPTURE AND EXAMINE 37
NETWORK PACKETS

SIMULATING ADDRESS
6A RESOLUTION PROTOCOL 41

SIMULATING REVERSE
6B ADDRESS RESOLUTION 44
PROTOCOL
STUDY OF NETWORK
7A SIMULATOR (NS) 48

SIMULATION OF
7B CONGESTION CONTROL 52
ALGORITHM
7C AIMD-CONGESTION 59
CONTROL ALGORITHM
STUDY OF TCP/UDP
8A PERFORMANCE USING 64
SIMULATION TOOL
TCP PROGRAM:
8B MESSAGE REVERSAL 68

UDP PROGRAM:
8C MESSAGE REVERSAL 71

SIMULATION OF LINK
9A STATE ROUTING 76
ALGORITHM
LINK STATE ROUTING
9B ALGORITHM USING 80
JAVA
SIMULATION OF
9C DISTANCE VECTOR 86
ROUTING ALGORITHM
DISTANCE VECTOR
9D ROUTING ALGORITHM 91
USING JAVA
SIMULATION OF ERROR
10 A CORRECTION CODE 95
(CRC)
SIMULATION OF ERROR
10 B CORRECTION - 100
HAMMING CODE
Ex No:1 A
INTRODUCTION TO OSI LAYERS

Aim
To study about the OSI layers.

OSI Model

OSI stands for Open System Interconnection is a reference model that describes how
information from a software application in one computer moves through a physical medium to
the software application in another computer. OSI consists of seven layers, and each layer
performs a particular network function. OSI model was developed by the International
Organization for Standardization (ISO) in 1984, and it is now considered as an architectural
model for the inter-computer communications.

OSI model divides the whole task into seven smaller and manageable tasks. Each layer is
assigned a particular [Link] layer is self-contained, so that task assigned to each layer can
be performed independently

7 Layers of OSI Model

There are the seven OSI layers. Each layer has different functions. A list of seven layers are given
below:

1. Physical Layer
2. Data-Link Layer
3. Network Layer
4. Transport Layer
5. Session Layer
6. Presentation Layer
7. Application Layer

1
1) Physical layer

The main functionality of the physical layer is to transmit the individual bits from one node
to another node. It is the lowest layer of the OSI model. It establishes, maintains and deactivates
the physical connection. It specifies the mechanical, electrical and procedural network interface
specifications.

2
Functions of a Physical layer

Line Configuration: It defines the way how two or more devices can be connected physically.

Data Transmission: It defines the transmission mode whether it is simplex, half-duplex or


fullduplex mode between the two devices on the network.

Topology: It defines the way how network devices are arranged.

Signals: It determines the type of the signal used for transmitting the information.

2) Data-Link Layer

This layer is responsible for the error-free transfer of data frames. It defines the format of
the data on the network. It provides a reliable and efficient communication between two or more
devices. It is mainly responsible for the unique identification of each device that resides on a local
network. It contains two sub-layers: Logical Link Control Layer, Media Access Control Layer.

Functions of the Data-link layer

Framing: The data link layer translates the physical's raw bit stream into packets known as Frames.
The Data link layer adds the header and trailer to the frame. The header which is added to the frame
contains the hardware destination and source address.

3
Physical Addressing: The Data link layer adds a header to the frame that contains a destination
address. The frame is transmitted to the destination address mentioned in the header.

Flow Control: Flow control is the main functionality of the Data-link layer. It is the technique
through which the constant data rate is maintained on both the sides so that no data get corrupted.
It ensures that the transmitting station such as a server with higher processing speed does not
exceed the receiving station, with lower processing speed.

Error Control: Error control is achieved by adding a calculated value CRC (Cyclic Redundancy
Check) that is placed to the Data link layer's trailer which is added to the message frame before it
is sent to the physical layer. If any error seems to occurr, then the receiver sends the
acknowledgment for the retransmission of the corrupted frames.

Access Control: When two or more devices are connected to the same communication channel,
then the data link layer protocols are used to determine which device has control over the link at a
given time.

3) Network Layer

4
It is a layer that manages device addressing, tracks the location of devices on the network.
It determines the best path to move data from source to the destination based on the network
conditions, the priority of service, and other factors. The Data link layer is responsible for routing
and forwarding the packets. Routers are the layer 3 devices, they are specified in this layer and
used to provide the routing services within an internetwork. The protocols used to route the
network traffic are known as Network layer protocols. Examples of protocols are IP and Ipv6.

Functions of Network Layer

Internetworking: An internetworking is the main responsibility of the network layer. It provides


a logical connection between different devices.

Addressing: A Network layer adds the source and destination address to the header of the frame.
Addressing is used to identify the device on the internet.

Routing: Routing is the major component of the network layer, and it determines the best optimal
path out of the multiple paths from source to the destination.

Packetizing: A Network Layer receives the packets from the upper layer and converts them into
packets. This process is known as Packetizing. It is achieved by internet protocol (IP).

4) Transport Layer

5
The Transport layer is a Layer 4 ensures that messages are transmitted in the order in which
they are sent and there is no duplication of data. The main responsibility of the transport layer is
to transfer the data completely. It receives the data from the upper layer and converts them into
smaller units known as segments. This layer can be termed as an end-to-end layer as it provides a
point-to-point connection between source and destination to deliver the data reliably.

The two protocols used in this layer are: Transmission Control Protocol, User Datagram Protocol

Functions of Transport Layer

Service-point addressing: Computers run several programs simultaneously due to this reason, the
transmission of data from source to the destination not only from one computer to another
computer but also from one process to another process. The transport layer adds the header that
contains the address known as a service-point address or port address. The responsibility of the
network layer is to transmit the data from one computer to another computer and the responsibility
of the transport layer is to transmit the message to the correct process.

Segmentation and reassembly: When the transport layer receives the message from the upper
layer, it divides the message into multiple segments, and each segment is assigned with a sequence
number that uniquely identifies each segment. When the message has arrived at the destination,
then the transport layer reassembles the message based on their sequence numbers.

Connection control: Transport layer provides two services Connection-oriented service and
connectionless service. A connectionless service treats each segment as an individual packet, and
they all travel in different routes to reach the destination. A connection-oriented service makes a
connection with the transport layer at the destination machine before delivering the packets. In
connection-oriented service, all the packets travel in the single route.

Flow control: The transport layer also responsible for flow control but it is performed end-to-end
rather than across a single link.

6
Error control: The transport layer is also responsible for Error control. Error control is performed
end-to-end rather than across the single link. The sender transport layer ensures that message reach
at the destination without any error.

5) Session Layer

The Session layer is used to establish, maintain and synchronizes the interaction between
communicating devices.

Functions of Session layer:

Dialog control: Session layer acts as a dialog controller that creates a dialog between two
processes or we can say that it allows the communication between two processes which can be
either half-duplex or full-duplex.

Synchronization: Session layer adds some checkpoints when transmitting the data in a sequence.
If some error occurs in the middle of the transmission of data, then the transmission will take place
again from the checkpoint. This process is known as Synchronization and recovery.

7
6) Presentation Layer

A Presentation layer is mainly concerned with the syntax and semantics of the information
exchanged between the two [Link] acts as a data translator for a [Link] layer is a part of
the operating system that converts the data from one presentation format to another [Link]
Presentation layer is also known as the syntax layer.

Functions of Presentation layer

Translation: The processes in two systems exchange the information in the form of character
strings, numbers and so on. Different computers use different encoding methods, the presentation
layer handles the interoperability between the different encoding methods. It converts the data from
sender-dependent format into a common format and changes the common format into receiver-
dependent format at the receiving end.

Encryption: Encryption is needed to maintain privacy. Encryption is a process of converting the


sender-transmitted information into another form and sends the resulting message over the
network.

8
7) Application Layer

An application layer serves as a window for users and application processes to access network
[Link] handles issues such as network transparency, resource allocation, [Link] application
layer is not an application, but it performs the application layer [Link] layer provides the
network services to the end-users.

Functions of Application layer

File transfer, access, and management (FTAM): An application layer allows a user to access the
files in a remote computer, to retrieve the files from a computer and to manage the files in a remote
computer.

Mail services: An application layer provides the facility for email forwarding and storage.

Result

Thus the OSI layers were studied successfully.

9
Ex No:1 B
COMMANDS

Aim
To explore the commands like tcpdump, netstat, ifconfig, nslookup, traceroute and ping.

1. Tcpdump

The tcpdump utility allows you to capture packets that flow within your network to assist in
network troubleshooting. The following are several examples of using tcpdump with different
options. Traffic is captured based on a specified filter.

Options Description

-D print a list of network interfaces.


-i specify an interface on which to capture.
-c specify the number of packets to receive.
-w write captured data to a file.
-r Read captured data from a file.
Many other options and arguments can be used with tcpdump. The following are some specific
examples of the power of the tcpdump utility.

1. Display traffic between 2 hosts

To display all traffic between two hosts (represented by variables host1 and host2):

#tcpdump host host1 and host2

2. Display traffic from a source or destination host only

To display traffic from only a source (src) or destination (dst) host:

#tcpdumpsrc host

#tcpdumpdst host

10
3. Display traffic for a specific protocol

Provide the protocol as an argument to display only traffic for a specific protocol, for example
tcp, udp, icmp, arp:

#tcpdump protocol

For example to display traffic only for the top traffic:

#tcpdumptcp

4. Filtering based on source or destination port To filter based on a source or destination


port:

#tcpdumpsrc port ftp

#tcpdumpdst port http

2. Netstat

Netstat is a common command like TCP/IP networking available in most versions of


windows,linux,unix and other operating systems. Netstat provides information and statistics
about protocols in use and current TCP/IP network connections.

Syntax
Netstat [-a][-b][-e][-f][-n][-o][-p prob][-r][-s][-t][-x][-y][interval]
Parameter
-a :Displays all connections and listening ports.
-b :Shows the executable involved in creating each connection or listening port.
-e : Displays Ethernet statistics.
-f : Displays fully qualified domain names for foreign address.
-n : Shows addresses and port number in numerical form.
-o : Displays the owning process ID associated with each connection.
-p proto : Shows connections for the specified protocol(TCP,UDP,etc).
-r : Displays the routing table.
-s : Displays per_protocol statistics.
-t : Shows the current connection offload state.
11
-x : Displays network direct connections,listeners and shared endpoints.
-y : Displays the TCP connection template for all connections.
Interval : The interval option in the netstat command specifies the time in seconds between each
display of [Link] the output every specified number of seconds until you stop it with
CTRL+C.
EX:netstat -e 5

Output

12
13
3. Ipconfig
The ipconfig command is not available on windows however you can use the ipconfigcommand,
which serves a similar purpose for managing and viewing network configurationin windows.
Syntax
ipconfig [/allcompartments] [/? | /all | /renew [adapter] | /release [adapter] | /renew6[adapter] |
/release6 [adapter] | /flushdns | /displaydns | /registerdns | /showclassid adapter |/setclassid
adapter [classid] | /showclassid6 adapter | /setclassid6 adapter [classid] ]

ipconfig /? :Display this help message ipconfig /all


:Display full configuration information.
ipconfig /release :Release the IPv4 address for the specified adapter.
ipconfig /release6 :Release the IPv6 address for the specified adapter.
ipconfig /renew :Renew the IPv4 address for the specified adapter. ipconfig
/renew6 :Renew the IPv6 address for the specified adapter. ipconfig
/flushdns :Purges the DNS Resolver cache.
ipconfig /registerdns :Refreshes all DHCP leases and re-registers DNSnames ipconfig
/displaydns :Display the contents of the DNS Resolver Cache. ipconfig /showclassid

14
:Displays all the dhcp class IDs allowed for adapter. ipconfig /setclassid :Modifies the
dhcp class id. ipconfig /showclassid6 :Displays all the IPv6 DHCP class IDs allowed
for adapter. ipconfig /setclassid6 :Modifies the IPv6 DHCP class id.

Output

15
16
4. Nslookup
The nslookup (Which stands for name server lookup) command is a network utilityprogram used
to obtain information about internet servers. Its finds name server informationfor domains by
queryibg the Domain Name System .
Syntax
>nslookup
>[Link]

Output

5. Traceroute

In Windows, the tracert command is known as tracert. It is used to trace the. path packets take
from your computer to a destination host, showing each hop along the way.

Syntax:> tracert [Link]

Output

17
6. Ping

The ping command in Windows is used to test the connectivity between your computer and
another device by sending ICMP Echo Requests and waiting for a response. It’s a simple and
effective tool for network troubleshooting.

Commands

-Ping a specific number of times:


> ping -n 10 [Link] -Ping
until stopped: > ping -t
[Link] -Specify packet size:
> ping -l 1000 [Link]
-Don’t resolve IP addresses to hostnames:
> ping -a [Link]
-Set a Timeout
>ping -w 5000 [Link]
-Force IPv4 or IPv6 ping
> ping -4 [Link]
> ping -6 [Link]

Output

18
Result
Thus the commands were explored.
19
Ex No:2 HTTP WEB CLIENT PROGRAM TO DOWNLOAD A
WEB PAGE USING TCP SOCKET

Aim
To download a webpage using TCP Socket.

Client side
1) Start the program.

2) Create a socket which binds the Ip address of server and the port address to acquire
service.

3) After establishing connection send the URL to server.

4) Open a file and store the received data into the file.

5) Close the socket.

6) End the program.

Server side
1) Start the program.

2) Create a server socket to activate the port address.

3) Create a socket for the server socket which accepts the connection.

4) After establishing connection receive url from client.

5) Download the content of the url received and send the data to client.

6) Close the socket.

7) End the program.

20
Program

import [Link].*;
import [Link].*;
import [Link];
public class WebPage{
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a website name:");
String host = [Link]();
int port = 80; // HTTP default port
String path = "/"; // Path of the web page
try {
Socket socket = new Socket(host, port);
// Send HTTP request
PrintWriter out = new PrintWriter([Link]());
[Link]("GET " + path + " HTTP/1.1");
[Link]("Host: " + host);
[Link]("Connection: close");
[Link](); // Empty line to indicate end of headers
[Link]();
// Receive and save HTTP response content to a file
BufferedReader in = new BufferedReader(new InputStreamReader([Link]()));
String line;
boolean foundDoctype = false;
StringBuilder content = new StringBuilder();
while ((line = [Link]()) != null){
if ([Link]("<!doctype html>")){
foundDoctype = true;
}
if (foundDoctype) {
[Link](line);
}
}

21
// Close the streams and socket
[Link]();
[Link]();
[Link]();
// Save content to a file
BufferedWriter writer = new BufferedWriter(new FileWriter("[Link]"));
[Link]([Link]());
[Link]();
[Link]("Web page content downloaded and saved as [Link]");
} catch (IOException e) {
[Link]();
}
}
}

OUTPUT

22
Result

Hence downloading the web page using TCP socket was executed successfully.

23
Ex No:3 A ECHO CLIENT AND ECHO SERVER USING TCP
SOCKETS

Aim
To write a TCP socket program for implementation of echo.

Algorithm

Client side

1. Start the program.

2. Create a socket which binds the IP address of server and the port address to acquire
service.

3. After establishing connection send a data to server.

4. Receive and print the same data from server.

5. Close the socket.

6. End the program.

Server side

1. Start the program.

2. Create a server socket to activate the port address.

3. Create a socket for the server socket which accepts the connection.

4. After establishing connection receive the data from client.

5. Print and send the same data to client.

6. Close the socket.

7. End the program.


24
Program

Server

import [Link].*;
import [Link].*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=[Link]();//establishes connection
DataInputStream dis=new DataInputStream([Link]());
String str=(String)[Link]();
[Link]("message= "+str);
[Link]();
}
catch(Exception e){
[Link](e);
}
}
}
Client

import [Link].*;
import [Link].*;
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream
([Link]());
[Link]("Hello Server");

25
[Link]();
[Link]();
[Link]();
}
catch(Exception e){
[Link](e);
}
}
}
Output

Server

Client

Result

Thus the Echo Client and Echo Server using TCP Sockets in java has written and
executed successfully.

26
Ex No:3 B CHAT APPLICATION USING TCP SOCKETS

Aim
To write a client-server application for chat using TCP SOCKETS.

Algorithm

Client

1. Start the program

2. Include necessary package in java

3. To create a socket in client to server.

4. The client establishes a connection to the server.

5. The client accept the connection and to send the data from client to server.

6. The client communicates the server to send the end of the message

7. Stop the program.

Server

1. Start the program

2. Include necessary package in java

3. To create a socket in server to client

4. The server establishes a connection to the client.

5. The server accept the connection and to send the data from server to client

6. The server communicates the client to send the end of the message.

7. Stop the program


27
Program

Server

import [Link].*;
import [Link].*;
import [Link].*;
public class Server1 {
public static void main(String[] args) {
try
{
ServerSocket ss=new ServerSocket(3333);
Socket s=[Link]();
String str,str2;
DataInputStream din=new DataInputStream([Link]());
DataOutputStream dout=new DataOutputStream([Link]());
Scanner m=new Scanner([Link]);
[Link]("Connection established");
[Link]("enter any data(enter stop to terminate)");
do
{
str2=[Link]();
[Link]("Data from client:"+str2);
str=[Link]();
[Link](str);
}while(([Link]("stop"))==false);
[Link]();
[Link]();
[Link]();
[Link]();
[Link]("Connection closed.");
}

28
catch(Exception e)
{
[Link](e);
}
}
}

Client
import [Link].*;
import [Link].*;
import [Link].*;
public class Client1 {
public static void main(String[] args) {
try
{
Socket s=new Socket("localhost",3333);
String str,str2;
DataInputStream din=new DataInputStream([Link]());
DataOutputStream dout=new DataOutputStream([Link]());
Scanner m=new Scanner([Link]);
[Link]("enter any data(enter stop to terminate)");
do
{
str=[Link]();
[Link](str);
str2=[Link]();
[Link]("Data from server:"+str2+"\n");
}while(([Link]("stop"))==false);
[Link]();
[Link]();
[Link]();

29
}
catch(Exception e)
{
[Link](e);
}
}
}

Output

Server

30
Client

Result

Hence the chat application using TCP Sockets in java has written and executed
successfully.

31
Ex No : 4
SIMULATION OF DNS USING UDP SOCKETS

Aim

To write a java program to simulate DNS using UDP sockets.

Algorithm

Server

i. Start the server program.


ii. Create a Datagram socket and a buffer (byte array).

iii. Initialize position to 0.


iv. Loop through the data:
a. If the character at the current position is not null or newline.
v. Create a Datagram Packet to send the character to the client. Send the
packet.
vi. Increment the position.
vii. Close the Datagram socket and stop the server.

Client

i. Start the client program.


ii. Create a Datagram socket and a buffer (byte any) for receiving data.
Step3 Loop to receive data.
1. Create a Datagram Socket to receive data from the server
2. Receive the packet from the server.
3. Print the received data.
iii. Close the Datagram socket and stop the client.

32
Program

Server

import [Link];
import [Link];
import [Link];
import [Link];
public class Server {
static String[] hosts = {
"[Link]", "[Link]", "[Link]", "[Link]", "[Link]",
"[Link]", "[Link]", "[Link]", "[Link]",
"[Link]", "[Link]", "[Link]", "[Link]",
"[Link]"
};
static String[] ipAddresses = {
"[Link]", "[Link]", "[Link]", "[Link]", "[Link]",
"[Link]", "[Link]", "[Link]", "[Link]", "[Link]",
"[Link]", "[Link]", "[Link]", "[Link]",
"[Link]"
};
public static int search(String key) {
for (int i = 0; i < [Link]; i++) {
if ([Link](hosts[i])) {
return i;
}
} return -1;
}

33
public static void main(String[] args) {
try{
DatagramSocket ds = new DatagramSocket();
Scanner sc = new Scanner([Link]);
[Link]("Enter host name: ");
String str = [Link]();
int strIndex = search(str);
InetAddress ip = [Link]();
String message = strIndex != -1 ? ipAddresses[strIndex]
:"Host_name_not_found";
DatagramPacket dp = new
DatagramPacket([Link](), [Link](), ip, 3000);
[Link](dp);
[Link]();
}
catch (Exception e) {
[Link](e);
}
}
}

Client

import [Link];
import [Link];
public class Client {
public static void main(String[] args) {

34
try{
DatagramSocket ds = new DatagramSocket(3000);
byte[] arr = new byte[30];
DatagramPacket dp = new DatagramPacket(arr, [Link]);
[Link](dp);
String str = new String([Link]()).trim();
[Link]("IP Address: " + str);
[Link]();
}
catch (Exception e) {
[Link](e);
}
}
}

35
Output

Server

Client

Result
Thus a java program to simulate DNS using UDP sockets is executed successfully.
36
USING WIRESHARK TO CAPTURE AND EXAMINE
Ex No : 5 NETWORK PACKETS

Introduction
Wireshark is a powerful open-source network protocol analyzer used to capture and
analyze network traffic in real-time. By capturing packets, network administrators and security
professionals can gain insights into network behavior, troubleshoot issues, and detect potential
security threats.
Installation Steps
1. Download Wireshark :
 Visit the official Wireshark website at [Link]
 Navigate to the "Download" section.
 Choose the appropriate installer for your operating system (Windows, macOS, or Linux).
 Follow the on-screen instructions to download the installer.
2. Install Wireshark :
 Locate the downloaded installer and run it.
 Follow the installation wizard's prompts:
 Choose installation options (e.g., desktop shortcuts).
 Accept the license agreement.
 Select installation location.
 Complete the installation process.
Capturing Packets
1. Open Wireshark
 Launch Wireshark from the desktop shortcut or start menu.
2. Select Network Interface
 In the main window, you'll see a list of available network interfaces (e.g., Ethernet, Wi-Fi).
 Choose the relevant interface for capturing packets.
3. Start Packet Capture
 Click on the chosen interface.
 Click the "Start" button or press "Ctrl + E" to begin capturing packets on that interface.

37
Examining Packets
1. Packet List
 The main window displays a list of captured packets.
 Columns show source and destination IPs, protocols, packet lengths, and more.
2. Packet Details
 Select a packet in the list to see detailed information.
 The packet details area dissects the packet's protocol layers.
 Inspect the layers for protocol-specific information and payload data.
3. Filtering Packets
 Use display filters to focus on specific types of packets.
 Enter a filter expression in the display filter field at the top of the window and press Enter.
Analyzing Packets
1. Identifying Anomalies
 Look for unusual traffic patterns, such as sudden spikes or frequent connections.
 Pay attention to communication between unfamiliar IP addresses.
2. Protocol Behavior
 Analyze protocol behavior for deviations from normal patterns.
 Investigate unexpected responses, errors, or repeated requests.
3. Malware Indicators
 Examine packet payloads for strings or patterns that may indicate malware activity.
 Look for suspicious commands, URLs, or file transfers.
Uses of Capturing Packets
Packet capture with Wireshark has several important uses, including:
1. Network Troubleshooting and Diagnostics
 Identify and resolve network performance issues, latency problems, and dropped connections.
 Analyze network behavior to pinpoint the source of problems.
2. Security Analysis and Intrusion Detection
 Detect unauthorized access attempts and security breaches.
 Monitor for suspicious traffic patterns and potential threats.
3. Vulnerability Assessment
 Identify vulnerabilities in network systems and applications
38
 Analyze traffic to uncover potential weaknesses that can be exploited

4. Quality of Service (QoS) Monitoring


 Monitor bandwidth usage, packet loss, and latency to maintain optimal network performance.
 Ensure that critical applications receive the necessary resources.
5. Forensics and Incident Response
 Use captured packet data as evidence during incident investigations.
 Reconstruct events leading up to security incidents.
Output

39
Conclusion
Wireshark is an invaluable tool for capturing and analyzing network packets. It aids in
diagnosing network issues, ensuring security, and identifying potential threats. Responsible and
ethical use of Wireshark is essential to maintain privacy and comply with legal considerations.

40
Ex No:6A SIMULATING ADDRESS RESOLUTION PROTOCOL

Aim
To write a java program for simulating ARP protocol.

Algorithm

Server

1. Start the program.


2. Accept the socket which is created by the client.
3. Server maintains the table in which IP and corresponding MAC addresses are stored.
4. Read the IP address which is send by the client.
5. Map the IP address with its Mac address and return the MAC address to client.

Client

1. Start the program.


2. Using socket connection is established between client and server.
3. Get the IP address to be converted into MAC address.
4. Send this IP address to server.
5. Server returns the MAC address to client.

Program
package arp;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class AAA {
public static void main(String[] args)
{

41
try
{
Scanner console = new Scanner([Link]);
[Link]("Enter System Name: ");
String ipaddr = [Link]();
InetAddress address = [Link](ipaddr);
[Link]("address = "+address);
NetworkInterface ni = [Link](address);
if (ni!=null)
{
byte[] mac = [Link]();
if (mac != null)
{
[Link]("MAC Address : ");
for (int i=0; i < [Link]; i++)
{
[Link]("%02X%s", mac[i], (i < [Link] - 1) ? "-" :"");
}
}
else
{
[Link]("Address doesn't exist or is not accessible/");

}
}
else
{
[Link]("Network Interface for the specified address is not found");
}
}
catch(UnknownHostException | SocketException e)
{
}

42
}

Output

Result
A java program for simulating ARP protocol was written,executed and the output was
verified successfully.

43
Ex No:6 B SIMULATING REVERSE ADDRESS RESOLUTION
PROTOCOL

Aim
To write a java program for simulationg RARP protocol.

Algorithm

Server
1. Start the program.

2. Server maintains the table in which IP and corresponding MAC addreddes are stored.

3. Read the MAC address which is send by the client.

4. Map the IP address with its MAC address and return the IP address to client.

5. Stop the program.

Client
1. Start the program.

2. Using datagram sockets UDP function is established.

3. Get the MAC address to be converted into IP address.

4. Sernd this MAC address to server.

5. Server returns the IP address to client.

6. Stop the program.

Program

Server

import [Link].*;
import [Link].*;
import [Link].*;
class Serverrarp{

44
public static void main(String args[]){
try{
DatagramSocket server=new DatagramSocket(1309);
while(true){
byte[] sendbyte=new byte[1024];
byte[] receivebyte=new byte[1024];
DatagramPacket receiver=new DatagramPacket(receivebyte,[Link]);
[Link](receiver);
String str=new String([Link]());
String s=[Link]();
InetAddress addr=[Link]();
int port=[Link]();
String ip[]={"[Link]","[Link]"};
String mac[]={"[Link]","[Link]"};
for(int i=0;i<[Link];i++){
if([Link](mac[i])){
sendbyte=ip[i].getBytes();
DatagramPacket sender=new
DatagramPacket(sendbyte,[Link],addr,port);
[Link](sender);
break;}}
break;}}
catch(Exception e){
[Link](e);
}
}
}

Client

import [Link].*;
import [Link].*;
import [Link].*;
class Clientrarp{
45
public static void main(String args[]){try{
DatagramSocket client=new DatagramSocket();
InetAddress addr=[Link]("[Link]");
byte[] sendbyte=new byte[1024];
byte[] receivebyte=new byte[1024];
BufferedReader in=new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter the Physical address (MAC):");
String str=[Link](); sendbyte=[Link]();
DatagramPacket sender=new DatagramPacket(sendbyte,[Link],addr,1309);
[Link](sender);
DatagramPacket receiver=new DatagramPacket(receivebyte,[Link]);
[Link](receiver);
String s=new String([Link]());
[Link]("The Logical Address is(IP): "+[Link]());
[Link]();
}
catch(Exception e){
[Link](e);
}
}
}

46
Output

Server

Client

Result
A java program for simulating RARP protocol was written,executed and the output was
verified successfully.

47
Ex No:7A STUDY OF NETWORK SIMULATOR (NS)

Aim
To explore Cisco Packet Tracer for network simulation and lab setup.
Introduction to Cisco Packet Tracer
A. Overview and Significance
• Definition: Cisco Packet Tracer is a robust network simulation tool developed by
Cisco Systems, designed for teaching and learning complex networking concepts.
• Importance in Lab Settings: Provides a virtual, risk-free environment for hands-on
learning, allowing students to experiment with network configurations and
troubleshoot issues.
B. Key Features of Cisco Packet Tracer
1. Wide Device Support: Packet Tracer supports a variety of devices, including
routers, switches, hubs, PCs, servers, and more.
2. Realistic Simulation: Offers real-time simulation of network behaviors, allowing
students to observe the effects of their configurations instantly.
3. Protocols and Applications: Simulates protocols like TCP/IP, DHCP, and DNS,
along with applications like web browsers and email clients.
4. Multi-User Collaboration: Supports multi-user mode, enabling collaborative
learning and group projects.
5. Assessment and Grading: Allows instructors to create assessments, track student
progress, and grade their performance.
6. Customization: Users can create custom devices, enhancing the range of network
scenarios that can be simulated.
Setting Up Cisco Packet Tracer Lab Environment
Installation and Configuration
• Go to the Cisco Networking Academy website ([Link]
• Sign in with your account or create a new account.
• Find the "Packet Tracer" section.
• Click on "Download" or "Get Packet Tracer."
• Choose your operating system (Windows, macOS, Linux).

48
• Accept the license agreement.
• Wait for the download to complete.
• Locate the downloaded file and install Packet Tracer.
• Launch the application.
• Sign in with your Cisco Networking Academy account if prompted.
Exploring Packet Tracer Interface Main
Components
i. Device Palette:
• Routers: Represented with icons resembling actual Cisco routers.
• Switches: Icons vary based on the type of switch (Layer 2 or Layer 3).
• Hubs: Depicted as circular icons.
• End Devices: PCs, laptops, servers, and phones, represented with appropriate icons.
ii. Physical Workspace:
• Grid Layout: Devices can be placed on a grid representing the physical workspace.
• Drag-and-Drop Functionality: Devices can be dragged from the Device Palette
and dropped onto the workspace.
iii. Toolbar:
• Select Tool: Allows selection of devices and connections for configuration.
• Place Tool: Used to place devices onto the workspace.
• Connection Types: Various connection types (straight-through, crossover, etc.) can
be selected based on the devices being connected.
iv. Menu Bar:
• File: Options for creating, opening, and saving Packet Tracer files.
• Edit: Functions for undo, redo, and managing selections.
• Options: Customization options for Packet Tracer's behavior and appearance.
• Help: Access to Packet Tracer tutorials, guides, and support resources.
Basic Networking Configurations and Troubleshooting
Configuring Basic Network Device
i. Connecting Switches:
• Step 1: Drag a switch from the Device Palette and drop it onto the workspace.
• Step 2: Use straight - through Ethernet cables to connect multiple switches.

49
• Step 3: Click on the switch, select a port, click on another switch, and select a port
to establish a connection.
ii. Connecting Routers and End Devices:
• Step 1: Drag a router and end devices (PCs, laptops) onto the workspace.
• Step 2: Use appropriate cables to connect PCs to router ports and configure IP
addresses on router interfaces.
• Step 3: Configure IP addresses on end devices within the same subnet as the router
interface for connectivity.
iii. Connecting Hubs and End Devices:
• Step 1: Drag a hub and end devices onto the workspace.
• Step 2: Use straight-through Ethernet cables to connect end devices to hub ports.
• Step 3: Configure IP addresses on end devices within the same subnet for
communication through the hub.
Troubleshooting Basics
• Ping and Traceroute: Hands-on practice on using ping and traceroute commands to
troubleshoot network issues.
• Debugging Tools: Introduction to Packet Tracer's built-in debugging tools for
diagnosing problems.
Advanced Networking Configurations
VLAN and Inter-VLAN Configurations
• VLAN Setup: Creating and configuring Virtual LANs to segment a network.
• Inter-VLAN Routing: Setting up routers to enable communication between
different VLANs.
DHCP and NAT Configurations
• DHCP Setup: Configuring routers or servers to provide IP addresses dynamically.
• NAT Configuration: Implementing Network Address Translation for internet
connectivity.
Access Control and Security Implementations
• Access Control Lists (ACLs): Implementing ACLs to control traffic flow based on
source and destination IP addresses.
• Firewall Configuration: Configuring firewalls for network security.

50
Real-World Simulations and Projects
Multi-Site Network Setup
• Branch Office Connections: Configuring VPNs and secure communication
channels between branch offices.
• Data Center Design: Designing a data center network with redundancy and high
availability.
Performance Optimization and QoS
• Traffic Analysis: Analyzing network traffic patterns and optimizing network
performance.
• Quality of Service (QoS): Implementing QoS to prioritize critical network traffic.
Advanced Security Scenarios
• Intrusion Detection: Configuring intrusion detection systems for network security.
• Security Best Practices: Implementing security best practices to safeguard the
network infrastructure.

Conclusion
Cisco Packet Tracer is an invaluable tool for networking education. It provides hands-
on learning experience, allowing users to design and simulate intricate network setups.
With its user-friendly interface and powerful features, it equips learners with essential
skills, making complex networking concepts accessible. By fostering practical
understanding and problem-solving abilities, Packet Tracer empowers users to excel
in real-world networking scenarios, making it an essential resource for students and
professionals alike.

51
SIMULATION OF CONGESTION CONTROL
Ex No 7B
ALGORITHMS

Aim

To write a program to simulate congestion control algorithm-stop and wait protocol.

Algorithm

Step 1: Read the number of frames to be sent.

Step 2: Sender establish connection with the receiver.

Step 3: After the connection is established, the sender send the frames one by one.

Step 4: The next frame is sent only when the acknowledgement for the previous frame is
received.

Step5: Disconnect the connection after all the frames are received by the receiver.

Program
//Sender

import [Link].*;

import [Link].*;

public class Sender{

Socket sender;

ObjectOutputStream out;

ObjectInputStream in;

String packet, ack, str, msg;

int n, i=0, sequence=0;

Sender(){}

public void run(){

52
try{

BufferedReader br=new BufferedReader(new InputStreamReader([Link]));

[Link]("Waiting for Connection. ..");

Sender = new Socket("localhost" ,2004);

sequence=0;

out = new ObjectOutputStream([Link]());

[Link]();

in=new ObjectInputStream([Link]());

str=(String)[Link]();

[Link]("receiver >"+str);

[Link]("Enter the data to send. ..");

Packet=[Link]();

n=[Link]();

do{

try{

if(i<n){

msg=[Link](sequence);

msg=[Link](packet, substring(i,,i+1));

else if (i==n){

msg="end";[Link](msg);break;

[Link](msg);

53
sequence=(sequence==0)?1:0;

[Link]();

[Link]("data sent>”+msg);

ack=(String)[Link]();

[Link]("waiting for ack…\n\n”);

if([Link]([Link](sequence))){

i++;

[Link]("receiver >"+"packet received\n\n”);

else{

[Link]("Time out resending data…\n\n”);

sequence=(sequence==0)?1:0;

}catch(Exception e){}

}{ while(i<n+1);

[Link]("All data sent. exting.”);

}catch(Exception e){}

finally{

try{

[Link]();

[Link]();

[Link]()

54
catch(Exception e){}

public static void main(String args[]){

Senders s= new Sender();

[Link]();

//Receiver

import [Link].*;

import [Link].*;

public class Receiver{

ServerSocket receiver;

Socket connection=null;

ObjectOutputStream out;

ObjectInputStream in;

String packet,ack,data="";

int i=0,sequence=0;

Receiver(){

public void run(){

try{

BufferedReader br=new BufferedReader(new InputStreamReader([Link]));

receiver = new ServerSocket(2004,10);

55
[Link]("waiting for connection...");

Connection=[Link]();

sequence=0;

[Link]("Connection established:");

out=new ObjectOutputStream([Link]());

[Link]();

in=new ObjectInputStream([Link]());

[Link]("connected .");

do{

try{

packet=(String)[Link]();

if ([Link]([Link](0,1))==sequence) {

data+=[Link](1);

sequence= (sequence==0)?1:0;

[Link]("\n\nreceiver >"+packet);

else

[Link]("\n\nreceiver 1 >"+packet+" duplicate data");

if(i<3){

[Link]([Link](sequence));i++;

56
else{

[Link]([Link](sequence+1)%2));

i=0;

catch(Exception e){}

}while(![Link]("end"));

[Link]("Data recived="+data);

[Link]("connection ended .");

catch(Exception e){}

finally{

try{

[Link]();

[Link]();

[Link]();

catch(Exception e){}

public static void main(String args[]){

Receiver s=new Receiver();

while(true){

57
[Link]();

Output

Result
Thus the program to simulate congestion control algorithm – stop and wait protocol is
executed successfully.

58
Ex No: 7C AIMD – CONGESTION CONTROL ALGORITHM

Aim
To write a java program to perform the Congestion Control Algorithm

Algorithm
Step 1: Start.

Step 2: Read the initial congestion window size , probability of receiving an


acknowledgment and probability of packet loss from the user.

Step3: Set the initial threshold ssthresh to Integer.MAX_VALUE ,Set the acknowledgment
count ackCount to 0.

Step 4: Send packets up to the current congestion window size cwnd.

Step 5: Simulate acknowledgment reception:

Step 5.1: If acknowledgment is received based on ackProbability, increment ackCount.

Step 5.2: If acknowledgment is not received, simulate packet loss and perform the
following:

Set ssthresh to half of cwnd, but at least 1.

reset cwnd to 1.

Reset `ackCount` to 0.

Step 6: If ackCount is greater than or equal to cwnd then,Increment cwnd by 1 and reset
ackCount to 0.

Step 7: Check if cwnd has reached or exceeded the threshold ssthresh:

Step 7.1: If cwnd ≥ ssthresh, enter the Congestion Avoidance phase.

Step 7.2: In Congestion Avoidance, if packet loss occurs based on lossProbability, reduce
cwnd by half multiplicative decrease.

59
Step 8: If cwnd is below ssthresh, continue the Slow Start phase , increment cwnd by 1 for
each acknowledgment received until ssthresh is reached.

Step 9: Simulate a time interval sleep for 1 second and Repeat from Step 4.

Step 10: Stop.

Program

import [Link];

import [Link];

public class AIMD {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

// Get initial congestion window size from user

[Link]("Enter initial congestion window size: ");

int cwnd = [Link]();

[Link]("Enter probability of receiving an acknowledgment (0 to 1): ");

double ackProbability = [Link]();

[Link]("Enter probability of packet loss (0 to 1): ");

double lossProbability = [Link]();

int ssthresh = Integer.MAX_VALUE; // Initial threshold set to maximum value

int ackCount = 0; // Number of acknowledgments received

Random random = new Random();

[Link]("\nSimulation started. Press Ctrl+C to terminate.\n");

// Simulate AIMD

while (true) {

60
[Link]("Current cwnd: " + cwnd + ", ssthresh: " + ssthresh);

// Send packets up to the current congestion window size

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

sendPacket();

// Simulate acknowledgment reception

if ([Link]() <= ackProbability) {

[Link]("Acknowledgment received.");

ackCount++;

// Additive increase

if (ackCount >= cwnd) {

cwnd++;

ackCount = 0;

// Simulate packet loss

if ([Link]() <= lossProbability) {

handlePacketLoss(cwnd, ssthresh);

ssthresh = cwnd / 2; // Set new threshold

cwnd = [Link](1, cwnd / 2); // Multiplicative decrease

ackCount = 0; // Reset acknowledgment count

// Slow Start and Congestion Avoidance

61
if (cwnd < ssthresh) {

// Slow Start Phase: Additive increase

continueAdditiveIncrease(cwnd);

} else {

// Congestion Avoidance Phase

[Link]("Congestion Avoidance Phase.");

// Simulate time passing

try {

[Link](1000);

} catch (InterruptedException e) {

[Link]("Simulation interrupted.");

break;

[Link]();

private static void sendPacket() {

[Link]("Packet sent.");

private static void handlePacketLoss(int cwnd, int ssthresh) {

[Link]("Packet loss detected! Reducing cwnd and updating ssthresh.");

62
private static void continueAdditiveIncrease(int cwnd) {

[Link]("Slow Start Phase: Increasing cwnd additively.");

Output

Result
Thus the java program to implement AIMD congestion control algorithm was written,

executed and the output is verified.

63
STUDY OF TCP/UDP PERFORMANCE USING
Ex No:8 A
SIMULATION TOOL

Aim
To Study of TCP/UDP performance using Simulation tool .

Procedure

1. Develop a Topology shown in figure given below.


2. Add HTTP Client, FTP Client, DNS Client, and Email Client connected to a multi-server
through the switch.
3. Configure the network.
4. Add users to the multi-server and create domain name.

5. Edit [Link] file using the code shown in figure. Run the Code by giving the domain in
multi- server and HTTP client.
6. Connect the [Link] domain using ftp server.
7. Compose, send and receive mail between the clients connected to the server.

64
65
66
Result
Thus the TCP/UDP performance has been simulated successfully

67
Ex No:8 B
TCP PROGRAM: MESSAGE REVERSAL

Aim
To write a java program for message reversal using TCP.

Algorithm

Tcp server
1. Create a server socket and wait for client connection.
2. Accept the client connection.
3. Receive a message from client.
4. Reverse the message.
5. Send the reverse message back to client.

TCP Client
1. Create a socket and connect to the server.

2. Read the message from the user.

3. Send the message to the server.

4. Receive the reversed message fom the server.

5. Display the server response.

Program

Server
import [Link].*;

import [Link].*;

public class TCPMessageServer {

public static void main(String[] args) {

try {

ServerSocket serverSocket = new ServerSocket(9876);

[Link]("TCP server is running...");


68
Socket socket = [Link]();

BufferedReader in = new BufferedReader(new InputStreamReader([Link]()));

PrintWriter out = new PrintWriter([Link](), true);

String message = [Link]();

String reversedMessage = new StringBuilder(message).reverse().toString();

[Link]("TCP Reversed Message: " + reversedMessage);

[Link](reversedMessage);

[Link]();

[Link]();

} catch (Exception e) {

[Link]();

Client
import [Link].*;

public class TCPMessageClient {

public static void main(String[] args) {

try {

Socket socket = new Socket("localhost", 9876);

BufferedReader userInput = new BufferedReader(new InputStreamReader([Link]));

PrintWriter out = new PrintWriter([Link](), true);

BufferedReader in = new BufferedReader(new InputStreamReader([Link]()));

[Link]("Enter a message for TCP: ");

String message = [Link]();

[Link](message);

String response = [Link]();


69
[Link]("From TCP server: " + response);

[Link]();

catch (Exception e) {

[Link]();

}}}

Output

Server

Client

Result
Thus the java program for message reversal using TCP was written executed and output was
verified successfully.

70
Ex No:8 C
UDP PROGRAM: MESSAGE REVERSAL

Aim
To write a java program to message Reversal using UDP

Algorithm

UDP server
1. Create a data gram socket.
2. Receive a message from the client.
3. Optionally simulate packet loss.
4. Reverse the message.
5. Send the reverse message back to client.

UDP Client
1. Create a datagram socket.

2. Read the message from the user.

3. Send the message to the server.

4. Receive the reversed message from the server.

5. Display the server response.

Program

Server
import [Link].*;

public class UDPMessageServer {

public static void main(String[] args) {

DatagramSocket serverSocket = null;

try {

serverSocket = new DatagramSocket(9877);

byte[] receiveData = new byte[1024];


71
byte[] sendData;
[Link]("UDP server is running...");
while (true) {

DatagramPacket receivePacket = new DatagramPacket(receiveData, [Link]);


[Link](receivePacket);
String message = new String([Link](), 0, [Link]());
// Simulate random packet loss
if ([Link]() > 0.9) {
[Link]("UDP packet lost: " + message);
continue; // Skip to the next iteration
}

// Reverse the message


String reversedMessage = new StringBuilder(message).reverse().toString();
sendData = ("UDP Reversed Message: " + reversedMessage).getBytes();
// Get the client's address and port
InetAddress clientAddress = [Link]();
int clientPort = [Link]();
// Create and send the response packet
DatagramPacket sendPacket = new DatagramPacket(sendData, [Link], clientAddress,
clientPort);
[Link](sendPacket);
[Link]("Processed message from client: " + message);

}
} catch (Exception e) {
[Link]();
} finally {
if (serverSocket != null && ![Link]()) {
[Link]();
}

72
}
}
}

Client
import [Link].*;

import [Link].*;

public class UDPMessageClient {

public static void main(String[] args) {

DatagramSocket clientSocket = null;

try {

clientSocket = new DatagramSocket();

InetAddress serverAddress = [Link]("localhost");

BufferedReader userInput = new BufferedReader(new InputStreamReader([Link]));

byte[] sendData;

byte[] receiveData = new byte[1024];

[Link]("Enter a message for UDP (type 'exit' to quit): ");

String message;

while (!(message = [Link]()).equalsIgnoreCase("exit")) {

sendData = [Link]();

// Create and send the packet

DatagramPacket sendPacket = new DatagramPacket(sendData, [Link], serverAddress, 9877);

[Link](sendPacket);

// Receive the response

DatagramPacket receivePacket = new DatagramPacket(receiveData, [Link]);

[Link](receivePacket);

String serverResponse = new String([Link](), 0, [Link]());

73
[Link]("From server: " + serverResponse);

[Link]("Enter a message for UDP (type 'exit' to quit): ");

}
} catch (Exception e) {

[Link]();

} finally {

if (clientSocket != null && ![Link]()) {

[Link]();

Output

Server

74
Client

Result
Thus the java program for message reversal using TCP was written executed and output was
verified successfully.

75
Ex No: 9A SIMULATION OF LINK STATE ROUTING ALGORITHM

Aim
To implement the Link State Routing Algorithm

Theory
Link State Vector Algorithm
❖ In Link state routing, each router share its information of its neighbors with every other router
in the inter-network.

Knowledge about the neighborhood


❖ Instead of sending its entire routing table, a router sends information about its neighborhood
only.

To all router
❖ Each router send this information to every other router on the internetworking, not just to its
neighbors.
❖ If s does so by a process called “flooding” it means that a router sends its information.

Information sharing when there is a Change


❖ Each router sends out information about the neighbors when there is a change.

Information sharing
❖ Link state routing process use the same internet work as distance vector algorithm.
❖ Here each other sends its knowledge about is neighbors to every other router in the internet
work.
❖ Cost is applied only by routers and not by any other station on a network, if cost was added by
every station, instead of by routers alone, it would accumulate unpredictably.

76
❖ Cost is applied as a packet leaves the router rather then as if enters. Most networks are broadcast
networks. When a packet is in network every station, including the router, can pick it up, we cannot assign
any cost to a packet.

Advertiser Network Cost Neighbor Getting information about neighbors


❖ A router gets its information about its neighbors by periodically sending them a short greeting
packet.
❖ If the neighbor responds to the greeting as expected, it is assumed to be alive and functioning.

Initialization
❖ Imagine that all routers in our sample internet work come up at the same time.
❖ Each router sends a greeting packet to its neighbors to find out the state of each link.

Link – State Database


❖ Every router every LSP and puts the information into a link-state database.
❖ Because every router receives the same LSPs every router builds the same database.
❖ It stores this database on its disk and uses it to calculate its routing table. If a router is added to
be deleted from the system, the whole database must be shared for fast updating.

Procedure

1. Open Cisco Packet Tracer

Launch Cisco Packet Tracer.

2. Add and Connect Routers

Use the editor to add routers and connect them. Ensure proper physical connections between
routers.

3. Assign IP Addresses

Configure IP addresses on router interfaces:

77
Router1: Interface Fa0/0: ip address [Link] [Link]

Router2: Interface Fa0/0: ip address [Link] [Link]

Interface Fa0/1: ip address [Link] [Link]

Enable OSPF:

Enable OSPF on the routers:

Router1: router ospf 1

network [Link] [Link] area 0

Router2: router ospf 1

network [Link] [Link] area 0

network [Link] [Link] area 0

Connect Nearby Routers

OSPF automatically calculates the shortest path within an area. By enabling OSPF on both routers and
defining network statements for their interfaces, you establish a connection between them.

78
Output

Result

Thus the Simulation of Link State Routing Algorithm using cisco packet tracer is studied
Successfully.

79
EX NO: 9b LINK STATE ROUTING ALGORITHM

Aim
To write a program to simulate Link State Routing algorithm.

Algorithm
Step 1: Create a network.
Step 2: Assign cost to the edges in the network.
Step 3: Initialize the distance of the node itself as zero.
Step 4: The node is taken and chosen as a root node of the tree, this creates the tree with a
single node, and now set the total cost of each node to some value based on the information
in Link State Database.
Step 5: Now the node selects one node, among all the nodes not in the tree like structure,
which is nearest to the root, and adds this to the [Link] shape of the tree gets changed
Step 6: After this node is added to the tree, the cost of all the nodes not in the tree needs to be
updated because the paths may have been changed.
Step 7: The node repeats the Step 5 and Step 6 until all the nodes are added in the tree.
Step 8: Print the shortest path from source to destination.

Program
import [Link];

import [Link];

import [Link];

import [Link];

public class Dijkstra {

private int[] distances;

private Set<Integer> settled;

private Set<Integer> unsettled;


private int number_of_nodes;

private int[][] adjacencyMatrix;

public Dijkstra(int number_of_nodes) {

80
this.number_of_nodes = number_of_nodes;

distances = new int[number_of_nodes + 1];

settled = new HashSet<>();

unsettled = new HashSet<>();

adjacencyMatrix = new int[number_of_nodes + 1][number_of_nodes + 1];

public void dijkstra_algorithm(int[][] adjacency_matrix, int source) {

int evaluationNode;

for (int i = 1; i <= number_of_nodes; i++) {

for (int j = 1; j <= number_of_nodes; j++) {

adjacencyMatrix[i][j] = adjacency_matrix[i][j];

for (int i = 1; i <= number_of_nodes; i++) {

distances[i] = Integer.MAX_VALUE;

[Link](source);

distances[source] = 0;

while (![Link]()) {

evaluationNode = getNodeWithMinimumDistanceFromUnsettled();

[Link](evaluationNode);

[Link](evaluationNode);

81
evaluateNeighbours(evaluationNode);

private int getNodeWithMinimumDistanceFromUnsettled() {

int min = Integer.MAX_VALUE;

int node = 0;

for (Integer vertex : unsettled) {

if (distances[vertex] < min) {

min = distances[vertex];

node = vertex;

return node;

private void evaluateNeighbours(int evaluationNode) {

int edgeDistance;

int newDistance;

for (int destinationNode = 1; destinationNode <= number_of_nodes; destinationNode++) {

if (![Link](destinationNode)) {

if (adjacencyMatrix[evaluationNode][destinationNode] != Integer.MAX_VALUE) {

edgeDistance = adjacencyMatrix[evaluationNode][destinationNode];

newDistance = distances[evaluationNode] + edgeDistance;

if (newDistance < distances[destinationNode]) {

distances[destinationNode] = newDistance;

[Link](destinationNode);

82
}

public static void main(String[] args) {

int[][] adjacency_matrix;

int number_of_vertices;

int source = 0, destination = 0;

Scanner scan = new Scanner([Link]);

try {

[Link]("Enter the number of vertices");

number_of_vertices = [Link]();

adjacency_matrix = new int[number_of_vertices + 1][number_of_vertices + 1];

[Link]("Enter the Weighted Matrix for the graph");

for (int i = 1; i <= number_of_vertices; i++) {

for (int j = 1; j <= number_of_vertices; j++) {

adjacency_matrix[i][j] = [Link]();

if (i == j) {

adjacency_matrix[i][j] = 0;

} else if (adjacency_matrix[i][j] == 0) {

adjacency_matrix[i][j] = Integer.MAX_VALUE;

83
[Link]("Enter the source ");

source = [Link]();

[Link]("Enter the destination ");

destination = [Link]();

Dijkstra dijkstraAlgorithm = new Dijkstra(number_of_vertices);

dijkstraAlgorithm.dijkstra_algorithm(adjacency_matrix, source);

[Link]("The Shortest Path from source " + source + " to " + destination + " is: "
+ [Link][destination]);

} catch (Exception e) {

[Link]("Wrong Input Format");

} finally {

[Link]();

Output

84
Result
Thus a program to simulate Link State Routing algorithm is executed successfully.

85
SIMULATION OF DISTANCE VECTOR
Ex No: 9 C
ROUTING ALGORITHM

Aim

To implement the Distance Vector Routing Algorithm and understand how routers share
routing information to calculate the shortest path in a network.

Theory
In the Distance Vector routing algorithm, each router maintains a table of the best
(shortest) distance to all other routers in the network. This algorithm works by exchanging this
distance information with neighboring routers. Each router updates its routing table based on the
distance vector received from its neighbors.

1. Routing Table:
o A table maintained by each router that holds the distance (or cost) to reach every
destination in the network.
2. Distance Vector:
o The vector (list) of distances from a router to all other routers. Each router sends
this vector to its immediate neighbors.
3. Cost:
o The cost is typically based on the number of hops (or other metrics like bandwidth
or delay). It helps in determining the shortest path to a destination.
4. Periodic Updates:
o Routers periodically exchange routing tables with their neighbors. If a better route
is found, the router updates its routing table and propagates the information to its
neighbors.
5. Convergence:
o Convergence happens when all routers have the correct routing table, meaning all
the paths have been updated with the shortest distances.

Procedure

1. Initialization:
o Initially, each router knows only the cost to reach its direct neighbors. For non-
neighboring routers, the cost is considered to be infinite.
2. Exchange of Information:
o Routers periodically exchange routing tables with their neighbors, and each router
recalculates its routing table based on the received information.

86
3. Bellman-Ford Algorithm:
o This algorithm is used to calculate the shortest path to each destination in the
network by considering the shortest paths to all neighbors.
4. Routing Table Update:
o If a router receives a routing table from a neighbor that offers a better (lower-cost)
path to any destination, it updates its own routing table and forwards the new
information to its neighbors.

Steps to implement distance vector routing algorithm

1. Open Cisco Packet Tracer

 Launch Cisco Packet Tracer to create a network topology.

2. Add and Connect Routers

 Add two or more routers to the workspace and connect them using appropriate cables
(serial or Ethernet).

3. Assign IP Addresses

 Assign IP addresses to the interfaces on the routers to enable communication between


them. Example:
o Router1:
 Interface Fa0/0: ip address [Link] [Link]
o Router2:
 Interface Fa0/0: ip address [Link] [Link]
o Router3:
 Interface Fa0/0: ip address [Link] [Link]
o PC1:
 IP address: [Link] [Link]
 Default gateway: [Link]
o PC2:
 IP address: [Link] [Link]
 Default gateway: [Link]
o PC3:
 IP address: [Link] [Link]
 Default gateway: 192.168.30.

4. Enable Routing Protocol (RIP)

 For the Distance Vector routing algorithm, enable RIP (Routing Information Protocol) on
each router.

87
o Router1 Configuration:

Router(config-if)#exit
Router(config)#interface Serial2/0
Router(config-if)#
Router(config-if)#exit
Router(config)# router rip
Router(config-router)# network [Link]
Router(config-router)# network [Link]
Router(config-router)#

o Router2 Configuration:

Router(config-if)#exit
Router(config)# router rip
Router(config-router)# network [Link]
Router(config-router)# network [Link]
Router(config-router)# network [Link]
Router(config-router)#

o Router3 Configuration:

Router(config-if)#
Router(config-if)#exit
Router(config)# router rip
Router(config-router)# network [Link]
Router(config-router)# network [Link]
Router(config-router)#

5. Establish Connection Between Routers

 When RIP is enabled, routers exchange their routing tables. This automatically builds the
routing table for each router based on the shortest path to each destination.

6. Monitor Updates

 Routers will periodically exchange updates. If a router finds a shorter path to a


destination through its neighbor, it will update its routing table and send this updated
information to its neighbors.

88
Output

89
Result

Thus the Simulation of Distance Vector Routing Algorithm using cisco packet tracer is
studied successfully.

90
EX NO:9D DISTANCE VECTOR ROUTING ALGORITHM
USING JAVA

Aim
To write a program to simulate Distance Vector Routing algorithm.

Algorithm
Step 1: Create a network.
Step 2: Assign cost to the edges in the network.
Step 3: Initialize the distance of the node itself as zero.
Step 4: Assign the edge cost as the cost for the immediate neighbours and for other nodes assign the
value as infinity.
Step 5: From time-to-time, each node sends its own distance vector estimate to neighbors. 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 Bellman Ford equation:

Dx(y) = min { C(x,v) + Dv(y)} for each node y∈ N


Step 6: Print the routing table.

Program

import [Link];
import [Link].*;
public class DVR {
static int graph[][];
static int via[][];
static int rt[][];
static int v;
static int e;
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
[Link]("Please enter the number of Vertices: ");
v = [Link]([Link]());
[Link]("Please enter the number of Edges: ");
e = [Link]([Link]());
graph = new int[v][v];
via = new int[v][v];
rt = new int[v][v];
for(int i = 0; i < v; i++)
for(int j = 0; j < v; j++)
91
{
if(i == j)
graph[i][j] = 0;
else
graph[i][j] = 9999;
}

for(int i = 0; i < e; i++)


{
[Link]("Please enter data for Edge " + (i + 1) + ":");
[Link]("Source: ");
int s = [Link]([Link]());
s--;
[Link]("Destination: ");
int d = [Link]([Link]());
d--;
[Link]("Cost: ");
int c = [Link]([Link]());
graph[s][d] = c;
graph[d][s] = c;
}

dvr_calc_disp("The initial Routing Tables are: ");

[Link]("Please enter the Source Node for the edge whose cost has changed: ");
int s = [Link]([Link]());
s--;
[Link]("Please enter the Destination Node for the edge whose cost has changed: ");
int d = [Link]([Link]());
d--;
[Link]("Please enter the new cost: ");
int c = [Link]([Link]());
graph[s][d] = c;
graph[d][s] = c;

dvr_calc_disp("The new Routing Tables are: ");


}

static void dvr_calc_disp(String message)


{
[Link]();
init_tables();
update_tables();
[Link](message);
print_tables();
[Link]();
}

static void update_table(int source)


{
92
for(int i = 0; i < v; i++)
{
if(graph[source][i] != 9999)
{
int dist = graph[source][i];
for(int j = 0; j < v; j++)
{
int inter_dist = rt[i][j];
if(via[i][j] == source)
inter_dist = 9999;
if(dist + inter_dist < rt[source][j])
{
rt[source][j] = dist + inter_dist;
via[source][j] = i;
}
}
}
}
}

static void update_tables()


{
int k = 0;
for(int i = 0; i < 4*v; i++)
{
update_table(k);
k++;
if(k == v)
k = 0;
}
}

static void init_tables()


{
for(int i = 0; i < v; i++)
{
for(int j = 0; j < v; j++)
{
if(i == j)
{
rt[i][j] = 0;
via[i][j] = i;
}
else
{
rt[i][j] = 9999;
via[i][j] = 100;
}
}
}
93
}

static void print_tables()


{
for(int i = 0; i < v; i++)
{
for(int j = 0; j < v; j++)
{
[Link]("Dist: " + rt[i][j] + " ");
}
[Link]();
}
}

Output

Result
Thus a program to simulate Distance Vector Routing algorithm is executed successfully.
94
SIMULATION OF ERROR CORRECTION CODE
EX NO: 10 A
(CRC)

Aim
To simulate the Error Correction Code using Java.

Theory

Cyclic redundancy check (CRC)

 Unlike checksum scheme, which is based on addition, CRC is based on binary


division.
 In CRC, a sequence of redundant bits, called cyclic redundancy check bits, are
appended to the end of data unit so that the resulting data unit becomes exactly
divisible by a second, predetermined binary number.
 At the destination, the incoming data unit is divided by the same number. If at this
step there is no remainder, the data unit is assumed to be correct and is therefore
accepted.
 A remainder indicates that the data unit has been damaged in transit and therefore
must be rejected.

95
Example

Algorithm

1. Open the editor and type the program for error detection.
2. Get the input in the form of bits.
3. Append the redundancy bits.
4. Divide the appended data using a divisor polynomial.

5. The resulting data should be transmitted to the receiver.

6. At the receiver the received data is entered.

7. The same process is repeated at the receiver.


8. If the remainder is zero there is no error otherwise there is some error in the received bits.
9. Run the program.

96
Program

import [Link].*;

class CRC {

public static void main(String args[]) throws IOException {

BufferedReader br = new BufferedReader(new InputStreamReader([Link]));

[Link]("Enter Generator:");

String gen = [Link]();

[Link]("Enter Data:");

String data = [Link]();

String code = data;

while ([Link]() < ([Link]() + [Link]() - 1)) {

code = code + "0";

code = data + div(code, gen);

[Link]("The transmitted Code Word is: " + code);

[Link]("Please enter the received Code Word:");

String rec = [Link]();

if ([Link](div(rec, gen)) == 0) {

[Link]("The received code word contains no errors.");

} else {

[Link]("The received code word contains errors.");

static String div(String num1, String num2) {

97
int pointer = [Link]();

String result = [Link](0, pointer);

String remainder = "";

for (int i = 0; i < [Link](); i++) {

if ([Link](i) == [Link](i)) {

remainder += "0";

} else {

remainder += "1";

while (pointer < [Link]()) {

if ([Link](0) == '0') {

remainder = [Link](1, [Link]());

remainder = remainder + [Link]([Link](pointer));

pointer++;

result = remainder;

remainder = "";

for (int i = 0; i < [Link](); i++) {

if ([Link](i) == [Link](i)) {

remainder += "0";

} else {

remainder += "1";

98
}

return [Link](1, [Link]());

Output

Result

Thus a program to simulate error correction code was executed successfully.

99
SIMULATION OF ERROR CORRECTION -
Ex No:10 B
HAMMING CODE

Aim
To write a program for the simulation of Error Correction - Hamming code.

Algorithm

1. Write the bit positions in binary form.


2. The bit positions should be started from 1(1, 10, 11, 100, etc.).
3. Mark all those bits as parity bits which are a power of 2 (1, 2, 4, 8, etc.).

4. Mark all the other bit positions as data bits.

5. Each data bit is included in a unique set of parity bits, as determined by its bit position
in binary form.
i. All those bits positions whose binary representation have 1 in the 4th position
from the least significant bit (8-15, 24-31, 40-47, etc.) are covered by the 8th
parity bit.
ii. All those bits positions whose binary representation have 1 in the 3rd position
from the least significant bit(4-7, 12-15, 20-23, etc.) are covered by the 4th
parity bit.
iii. All those bits positions whose binary representation have 1 in the second
position from the least significant bit(2, 3, 6, 7, 10, 11, etc.) are covered by the
2nd parity bit.
iv. All those bits positions whose binary representation have 1 in the least
significant position(1, 3, 5, 7, 9, 11, etc.) are covered by the second parity bit.
v. All the bits, where the bitwise AND of the parity position
vi. The bit position is non-zero, are covered by each parity bit.
6. Since we check for even parity, set a parity bit to 1 if the total number of ones in the
positions it checks is odd.
7. Set a parity bit to 0 when the total number of ones in the bit positions it covers is an
even.

100
Program

package [Link];
import [Link];
class HammingCodeExample {
public static void main(String args[]) {
int size, hammingCodeSize, errorPosition;
int arr[];
int hammingCode[];
Scanner sc = new Scanner([Link]);
[Link]("Enter the number of data bits:");
size = [Link]();
arr = new int[size];
for (int i = 0; i < size; i++) {
[Link]("Enter " + (size - i) + "-bit of the data:");
arr[size - i - 1] = [Link]();
}
[Link]("The data you entered is:");
for (int i = 0; i < size; i++) {
[Link](arr[size - i - 1]);
}
[Link]();
hammingCode = getHammingCode(arr);
hammingCodeSize = [Link];
[Link]("The generated Hamming code is:");
for (int i = 0; i < hammingCodeSize; i++) {
[Link](hammingCode[hammingCodeSize - i - 1]);
}
[Link]();
[Link]("Enter the position of a bit to alter (0 for no error):");
errorPosition = [Link]();
[Link]();
if (errorPosition != 0)
{

101
hammingCode[errorPosition - 1] = (hammingCode[errorPosition - 1] + 1) % 2;
}
[Link]("Sent Data is:");
for (int i = 0; i < hammingCodeSize; i++) {
[Link](hammingCode[hammingCodeSize - i - 1]);
}
[Link]();
receiveData(hammingCode, hammingCodeSize - [Link]);
}
static int[] getHammingCode(int data[]) {
int size = [Link];
int i = 0, parityBits = 0, j = 0, k = 0;
while (i < size) {
if ([Link](2, parityBits) == (i + parityBits + 1)) {
parityBits++;
}
else
{
i++;
}
}
int returnData[] = new int[size + parityBits];
for (i = 1; i <= [Link]; i++) {
if ([Link](2, j) == i) {
returnData[i - 1] = 2;
j++;
}
else
{
returnData[k + j] = data[k++];
}
}

102
for (i = 0; i < parityBits; i++)
{
returnData[(int) [Link](2, i) - 1] = getParityBit(returnData, i);
}
return returnData;
}
static int getParityBit(int returnData[], int pow) {
int parityBit = 0;
int size = [Link];
for (int i = 0; i < size; i++) {
if (returnData[i] != 2) {
int k = i + 1;
String str = [Link](k);
int temp = ([Link](str) / (int) [Link](10, pow)) % 10;
if (temp == 1 && returnData[i] == 1) {
parityBit = (parityBit + 1) % 2;
}
}
}
return parityBit;
}
static void receiveData(int data[], int parityBits) {
int size = [Link];
int parityArray[] = new int[parityBits];
String errorLoc = "";
for (int pow = 0; pow < parityBits; pow++) {
for (int i = 0; i < size; i++) {
int j = i + 1;
String str = [Link](j);
int bit = ([Link](str) / (int) [Link](10, pow)) % 10;
if (bit == 1 && data[i] == 1) {
parityArray[pow] = (parityArray[pow] + 1) % 2;
}

103
}
errorLoc = parityArray[pow] + errorLoc;
}
int finalLoc = [Link](errorLoc, 2);
if (finalLoc != 0) {
[Link]("Error is found at location " + finalLoc + ".");
data[finalLoc - 1] = (data[finalLoc - 1] + 1) % 2;
[Link]("After correcting the error, the code is:");
for (int i = 0; i < size; i++) {
[Link](data[size - i - 1]);
}
[Link]();
}
else
{
[Link]("There is no error in the received data.");
}
[Link]("The data sent from the sender:");
int pow = parityBits - 1;
for (int k = size; k > 0; k--) {
if ([Link](2, pow) != k) {
[Link](data[k - 1]);
}
else
{
pow--;
}
}
[Link]();
}
}

104
Output:

Result
Thus the program for Error Correction using Hamming Code was implemented and the
output was verified successfully.

105

You might also like