Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
37 views41 pages

Unit 4 Simulation Notes

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)
37 views41 pages

Unit 4 Simulation Notes

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

UNIT 4 SIMULATIONS

Simulation on DNS using UDP sockets- ARP /RARP protocols-Simulation of Congestion


Control Algorithms-Study of TCP/UDP performance using Simulation tool-Simulation of
Distance Vector/ Link State Routing algorithm-Performance evaluation of Routing protocols
using Simulation tool.

4.1. Simulation on DNS using UDP sockets :

Simulation is the process of learning by doing. Whenever there is something new in the
world, we try to analyze it first by examining it and in the process get to learn a lot of
things. This entire course is called Simulation
Introduction to DNS and UDP in IoT Networks:
The Domain Name System (DNS) is a critical component of the Internet, acting as a
directory service that translates humanreadable domain names into IP addresses. In the
context of Internet of Things (IoT) networks, DNS enables IoT devices to communicate with
servers, cloud services, and other devices using easytoremember domain names. UDP (User
Datagram Protocol) is often used with DNS in IoT networks due to its low overhead and
speed, making it suitable for resourceconstrained devices.

4.1.1. Overview of DNS in IoT Networks

1. Role of DNS in IoT

DNS plays a crucial role in IoT networks by providing a mechanism for device identification
and service discovery. It allows IoT devices to resolve domain names to IP addresses,
enabling communication with external servers, cloud platforms, or other IoT devices.

2. Challenges in IoT DNS Implementation

Resource Constraints: IoT devices often have limited processing power, memory, and
energy, making efficient DNS resolution critical.
Security Concerns: DNS is vulnerable to attacks like DNS spoofing, which can be
particularly problematic in IoT environments where security is a major concern.
Network Dynamics: IoT networks can be highly dynamic, with devices frequently joining
and leaving the network, requiring DNS mechanisms to adapt quickly.

4.1.2. UDP Sockets and Their Use in DNS for IoT

1. Introduction to UDP

UDP is a lightweight, connectionless protocol that allows data to be sent without establishing
a connection. This makes it ideal for timesensitive applications like DNS queries, where
speed is prioritized over reliability. UDP does not guarantee message delivery, order, or data
integrity, which can be a concern but is often acceptable for DNS lookups due to their
relatively small size and low frequency of errors.

2. UDP Sockets in IoT

Advantages:
Low Overhead: UDP's simplicity and lack of connection establishment reduce the
processing and memory requirements on IoT devices.
Speed: The absence of handshaking and connection setup allows for faster communication,
which is critical for realtime applications in IoT.

Disadvantages:
Lack of Reliability: UDP does not ensure that messages are delivered or that they arrive in
the correct order, which can be problematic for certain applications.
Security Issues: The lack of builtin security features makes UDP vulnerable to attacks like
spoofing and amplification.

4.1.3. Implementing DNS Using UDP Sockets in IoT Networks

1. Setting Up UDP Sockets

Socket Creation: In a typical implementation, a UDP socket is created using the `socket()`
function, specifying the `AF_INET` (IPv4) or `AF_INET6` (IPv6) address family and the
`SOCK_DGRAM` type for datagrambased communication.
Binding and Listening: The socket is bound to a specific port number, usually port 53 for
DNS, allowing it to receive incoming DNS queries.

2. DNS Query and Response Process

Query Formation: IoT devices construct a DNS query by specifying the domain name and
the type of record requested (e.g., A, AAAA, MX).
Sending the Query: The query is sent through the UDP socket to a DNS server.
Receiving the Response: The device listens for a response from the DNS server, which
includes the resolved IP address or an error message if the domain cannot be resolved.

3. Optimizing DNS Resolution in IoT

Caching: To reduce latency and conserve resources, IoT devices can cache DNS responses
for a specified duration (TimeToLive, TTL).
Load Balancing: DNS servers can distribute traffic among multiple IP addresses for a single
domain, balancing the load across resources.
Security Enhancements: DNSSEC (DNS Security Extensions) can be implemented to
protect against spoofing and other attacks, though this adds complexity and overhead.

4.1.4. Security Considerations

1. DNS Spoofing and Cache Poisoning

DNS spoofing involves intercepting and altering DNS responses to redirect traffic to malicious
sites. Cache poisoning is a related attack where incorrect DNS data is cached, leading to
incorrect IP address resolution.

2. Mitigation Strategies

Use of DNSSEC: DNSSEC adds a layer of security by enabling DNS responses to be verified
for authenticity.
Regular Updates and Monitoring: Keeping DNS software and configurations up to date and
monitoring for suspicious activities can help mitigate threats.

4.1.5. Conclusion
DNS, facilitated by UDP sockets, is a fundamental component of IoT networks, enabling
efficient device communication. While UDP provides a lightweight and fast mechanism for
DNS resolution, it comes with challenges related to reliability and security. Proper
implementation, including caching, security measures, and efficient socket management, is crucial
for maintaining robust and secure DNS operations in IoT environments.

4.2. SIMULATING ARP /RARP PROTOCOLS:


4.2.1. Address Resolution Protocol (ARP) and its types:
Address Resolution Protocol (ARP) is a communication protocol used to find the MAC (Media
Access Control) address of a device from its IP address. This protocol is used when a device
wants to communicate with another device on a Local Area Network or Ethernet.
Important ARP Terms
 ARP Cache :- After receiving the MAC address, ARP passes it to the sender where it is
stored in a table for future reference. And this is called ARP Cache which is later used to
obtain the MAC address.
 ARP Cache Timeout :- This is the time in which the MAC address can remain in the ARP
Cache.
 ARP request :- Broadcasting a packet over the network to verify whether we have arrived
at the destination MAC address.
 ARP response/reply :- It is a MAC address response that the sender receives from the
receiver which helps in further communication of data.
4.2.2. Types of ARP
There are four types of Address Resolution Protocol, which is given below:
a) Proxy ARP
b) Gratuitous ARP
c) Reverse ARP (RARP)
d) Inverse ARP

FIGURE: 4.1. ARP


a) Proxy ARP Proxy ARP is a method through which a Layer 3 devices may respond to
ARP requests for a target that is in a different network from the sender. The Proxy ARP
configured router responds to the ARP and map the MAC address of the router with the
target IP address and fool the sender that it is reached at its destination.
At the backend, the proxy router sends its packets to the appropriate destination because the
packets contain the necessary information.
Example If Host A wants to transmit data to Host B, which is on the different network, then
Host A sends an ARP request message to receive a MAC address for Host B. The router
responds to Host A with its own MAC address pretend itself as a destination. When the data is
transmitted to the destination by Host A, it will send to the gateway so that it sends to Host B.
This is known as proxy ARP.

b) Gratuitous ARP Gratuitous ARP is an ARP request of the host that helps to identify the
duplicate IP address. It is a broadcast request for the IP address of the router. If an ARP
request is sent by a switch or router to get its IP address and no ARP responses are
received, so all other nodes cannot use the IP address allocated to that switch or router.
Yet if a router or switch sends an ARP request for its IP address and receives an ARP
response, another node uses the IP address allocated to the switch or router.
 There are some primary use cases of gratuitous ARP that are given below:
 The gratuitous ARP is used to update the ARP table of other devices.
 It also checks whether the host is using the original IP address or a duplicate one.
c) Reverse ARP (RARP) It is a networking protocol used by the client system in a local area
network (LAN) to request its IPv4 address from the ARP gateway router table. A table is created
by the network administrator in the gatewayrouter that is used to find out the MAC address to the
corresponding IP address.
When a new system is set up or any machine that has no memory to store the IP address, then the
user has to find the IP address of the device. The device sends a RARP broadcast packet,
including its own MAC address in the address field of both the sender and the receiver hardware.
A host installed inside of the local network called the RARPserver is prepared to respond to such
type of broadcast packet. The RARP server is then trying to locate a mapping table entry in the
IP to MAC address. If any entry matches the item in the table, then the RARP server sends the
response packet along with the IP address to the requesting computer.
RARP is commonly known as a "Reverse Address Resolution Protocol". The RARP protocol is
also a type of network layer protocol. A TCP/IP protocol enables any host to get its true IP
address from the network server. As the name defines, the RARP protocol is an extended version
of the ARP. It is usually the opposite of the ARP protocol.
Advantages and Disadvantages of RARP
There are various advantages and disadvantages of RARP. Some main advantages and
disadvantages of RARP are as follows:
Advantages
 It is a network access layer protocol that is utilized to transfer data between two sites in a
network.
 It is utilized to convert an Ethernet address to an IP address.
 It is accessible for LAN technologies such as FDDI, token ring LANs, and many others.
Disadvantages
 It can't handle the subnetting operation since no network masks are transferred. If the
network is categorized into subnets, every subnet must have its own RARP server.
 It should be placed on the same physical network as the client.
 It does not fully exploit the capability of a network such as Ethernet.
 The computer transfers the RARP protocol request through a lowcost network layer. As a
result, a router cannot forward the packet since the computer system makes the RARP
request on a relatively low layer of the network.
 In a modern network, setting up a computer system is impossible.

d) Inverse ARP (InARP) Inverse ARP is inverse of the ARP, and it is used to find the IP
addresses of the nodes from the data link layer addresses. These are mainly used for the frame
relays, and ATM networks, where Layer 2 virtual circuit addressing are often acquired from
Layer 2 signaling. When using these virtual circuits, the relevant Layer 3 addresses are available.
Advantages
 The primary purpose of this protocol is to enable any computer system on a network to
enhance a mapping between two addresses, including IP and physical.
 If you know the IP address of the same system, you may utilize an ARP protocol to
determine the MAC address.
 The set of mappings saved on the host is referred to as the ARP cache/table.
 End nodes should not be arranged in such a way that they may detect MAC addresses. It
may be found when needed.
Disadvantages
 ARP Spoofing is a technique that an attacker mainly utilizes to gain access to an Ethernet
network. It can result in data frame snooping on switched LAN networks, or the attacker
can terminate overall traffic, commonly known as ARP denial of service.
 ARP attacks may occur, including ARP spoofing and Denial of Service.
4.2.3. Working of ARP Protocol:
Below is a Working flow diagram of ARP Protocol

Figure. 4.2. ARP Protocol


Below is the working of address resolution protocol is being explained in some steps :-
 When a sender wants to communicate with a receiver, the sender first checks its ARP
cache. Sender checks whether the receiver’s MAC address is already present in the ARP
cache or not?
 If the receiver’s MAC address is already present in the ARP cache, the sender will
communicate with the receiver using that MAC address.
 If the MAC address of the receiver device is not already present in the ARP cache, then in
such a situation an ARP request message is prepared by the sender device.This message
contains the MAC address of the sender, IP address of the sender and IP address of the
receiver. The field containing the MAC address of the receiver is left blank because it is
being searched.
 Sender device broadcasts this ARP request message in the LAN. Because this is a
broadcast message, every device connected to the LAN receives this message.
 All devices match the receiver IP address of this request message with their own IP
address. Devices whose IP address does not match drop this request message.
 The device whose IP address matches the receiver IP address of this request message
receives this message and prepares an ARP reply message. This is a unicast message which
is sent only to the sender.
 In ARP reply message, the sender’s IP address and MAC address are used to send the reply
message. Besides, in this message the receiver also sends its IP address and MAC address.
 As soon as the sender device receives this ARP reply message, it updates its ARP cache
with the new information (Receiver’s MAC address). Now the MAC address of the
receiver is present in the ARP cache of the sender. The sender can send and receive data
without any problem.
4.2.4. Message Format of ARP Protocol:
Messages are sent to find the MAC address through ARP(address resolution protocol). These
messages are broadcast to all the devices in the LAN. The format of this message is being
shown in the diagram below :
Figure:4.3. Message format of ARP

All the fields given in ARP message format are being explained in detail below:-
 Hardware Type: The size of this field is 2 bytes. This field defines what type of Hardware
is used to transmit the message. The most common Hardware type is Ethernet. The value of
Ethernet is 1.
 Protocol Type: This field tells which protocol has been used to transmit the message.
substantially the value of this field is 2048 which indicates IPv4.
 Hardware Address Length: It shows the length of the tackle address in bytes. The size of
Ethernet MAC address is 6 bytes.
 Protocol Address Length: It shows the size of the IP address in bytes. The size of IP
address is 4 bytes.
 OP law: This field tells the type of message. If the value of this field is 1 also it’s a request
message and if the value of this field is 2 also it’s a reply message.
 Sender Hardware Address: This field contains the MAC address of the device
transferring the message.
 Sender Protocol Address: This field contains the IP address of the device transferring the
message.
 Target Hardware Address: This field is empty in the request message. This field contains
the MAC address of the entering device.
 Target Protocol Address: This field contains the IP address of the entering device.
Advantages of ARP Protocol
There are many Advantages of ARP protocol but below we have told you about some
important advantages.
 By using this protocol we can easily find out the MAC Address of the device.
 There is no need to configure the end nodes at all to extract the MAC address through this
protocol.
 Through this protocol we can easily translate IP address into MAC Address.
 There are four main types of this protocol. Which we can use in different ways, and they
prove to be very helpful.

4.2.5. SIMULATING ARP /RARP PROTOCOLS PROGRAM:


To write a python program for simulating ARP protocols using TCP.

ALGORITHM:

Client:

1. Start the program


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

1. Start the program


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

PROGRAM:

CLIENT:

import socket
s=socket.socket()
s.bind(('localhost',8000))
s.listen(5)
c,addr=s.accept()
address={"165.165.80.80":"6A:08:AA:C2","165.165.79.1":"8A:BC:E3:FA"};
while True:
ip=c.recv(1024).decode()
try:
c.send(address[ip].encode())
except KeyError:
c.send("Not Found".encode())
SERVER:

import socket
s=socket.socket()
s.connect(('localhost',8000))
while True:
REG NO:
ip=input("Enter logical Address : ")
s.send(ip.encode())
print("MAC Address",s.recv(1024).decode())
OUTPUT:

SERVER:
CLIENT:

4.3. Simulation of Congestion Control Algorithms:

There are several congestion control algorithms used in networking to manage traffic and avoid
congestion in networks. These algorithms are designed to optimize the use of network resources,
minimize packet loss, and ensure fairness among multiple flows. Here is a list of some widely
used congestion control algorithms:

4.3.1. TCP Congestion Control Algorithms

4.3.1.1. Active Queue Management (AQM) Algorithms

1. RED (Random Early Detection)


o Detects congestion early by probabilistically dropping packets before the queue is
full.
o Aims to prevent global synchronization.
2. Blue
o Manages queue length by adjusting the probability of packet marking/dropping.
o Uses packet loss and link idle events for adjustments.
3. CoDel (Controlled Delay)
o Targets minimizing packet delay.
o Drops packets when the minimum delay exceeds a threshold.
4. PIE (Proportional Integral controller Enhanced)
o Controls packet latency by adjusting the dropping probability.
o Uses the Proportional-Integral (PI) control theory.
5. FQ-CoDel (Flow Queue CoDel)
o Combines fair queuing with CoDel.
o Aims to provide low latency and fairness among flows.
4.3.1.2. Explicit Congestion Notification (ECN) Based Algorithms

1. DCTCP (Data Center TCP)


o Designed for data center networks.
o Uses ECN to provide more precise congestion signals.
2. L4S (Low Latency Low Loss Scalable Throughput)
o Uses ECN to signal congestion early and reduce latency.
o Designed for low latency and high throughput in modern networks.

4.3.1.3. Other Notable Congestion Control Algorithms

1. XCP (eXplicit Control Protocol)


o Uses explicit feedback from routers to adjust the congestion window.
o Provides more precise congestion control.
2. RCP (Rate Control Protocol)
o Uses explicit rate control feedback from routers.
o Aims to allocate network resources more effectively.
3. QUIC
o A transport protocol developed by Google.
o Uses a combination of congestion control algorithms like Cubic or BBR.
4. LEDBAT (Low Extra Delay Background Transport)
o Designed for background data transfers.
o Reduces impact on other traffic by keeping delays low.

These algorithms are implemented in various network devices and software, and each has its
own strengths and weaknesses depending on the specific network environment and application
requirements.

4.3.2. What is TCP Congestion Control?


Congestion control is a state in which a part of a network message traffic is so heavy that it slows
down network response time. When one part of the subnet (e.g. one or more routers in an area)
becomes overloaded, congestion results. Congestion control is a global issue which involves
every host and router within the subnet becomes overloaded.
FIGURE. 4.4. congestion control
TCP congestion control is a method used by the TCP protocol to manage data flow over a
network and prevent congestion. TCP uses a congestion window and congestion policy that
avoids congestion. Previously, we assumed that only the receiver could dictate the sender’s
window size. We ignored another entity here, the network. If the network cannot deliver the
data as fast as it is created by the sender, it must tell the sender to slow down. In other words,
in addition to the receiver, the network is a second entity that determines the size of the
sender’s window.
4.3.2.1. Congestion Policy in TCP
 Slow Start Phase: Starts slow increment is exponential to the threshold.
 Congestion Avoidance Phase: After reaching the threshold increment is by 1.
 Congestion Detection Phase: The sender goes back to the Slow start phase or the
Congestion avoidance phase.

4.3.2.1. Slow Start Phase


Exponential Increment: In this phase after every RTT the congestion window size increments
exponentially.
Example: If the initial congestion window size is 1 segment, and the first segment is
successfully acknowledged, the congestion window size becomes 2 segments. If the next
transmission is also acknowledged, the congestion window size doubles to 4 segments. This
exponential growth continues as long as all segments are successfully acknowledged.
Initially cwnd = 1
After 1 RTT, cwnd = 2^(1) = 2
2 RTT, cwnd = 2^(2) = 4
3 RTT, cwnd = 2^(3) = 8

4.3.2.2. Congestion Avoidance Phase


Additive Increment: This phase starts after the threshold value also denoted as ssthresh. The
size of CWND (Congestion Window) increases additive. After each RTT cwnd = cwnd + 1.
For example: if the congestion window size is 20 segments and all 20 segments are successfully
acknowledged within an RTT, the congestion window size would be increased to 21 segments
in the next RTT. If all 21 segments are again successfully acknowledged, the congestion window
size will be increased to 22 segments, and so on.
Initially cwnd = i
After 1 RTT, cwnd = i+1
2 RTT, cwnd = i+2
3 RTT, cwnd = i+3

4.3.2.3. Congestion Detection Phase


Multiplicative Decrement: If congestion occurs, the congestion window size is decreased. The
only way a sender can guess that congestion has happened is the need to retransmit a segment.
Retransmission is needed to recover a missing packet that is assumed to have been dropped by
a router due to congestion. Retransmission can occur in one of two cases: when the RTO timer
times out or when three duplicate ACKs are received.
Case 1: Retransmission due to Timeout – In this case, the congestion possibility is high.
(a) ssthresh is reduced to half of the current window size.
(b) set cwnd = 1
(c) start with the slow start phase again.

Case 2: Retransmission due to 3 Acknowledgement Duplicates – The congestion possibility is


less.
(a) ssthresh value reduces to half of the current window size.
(b) set cwnd= ssthresh
(c) start with congestion avoidance phase
Example
Assume a TCP protocol experiencing the behavior of slow start. At the 5th transmission round
with a threshold (ssthresh) value of 32 goes into the congestion avoidance phase and continues
till the 10th transmission. At the 10th transmission round, 3 duplicate ACKs are received by the
receiver and entered into additive increase mode. Timeout occurs at the 16th transmission round.
Plot the transmission round (time) vs congestion window size of TCP segments.
Figure. 4.5. Congestion Detection Phase
4.3.3. Goals of TCP congestion control:

 To increase the source send rate when the network is not congested.
 To share the network resources with other TCP flows in a “fair” way.
 To reduce the source send rate when the network is congested.
4.3.4. TCP congestion control algorithms:

 Slow start.
 Fast recovery.
 Network pricing.
 Congestion avoidance.
 Fast retransmit.
 TCP paging.
 Selective acknowledgment.
 Random early detection.
4.3.5. Sample code for TCP congestion control:
This is the code for packets handled in tcp congestion control
class PacketData : public AppData {
public:
PacketData(int sz) : AppData(PACKET_DATA) {
datalen_ = sz;
if (datalen_ > 0)
data_ = new unsigned char[datalen_];
else
data_ = NULL;
}
PacketData(PacketData& d) : AppData(d) {
datalen_ = d.datalen_;
if (datalen_ > 0) {
data_ = new unsigned char[datalen_];
memcpy(data_, d.data_, datalen_);
} else
data_ = NULL;
}
virtual ~PacketData() {
if (data_ != NULL)
delete []data_;
}
unsigned char* data() { return data_; }
virtual int size() const { return datalen_; }
virtual AppData* copy() { return new PacketData(*this); }
private:
unsigned char* data_;
int datalen_;
};

4.4. Study of TCP/UDP performance using Simulation Tool:

To study the performance of TCP and UDP using a simulation tool, you'll need to follow a
structured approach. Here’s a detailed guide:

4.4.1. Steps for Studying TCP/UDP Performance

1. Select a Simulation Tool

 NS-3: A popular network simulator with extensive support for TCP and UDP protocols.
 OMNeT++: A modular and extensible simulation library.
 GNS3: A graphical network simulator that allows the combination of virtual and real
devices.
 OPNET (Riverbed Modeler): A comprehensive tool for network simulation and
performance analysis.

2. Define Evaluation Metrics

 Throughput: The rate at which data is successfully transmitted.


 Latency (Delay): The time taken for a packet to travel from source to destination.
 Packet Loss: The number of packets lost during transmission.
 Jitter: The variation in packet arrival times.
 Goodput: The rate of useful data received, excluding protocol overhead.
 Connection Setup Time (TCP): Time taken to establish a connection (handshake).

3. Design Network Scenarios

 Topology: Define various network topologies (e.g., star, mesh, linear).


 Traffic Patterns: Use different traffic patterns such as constant bit rate (CBR) for UDP
and varying traffic loads for TCP.
 Node Configuration: Configure nodes with varying bandwidths, delays, and error rates.

4. Simulation Setup

 Configure Simulation Environment: Set up the network topology and define node
parameters.
 Implement Protocols: Enable and configure TCP and UDP protocols in the simulation
tool.
 Traffic Generation: Use traffic generation models to simulate data transfer using TCP
and UDP.
 Parameters: Define simulation parameters such as simulation time, link bandwidth, and
propagation delay.

5. Run Simulations

 Multiple Runs: Perform multiple simulation runs to obtain statistically significant


results.
 Different Scenarios: Test under various network conditions (e.g., different load levels,
mobility patterns).

6. Collect Data

 Log Files: Enable logging to capture detailed performance metrics.


 Statistics Collection: Use built-in tools or scripts to extract relevant metrics from the
simulation logs.

7. Analyze Results

 Throughput Analysis: Compare the throughput of TCP and UDP under different
conditions.
 Latency Analysis: Measure and compare the end-to-end delay for TCP and UDP
packets.
 Packet Loss Analysis: Evaluate the packet loss rate for both protocols.
 Jitter Analysis: Analyze the jitter experienced by UDP packets, which is crucial for real-
time applications.
 Goodput Analysis: Compare the goodput for TCP and UDP, focusing on the efficiency
of data transfer.

8. Visualize Data
 Graphs and Charts: Use tools like Excel, MATLAB, or built-in visualization tools in
the simulator to plot graphs and charts.
 Performance Comparison: Create comparative charts to highlight the differences
between TCP and UDP performance.

4.4.2. Example Scenarios

Scenario 1: Simple Point-to-Point Network

 Topology: Single link between two nodes.


 Traffic: Simulate a file transfer using TCP and a video stream using UDP.
 Metrics: Measure throughput, latency, and packet loss.

Scenario 2: Star Topology

 Topology: Central node connected to multiple peripheral nodes.


 Traffic: Generate traffic from the central node to all peripheral nodes using TCP and
UDP.
 Metrics: Evaluate how well TCP and UDP handle multiple simultaneous connections.

Scenario 3: Mesh Network

 Topology: Multiple nodes connected in a mesh topology.


 Traffic: Create random traffic patterns between nodes using both TCP and UDP.
 Metrics: Measure the scalability and robustness of TCP and UDP in a dense network.

4.4.3. Example NS2 Script

Here's an example script to simulate TCP and UDP performance in a simple network topology:

1. Create the Simulation Script (tcp_udp_simulation.tcl)

# Create a simulator object


set ns [new Simulator]

# Open the NS2 trace file


set tracefile [open out.tr w]
$ns trace-all $tracefile

# Open the NAM trace file


set namfile [open out.nam w]
$ns namtrace-all $namfile

# Define a 'finish' procedure


proc finish {} {
global ns tracefile namfile
$ns flush-trace
close $tracefile
close $namfile
exec nam out.nam &
exit 0
}

# Create nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]

# Create links
$ns duplex-link $n0 $n2 1Mb 10ms DropTail
$ns duplex-link $n1 $n2 1Mb 10ms DropTail
$ns duplex-link $n2 $n3 1Mb 10ms DropTail

# Setup TCP connection


set tcp0 [new Agent/TCP]
$tcp0 set class_ 2
$ns attach-agent $n0 $tcp0
set sink0 [new Agent/TCPSink]
$ns attach-agent $n3 $sink0
$ns connect $tcp0 $sink0
set ftp0 [new Application/FTP]
$ftp0 attach-agent $tcp0
$ftp0 set type_ FTP

# Setup UDP connection


set udp0 [new Agent/UDP]
$ns attach-agent $n1 $udp0
set null0 [new Agent/Null]
$ns attach-agent $n3 $null0
$ns connect $udp0 $null0
set cbr0 [new Application/Traffic/CBR]
$cbr0 attach-agent $udp0
$cbr0 set packet_size_ 512
$cbr0 set interval_ 0.005

# Schedule events
$ns at 0.5 "$ftp0 start"
$ns at 1.0 "$cbr0 start"
$ns at 4.5 "$ftp0 stop"
$ns at 5.0 "$cbr0 stop"
$ns at 6.0 "finish"

# Run the simulation


$ns run

Running the Simulation

1. Save the Script: Save the above script as tcp_udp_simulation.tcl.


2. Run NS2: Execute the script using the NS2 command:

ns tcp_udp_simulation.tcl
Analyze the Output:

 Trace File (out.tr): Contains detailed event logs.


 NAM File (out.nam): Visualize the network events using the NAM tool.

4.4.4. Analyzing the Results:

Extracting Metrics from the Trace File

 Throughput: Calculate throughput by analyzing the amount of data received over time.
 Latency: Measure the time difference between packet send and receive events.
 Packet Loss: Count the number of packets sent versus packets received.
 Jitter: Calculate the variation in inter-arrival times for UDP packets.
 Goodput: Measure the amount of useful data received, excluding retransmissions and
control messages.

Visualizing Data

 Use Gnuplot, Excel, or Python libraries to plot the extracted metrics for better
visualization and comparison.

Example Analysis Script (Using AWK for Throughput Calculation):


awk '
BEGIN {
FS=" ";
start_time = 0;
total_bytes = 0;
}
$1 == "+" && $4 == "2" && $5 == "3" {
if (start_time == 0) {
start_time = $2;
}
total_bytes += $11;
}
END {
duration = $2 - start_time;
throughput = (total_bytes * 8) / (duration * 1000000);
print "Throughput: " throughput " Mbps";
}
' out.tr

This AWK script calculates the throughput for packets sent from node 2 to node 3.

By following these steps, you can effectively study and compare the performance of TCP and
UDP protocols using NS2.

4.5. Simulation of Distance Vector/ Link State Routing algorithm:

4.5.1. Distance Vector Routing Algorithm

Overview:

Distance Vector Routing is a decentralized routing protocol where each router maintains a routing
table that stores the distance (cost) to reach each destination network and the direction (next hop)
to reach that destination. The routers periodically exchange this information with their directly
connected neighbors.

Distance Vector Routing (DVR) Protocol:

Distance Vector Routing (DVR) Protocol is a method used by routers to find the best path for data
to travel across a network. Each router keeps a table that shows the shortest distance to every other
router, based on the number of hops (or steps) needed to reach them. Routers share this information
with their neighbors, allowing them to update their tables and find the most efficient routes. This
protocol helps ensure that data moves quickly and smoothly through the network.

Distance Vector Routing Algorithm:

The protocol requires that a router inform its neighbors of topology changes periodically.
Bellman-Ford Basics:
Each router maintains a Distance Vector table containing the distance between itself and All
possible destination nodes. Distances, based on a chosen metric, are computed using information
from the neighbors’ distance vectors.
Information kept by DV router:
 Each router has an ID
 Associated with each link connected to a router,
there is a link cost (static or dynamic).
 Intermediate hops

Distance Vector Table Initialization:


 Distance to itself = 0
 Distance to ALL other routers = infinity number.

Distance Vector Algorithm:


 A router transmits its distance vector to each of its neighbors in a routing packet.
 Each router receives and saves the most recently received distance vector from each of its
neighbors.
 A router recalculates its distance vector when:
o It receives a distance vector from a neighbor containing different information than
before.
o 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 ]

Note:
 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 B-F equation:
 Dx(y) = min { C(x,v) + Dv(y), Dx(y) } for each node y ? N

Example :
 Consider 3-routers X, Y and Z as shown in figure. Each router have their routing table.
Every routing table will contain distance to the destination nodes.
Consider router X , X will share it routing table to neighbors and neighbors will share it
routing table to it to X and distance from node X to destination will be calculated using
bellmen- ford equation.
 Dx(y) = min { C(x,v) + Dv(y)} for each node y ? N
As we can see that distance will be less going from X to Z when Y is intermediate node(hop) so
it will be update in routing table X.

 Similarly for Z also –


 Finally the routing table for all –

Key Characteristics:

1. Bellman-Ford Algorithm: The algorithm used for calculating the shortest path.
2. Periodic Updates: Routers send their entire routing table to their neighbors at regular
intervals.
3. Table Maintenance: Each router maintains a table (vector) containing the distance to
each destination and the next hop.
4. Simple Implementation: It's straightforward to implement but has limitations in larger
or more dynamic networks.

Operation:

1. Initialization: Each router starts with a table listing the cost to reach directly connected
networks and sets the cost to reach itself as zero.
2. Exchange: Routers exchange routing tables with their neighbors periodically.
3. Update: Upon receiving the routing information, a router updates its own table if a
shorter path is found.
4. Convergence: This process continues until no more updates are made, and the network is
considered to have converged.

Issues:

1. Count to Infinity Problem: This occurs when there is a loop in the network, leading to
infinite loops in route calculations.
2. Slow Convergence: It can take a long time for the network to converge after a change.

Applications of Distance Vector Routing Algorithm:

The Distance Vector Routing Algorithm has several uses:


 Computer Networking: It helps route data packets in networks.
 Telephone Systems: It’s used in some telephone switching systems.
 Military Applications: It has been used to route missiles.

Advantages of Distance Vector routing:

 Shortest Path: Distance Vector Routing finds the shortest path for data to travel in a
network.
 Usage: It is used in local, metropolitan, and wide-area networks.
 Easy Implementation: The method is simple to set up and doesn’t require many
resources.
 Quick Convergence: It quickly adjusts to changes in the network, finding the best route
to a destination fast.

Disadvantages of Distance Vector Routing Algorithm:


 It is slower to converge than link state.
 It is at risk from the count-to-infinity problem.
 It creates more traffic than link state since a hop count change must be propagated to all
routers and processed on each router. Hop count updates take place on a periodic basis,
even if there are no changes in the network topology, so bandwidth-wasting broadcasts
still occur.
 For larger networks, distance vector routing results in larger routing tables than link state
since each router must know about all other routers. This can also lead to congestion
on WAN links.
Thus, Distance Vector Routing (DVR) Protocol is a simple and efficient method for finding
the shortest path for data in various types of networks. Its ease of implementation and quick
adjustment to network changes make it a valuable tool for ensuring data travels quickly and
efficiently. DVR Protocol helps maintain smooth network operations by constantly updating
and optimizing routes.

4.5.2. Link State Routing Algorithm:

Link state routing is a technique in which each router shares the knowledge of its neighborhood
with every other router in the inter network.

Link State Routing is a more complex and efficient routing protocol where each router has a
complete map of the network topology. Routers maintain a database describing the entire
network's structure and use this information to compute the shortest path to each destination.

The three keys to understand the Link State Routing algorithm:

o Knowledge about the neighborhood: Instead of sending its routing table, a router sends
the information about its neighborhood only. A router broadcast its identities and cost of
the directly attached links to other routers.
o Flooding: Each router sends the information to every other router on the internetwork
except its neighbors. This process is known as Flooding. Every router that receives the
packet sends the copies to all its neighbors. Finally, each and every router receives a copy
of the same information.
o Information sharing: A router sends the information to every other router only when the
change occurs in the information.

Link State Routing has two phases:

Reliable Flooding:

o Initial state: Each node knows the cost of its neighbors.


o Final state: Each node knows the entire graph.

Route Calculation:
Each node uses Dijkstra's algorithm on the graph to calculate the optimal routes to all nodes.

o The Link state routing algorithm is also known as Dijkstra's algorithm which is used to find
the shortest path from one node to every other node in the network.
o The Dijkstra's algorithm is an iterative, and it has the property that after kth iteration of the
algorithm, the least cost paths are well known for k destination nodes.

Let's describe some notations:


o c( i , j): Link cost from node i to node j. If i and j nodes are not directly linked, then c(i , j)
= ∞.
o D(v): It defines the cost of the path from source code to destination v that has the least cost
currently.
o P(v): It defines the previous node (neighbor of v) along with current least cost path from
source to v.
o N: It is the total number of nodes available in the network.

Algorithm:
Initialization
N = {A} // A is a root node.
for all nodes v
if v adjacent to A
then D(v) = c(A,v)
else D(v) = infinity
loop
find w not in N such that D(w) is a minimum.
Add w to N
Update D(v) for all v adjacent to w and not in N:
D(v) = min(D(v) , D(w) + c(w,v))
Until all nodes in N

In the above algorithm, an initialization step is followed by the loop. The number of times the
loop is executed is equal to the total number of nodes available in the network.

Let's understand through an example:


In the above figure, source vertex is A.

Step 1:

The first step is an initialization step. The currently known least cost path from A to its directly
attached neighbors, B, C, D are 2,5,1 respectively. The cost from A to B is set to 2, from A to D is
set to 1 and from A to C is set to 5. The cost from A to E and F are set to infinity as they are not
directly linked to A.

Step 2:

In the above table, we observe that vertex D contains the least cost path in step 1. Therefore, it is
added in N. Now, we need to determine a least-cost path through D vertex.

a) Calculating shortest path from A to B

v = B, w = D

D(B) = min( D(B) , D(D) + c(D,B) )

= min( 2, 1+2)>
= min( 2, 3)

The minimum value is 2. Therefore, the currently shortest path from A to B is 2.

b) Calculating shortest path from A to C

v = C, w = D
D(B) = min( D(C) , D(D) + c(D,C) )
= min( 5, 1+3)
= min( 5, 4)
The minimum value is 4. Therefore, the currently shortest path from A to C is 4.</p>

c) Calculating shortest path from A to E

v = E, w = D
D(B) = min( D(E) , D(D) + c(D,E) )
= min( ∞, 1+1)
= min(∞, 2)
The minimum value is 2. Therefore, the currently shortest path from A to E is 2.

The vertex D has no direct link to vertex E. Therefore, the value of D(F) is infinity.

Step 3:

In the above table, we observe that both E and B have the least cost path in step 2. Let's consider
the E vertex. Now, we determine the least cost path of remaining vertices through E.

a) Calculating the shortest path from A to B.

v = B, w = E
D(B) = min( D(B) , D(E) + c(E,B) )
= min( 2 , 2+ ∞ )
= min( 2, ∞)
The minimum value is 2. Therefore, the currently shortest path from A to B is 2.

b) Calculating the shortest path from A to C:

v = C, w = E
D(B) = min( D(C) , D(E) + c(E,C) )
= min( 4 , 2+1 )
= min( 4,3)
The minimum value is 3. Therefore, the currently shortest path from A to C is 3.

c) Calculating the shortest path from A to F:

v = F, w = E
D(B) = min( D(F) , D(E) + c(E,F) )
= min( ∞ , 2+2 )
= min(∞ ,4)
The minimum value is 4. Therefore, the currently shortest path from A to F is 4.

Step 4:

In the above table, we observe that B vertex has the least cost path in step 3. Therefore, it is added
in N. Now, we determine the least cost path of remaining vertices through B.

a) Calculating the shortest path from A to C.

v = C, w = B
D(B) = min( D(C) , D(B) + c(B,C) )
= min( 3 , 2+3 )
= min( 3,5)
The minimum value is 3. Therefore, the currently shortest path from A to C is 3.
b) Calculating the shortest path from A to F:

v = F, w = B
D(B) = min( D(F) , D(B) + c(B,F) )
= min( 4, ∞)
= min(4, ∞)
The minimum value is 4. Therefore, the currently shortest path from A to F is 4.

Step 5:

In the above table, we observe that C vertex has the least cost path in step 4. Therefore, it is added
in N. Now, we determine the least cost path of remaining vertices through C.

a) Calculating the shortest path from A to F.

v = F, w = C
D(B) = min( D(F) , D(C) + c(C,F) )
= min( 4, 3+5)
= min(4,8)
The minimum value is 4. Therefore, the currently shortest path from A to F is 4.
Final table:

Disadvantage:

Heavy traffic is created in Line state routing due to Flooding. Flooding can cause an infinite
looping, this problem can be solved by using Time-to-leave field

Key Characteristics:

1. Dijkstra’s Algorithm: The algorithm used for calculating the shortest path.
2. Link State Advertisements (LSAs): Routers send LSAs to all other routers in the
network, containing information about directly connected links and their state.
3. Topology Database: Each router builds and maintains a database of the entire network
topology.
4. Complexity and Efficiency: More complex to implement but offers better scalability
and faster convergence.
Operation:

1. Link State Information: Each router discovers its neighbors and measures the cost to
each link.
2. Flooding LSAs: Routers create LSAs and flood them to all other routers in the network.
3. Database Synchronization: All routers collect LSAs to build an identical topology
database.
4. SPF Calculation: Each router independently runs the Dijkstra algorithm on the topology
database to compute the shortest path tree.
5. Routing Table Update: The shortest path tree is used to update the routing table.

TCL script to simulate link state routing in NS2 :

To implement TCL script to simulate link state routing in ns2, we will go through the various
steps in simulating LS (Link State) routing, each with several lines of code as follows.

Step-1: Initializing the network :

The first step is to initialize the network simulator, and we do so by creating a network simulator
object. After that, we initialize rtproto (routing protocol) to Link State (LS).

set ns [new Simulator]

$ns rtproto LS

Step-2: Creating number of nodes :

We next create a random number of nodes, let’s say 7. We use the node instance to create these
nodes as follows.

set node1 [$ns node]

set node2 [$ns node]

set node3 [$ns node]

set node4 [$ns node]

set node5 [$ns node]

set node6 [$ns node]

set node7 [$ns node]

Step-3: Creating the trace file :


Our next step is to create the trace file and nam file. The nam file is used to view simulator
output whereas the trace file traces all the routing information in the process. For this we create
trace file and nam file objects and then open the files in write mode. The trace-all instance is
used to trace all routing information into the trace file and similarly namtrace-all for the nam file.

set tf [open out.tr w]

$ns trace-all $tf

set nf [open out.nam w]

$ns namtrace-all $nf

Step-4: Labeling the nodes :

In the next step we can label the nodes if we wish to. Here we are labeling them from node 0 to
node 6. We can also customize the labels by assigning different colors to them and thus viewing
the simulation much more clearly. Here we will use red and blue.

$node1 label "node 1"

$node1 label "node 2"

$node1 label "node 3"

$node1 label "node 4"

$node1 label "node 5"

$node1 label "node 6"

$node1 label "node 7"

$node1 label-color blue

$node2 label-color red

$node3 label-color red

$node4 label-color blue

$node5 label-color blue

$node6 label-color blue

$node7 label-color blue


Step-5: Creating duplex links :

The next step is to create duplex links between the nodes forming a ring in the end. This can be
achieved by using the duplex-link instance along with specifying three parameters: data rate
(1.5Mb), delay (10ms) and kind of queue (DropTail).

$ns duplex-link $node1 $node2 1.5Mb 10ms DropTail

$ns duplex-link $node2 $node3 1.5Mb 10ms DropTail

$ns duplex-link $node3 $node4 1.5Mb 10ms DropTail

$ns duplex-link $node4 $node5 1.5Mb 10ms DropTail

$ns duplex-link $node5 $node6 1.5Mb 10ms DropTail

$ns duplex-link $node6 $node7 1.5Mb 10ms DropTail

$ns duplex-link $node7 $node1 1.5Mb 10ms DropTail

Step-6: Orient the links between the nodes :

Now we need to orient the links between the nodes appropriately to obtain proper alignment. The
duplex-link-op instance is used for the same.

$ns duplex-link-op $node1 $node2 orient left-down

$ns duplex-link-op $node2 $node3 orient left-down

$ns duplex-link-op $node3 $node4 orient right-down

$ns duplex-link-op $node4 $node5 orient right

$ns duplex-link-op $node5 $node6 orient right-up

$ns duplex-link-op $node6 $node7 orient left-up

$ns duplex-link-op $node7 $node1 orient left-up

Step-7: Attaching TCP agents :

The next step is to attach TCP agents (using attach-agent) at two nodes let’s say node 1 and node
4. We can do this creating the source and sink objects and connecting them using connect
instance.

set tcp2 [new Agent/TCP]


$ns attach-agent $node1 $tcp2

set sink2 [new Agent/TCPSink]

$ns attach-agent $node4 $sink2

$ns connect $tcp2 $sink2

Step-8: Creating FTP traffic :

Our next step is to create FTP traffic and attach to TCP source. The traffic then flows across
node 1 and node 4. We can do this by creating an FTP agent and attaching it to tcp2.

set traffic_ftp2 [new Application/FTP]

$traffic_ftp2 attach-agent $tcp2

Step-9: Adding a finish procedure :

The next step is to add a finish procedure to flush all data into trace file and then and then run the
nam file.

proc finish{} {

global ns nf

$ns flush-trace

close $nf

exec nam out.nam &

exit 0

Step-10: Scheduling the FTP :

The final step is to schedule the FTP traffic at the required time intervals. We can also disable
the link between any pair of nodes at a certain timestamp using rtmodel-at instance and then
enable it after a certain time. This is majorly done for testing purposes. Here we have disabled
the link between nodes 2 and 3. The program ends with the run command.
$ns at 0.5 "traffic_ftp2 start"

$ns rtmodel-at 1.0 down $node2 $node3

$ns rtmodel-at 2.0 up $node2 $node3

$ns at 3.0 "traffic_ftp2 start"

$ns at 4.0 "traffic_ftp2 stop"

$ns at 5.0 "finish"

$ns run

Output :

The final output can be visualized as follows.

As shown in the figure above there is a normal flow of packets from node 1 to node 4. We now
disable the link between nodes 2 and 3 at time 1 and the simulations changes as shown below. The
disabled link is shown in red and the packet flow this time changes direction rather than the original
route to node 4.

Advantages:

1. Fast Convergence: Rapidly converges to a new routing structure after a topology


change.
2. Loop-Free Paths: Ensures loop-free routing at all times.
Issues:

1. Resource Intensive: Requires more memory and processing power compared to


Distance Vector routing.
2. Complexity: More complex to configure and maintain.

4.4.5. Comparison of Distance Vector/ Link State Routing algorithm:

Feature Distance Vector Link State


Algorithm Bellman-Ford Dijkstra
Information Exchanged Distance vectors with neighbors LSAs with all routers
Convergence Speed Slow Fast
Loop Prevention Susceptible to loops Loop-free
Resource Requirements Low High
Network Knowledge Local Global
Complexity Simple Complex

These algorithms are fundamental to understanding how routers communicate and determine the
best paths for data to travel across networks.

4.5. Performance evaluation of Routing protocols using Simulation tool:

Evaluating the performance of routing protocols using simulation tools is essential for
understanding their behavior under various network conditions. Here’s a structured approach to
performance evaluation for ARP/RARP, TCP/UDP, and Distance Vector/Link State Routing
algorithms using a simulation tool:

Steps for Performance Evaluation:

1. Select a Simulation Tool:


o Choose a robust network simulation tool such as NS-3, OMNeT++, GNS3, or
OPNET.
2. Define Evaluation Metrics:
o ARP/RARP Protocols:
 Resolution Time: Time taken to resolve an IP address to a MAC address.
 Overhead: Amount of additional traffic generated by ARP/RARP requests.
 Accuracy: Rate of successful resolutions versus failed attempts.
o TCP/UDP:
 Throughput: Amount of data successfully delivered over a network per
unit time.
 Latency: Time taken for data to travel from source to destination.
 Packet Loss: Number of packets lost during transmission.
 Congestion Control Performance: Effectiveness of TCP’s congestion
control mechanisms.
o Distance Vector/Link State Routing:
 Convergence Time: Time taken for the network to reach a stable state after
a change.
 Routing Overhead: Amount of control traffic generated by the routing
protocol.
 Path Optimality: Efficiency of the selected routes in terms of hop count or
other metrics.
 Scalability: Performance as network size increases.
3. Design Network Scenarios:
o Topology: Create different network topologies (e.g., mesh, star, ring).
o Traffic Patterns: Simulate different types of traffic (e.g., constant bit rate,
variable bit rate).
o Failure Scenarios: Introduce link/node failures to evaluate protocol robustness.
4. Simulation Setup:
o Configure the simulation environment with the chosen network topology and
traffic patterns.
o Implement ARP/RARP, TCP/UDP, and Distance Vector/Link State protocols in
the simulation tool.
o Set parameters such as link bandwidth, delay, error rates, and node capacities.
5. Run Simulations:
o Perform multiple simulation runs to account for variability and obtain statistically
significant results.
o Use different scenarios to test under various network conditions and load levels.
6. Collect Data:
o Gather performance metrics from the simulation logs.
o Ensure that the data collected is relevant to the defined evaluation metrics.
7. Analyze Results:
o Compare the performance of ARP and RARP in terms of resolution time and
overhead.
o Evaluate TCP versus UDP performance in terms of throughput, latency, and
packet loss.
o Analyze the convergence time, routing overhead, and path optimality of Distance
Vector versus Link State routing protocols.
8. Visualize Data:
o Use graphs and charts to present the performance metrics clearly.
o Highlight key findings and patterns observed from the simulation results.
Figure. 4.6. Simulation Flow Diagram

Example Simulation Tools:

1. NS-3:
o A discrete-event network simulator for internet systems.
o Provides support for various routing protocols, ARP, TCP, and UDP.
2. OMNeT++:
o A modular, component-based C++ simulation library and framework.
o Suitable for simulating communication networks and other distributed systems.
3. GNS3:
o A network software emulator that allows the combination of virtual and real
devices.
o Useful for simulating complex network topologies and protocols.
4. OPNET (now part of Riverbed Modeler):
o A comprehensive network simulation and modeling tool.
o Supports detailed analysis of routing protocols, TCP/UDP, and ARP/RARP
performance.

Example Scenario for Distance Vector vs. Link State:


1. Network Topology:
o Simulate a network with 10-50 nodes.
o Create different topologies (e.g., random, mesh, hierarchical).
2. Traffic Patterns:
o Generate traffic between random pairs of nodes.
o Include both constant and variable bit rate traffic.
3. Failure Scenarios:
o Introduce random link failures.
o Observe how quickly and efficiently each protocol converges to a new stable
state.
4. Metrics Collection:
o Measure convergence time after topology changes.
o Collect data on routing overhead and control message frequency.
o Evaluate the optimality of the routing paths chosen.

By following these steps and using appropriate simulation tools, you can effectively evaluate the
performance of various routing protocols and understand their strengths and limitations under
different network conditions.

You might also like