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

0% found this document useful (0 votes)
26 views45 pages

All Exp CN

The document outlines various experiments related to socket programming using TCP and UDP, including simulations of DNS, time servers, echo servers, and RPC/RMI in NS2. It details the implementation of raw sockets for low-level network packet manipulation, as well as simulating Ping and Traceroute commands. Additionally, it discusses the creation of HTTP-like behavior for webpage upload and download using TCP agents in a simulated environment.
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)
26 views45 pages

All Exp CN

The document outlines various experiments related to socket programming using TCP and UDP, including simulations of DNS, time servers, echo servers, and RPC/RMI in NS2. It details the implementation of raw sockets for low-level network packet manipulation, as well as simulating Ping and Traceroute commands. Additionally, it discusses the creation of HTTP-like behavior for webpage upload and download using TCP agents in a simulated environment.
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/ 45

OUTPUT:

EXPERIMENT-5
Aim:
Socket programming using UDP and TCP (e.g., simple DNS, data & time client/server, echo
client/server, iterative & concurrent servers.
Description:
Socket programming allows communication between two different processes over a network.
In the context of TCP (Transmission Control Protocol) and UDP (User Datagram Protocol),
sockets enable the creation of client-server models where a client sends a request and a server
provides a response.
TCP sockets are connection-oriented, ensuring reliable and ordered delivery of messages.
They are best suited for applications where data integrity and reliability are critical, such as
web browsing, email, and file transfers.
UDP sockets are connectionless, meaning they send data without establishing a prior
connection. While faster than TCP, they do not guarantee delivery, making them suitable for
real-time applications like video streaming or online gaming.
This experiment involves implementing simple socket-based programs such as:
• A DNS-like server that returns IP addresses for given domain names.
• A Date and Time Server that returns the current server time to connected clients.
• An Echo Server, which sends back the same message it receives from the client.
• Iterative servers, which handle one client at a time.
• Concurrent servers, which handle multiple clients simultaneously using
multithreading or multiprocessing.
These examples help understand how sockets work under both TCP and UDP protocols and
how to manage client-server communications in different scenarios.
1. Simple DNS Simulation Using UDP in NS2:
NS2 does not have a DNS-specific application out of the box, but we can simulate a basic
UDP-based request-response communication which is similar to DNS behavior.
# Simple DNS simulation in NS2 (UDP)
# Create a new simulator instance
set ns [new Simulator]
# Create the nodes (DNS server and client)
set dnsServer [ $ns node ]
set dnsClient [ $ns node ]
# Create UDP agents for both client and server
set udpClient [new Agent/UDP]
set udpserver [new Agent/UDP]
# Attach the agents to the nodes
$ns attach-agent $dnsClient $udpClient
$ns attach-agent $dnsServer $udpServer
# Set up a duplex link between client and server (10Mb, 100ms delay)
$ns duplex-link $dnsClient $dnsServer 10Mb 100ms DropTail
# Create a Traffic Application for the DNS client (UDP-based)
set dnsApp [new Application/Traffic/ConstantTraffic]
$dnsApp attach-agent $udpClient
$dnsApp set packetSize_ 128
$dnsApp set interval_ 0.5
# Simulate DNS query at time 0.1 seconds
$ns at 0.1 "$dnsApp start"
# End the simulation at 10.0 seconds
$ns at 10.0 "puts \"DNS Simulation Complete\""
$ns run
2. Time Client/Server Simulation Using TCP/UDP in NS2:
# Create a new simulator instance
set ns [new Simulator]
# Create the nodes (server and client)
set timeServer [ $ns node ]
set timeClient [ $ns node ]
# Create TCP agents for client and server
set tcpClient [new Agent/TCP]
set tcpServer [new Agent/TCPSink]
# Attach the agents to the nodes
$ns attach-agent $timeClient $tcpClient
$ns attach-agent $timeServer $tcpServer
# Set up the duplex link between client and server (10Mb, 100ms delay)
$ns duplex-link $timeClient $timeServer 10Mb 100ms DropTail
# Create a Time application (simulate time request)
set timeApp [new Application/Traffic/ConstantTraffic]
$timeApp attach-agent $tcpClient
$timeApp set packetSize_ 128
$timeApp set interval_ 1.0
# Start the time application at 0.1 seconds
$ns at 0.1 "$timeApp start"
# End the simulation at 10.0 seconds
$ns at 10.0 "puts \"Time Simulation Complete\""
$ns run
3. Echo Client/Server Using TCP in NS2:
# Create a new simulator instance
set ns [new Simulator]
# Create the nodes (server and client)
set echoServer [ $ns node ]
set echoClient [ $ns node ]
# Create TCP agents for client and server
set tcpClient [new Agent/TCP]
set tcpServer [new Agent/TCPSink]
# Attach the agents to the nodes
$ns attach-agent $echoClient $tcpClient
$ns attach-agent $echoServer $tcpServer
# Set up the duplex link between client and server (10Mb, 100ms delay)
$ns duplex-link $echoClient $echoServer 10Mb 100ms DropTail
# Create Echo traffic application for the client
set echoApp [new Application/Traffic/ConstantTraffic]
$echoApp attach-agent $tcpClient
$echoApp set packetSize_ 128
$echoApp set interval_ 1.0
# Start the echo application at 0.1 seconds
$ns at 0.1 "$echoApp start"
# End the simulation at 10.0 seconds
$ns at 10.0 "puts \"Echo Simulation Complete\""
$ns run
4. Iterative and Concurrent Servers Simulation in NS2:
# Create a new simulator instance
set ns [new Simulator]
# Create server node and client nodes
set server [ $ns node ]
set client1 [ $ns node ]
set client2 [ $ns node ]
# Create TCP agents for client and server
set tcpServer [new Agent/TCPSink]
set tcpClient1 [new Agent/TCP]
set tcpClient2 [new Agent/TCP]
# Attach agents to the nodes
$ns attach-agent $server $tcpServer
$ns attach-agent $client1 $tcpClient1
$ns attach-agent $client2 $tcpClient2
# Set up duplex links between server and clients
$ns duplex-link $client1 $server 10Mb 100ms DropTail
$ns duplex-link $client2 $server 10Mb 100ms DropTail
# Traffic generation for each client
set traffic1 [new Application/Traffic/ConstantTraffic]
$traffic1 attach-agent $tcpClient1
$traffic1 set packetSize_ 128
$traffic1 set interval_ 1.0
set traffic2 [new Application/Traffic/ConstantTraffic]
$traffic2 attach-agent $tcpClient2
$traffic2 set packetSize_ 128
$traffic2 set interval_ 1.0
# Start traffic at 0.1 seconds
$ns at 0.1 "$traffic1 start"
$ns at 0.1 "$traffic2 start"
# End the simulation at 10.0 seconds
$ns at 10.0 "puts \"Iterative Simulation Complete\""
$ns run

Conclusion:
While NS2 is primarily a network simulator and not a socket programming environment, you
can simulate various network behaviors such as DNS, echo services, and client-server
communication by modeling traffic and agents between nodes.
• UDP and TCP traffic generation can be used in NS2 to simulate applications like
DNS, echo clients, and file transfer, and you can adjust the simulation to represent
sequential or concurrent behaviors by managing how many clients interact with the
server.
EXPERIMENT-6
Aim:
Programming using raw sockets.
Description:
Raw sockets provide a low-level interface for sending and receiving network packets,
allowing direct access to the underlying transport layer. Unlike standard sockets, which
abstract the details of the transport protocol (TCP/UDP), raw sockets allow the programmer
to manually construct IP headers and manage packet-level data transmission.
Using raw sockets, users can create custom network tools such as packet sniffers, protocol
testers, or tools for network diagnostics and security auditing. Raw sockets are especially
useful in scenarios where full control over packet structure and behavior is needed — such as
simulating custom protocols or implementing proprietary communication standards.
This experiment typically demonstrates:
• Creation of raw sockets in TCP and UDP modes.
• Manually forming and analyzing IP packets.
• Sending and receiving raw packets directly over the network interface.
• Observing differences in behavior between TCP and UDP transmissions.
Note: Since raw sockets operate at a privileged level, administrative/root access is often
required to execute these programs on most systems.

Algorithm/Syntax:
set ns [new Simulator] set nf [open
lab2.nam w] $ns namtrace-all $nf
settf [open lab2.tr w] $ns trace-all
$tf
proc finish { } { global ns nftf $ns
flush-trace close $nf
close $tf
execnam lab2.nam & exit 0
}
set n0 [$ns node] set n1 [$ns node]
set n2 [$ns node] set n3 [$ns node]
$ns duplex-link $n0 $n2
10Mb 1ms DropTail $ns
duplex-link $n1 $n2
10Mb 1ms DropTail $ns
duplex-link $n2 $n3
10Mb 1ms DropTail
set tcp0 [new Agent/TCP]
# letters A,T,C,P are capital

$ns attach-agent $n0 $tcp0


set udp1 [new Agent/UDP]
$ns attach-agent $n1 $udp1
set null0 [new Agent/Null]
$ns attach-agent $n3 $null0
set sink0 [new Agent/TCPSink]
# letters A,U,D,P are capital
# letters A and N are capital
# letters A,T,C,P,S are capital
$ns attach-agent $n3 $sink0
set ftp0 [new Application/FTP]
$ftp0 attach-agent $tcp0
set cbr1 [new Application/Traffic/CBR]
$cbr1 attach-agent $udp1
$ns connect $tcp0 $sink0
$ns connect $udp1 $null0
$ns at 0.1 "$cbr1 start"
$ns at 0.2 "$ftp0 start"
$ns at 0.5 "finish"
$ns run
AWK file:(Open a new editor using “vi command” and write awk file and save with “.awk”
extension)
BEGIN{
udp=0;
tcp=0;}
{if($1= = “r” && $5 = = “cbr”)
{udp++;}
else if($1 = = “r” && $5 = = “tcp”)
{
tcp++;}}
END{ printf(“Number of packets sent by TCP = %d\n”, tcp); printf(“Number of
packets sent by UDP=%d\n”,udp);
}
EXPERIMENT-7
Aim:
To implement the program using RPC/RMI
Theory:
Remote Procedure Call (RPC):
RPC is a protocol that allows a program to call a procedure or function on another machine
(remote system) over a network. The caller program is unaware of the network layer, making
it seem as if the procedure is being executed locally.
Remote Method Invocation (RMI):
RMI is a Java-specific mechanism that allows invoking methods on objects located in different
address spaces, potentially on remote machines.
In NS2, while there’s no native support for RPC/RMI as used in application-level programming
(like in Java or Python), you can simulate the communication behavior where nodes (simulated
as clients and servers) send messages to invoke remote actions (like requesting a service,
response, or data) over the network.
Approach to Simulate RPC/RMI in NS2:
Although NS2 does not provide a direct mechanism for implementing RPC or RMI as in
programming languages, you can simulate the RPC/RMI behavior using message passing,
where one node sends a request (like an RPC or RMI call), and the other node responds back
(like an RPC/RMI response).
We can simulate RPC-like behavior by creating a client-server communication using
TCP/UDP agents where the client sends a request to the server, and the server responds with
the result.
Simulating RPC-like Communication in NS2
# Simulate RPC-like behavior in NS2 using TCP
# Create a new simulator instance
set ns [new Simulator]
# Create nodes (RPC client and RPC server)
set rpcClient [ $ns node ]
set rpcServer [ $ns node ]
# Create TCP agents (Client and Server)
set tcpClient [new Agent/TCP]
set tcpServer [new Agent/TCPSink]
# Attach the TCP agents to the nodes
$ns attach-agent $rpcClient $tcpClient
$ns attach-agent $rpcServer $tcpServer
# Set up duplex link between client and server (10Mbps, 100ms delay)
$ns duplex-link $rpcClient $rpcServer 10Mb 100ms DropTail
# Create a Traffic Application to simulate RPC request/response
set trafficApp [new Application/Traffic/ConstantTraffic]
$trafficApp attach-agent $tcpClient
$trafficApp set packetSize_ 128
$trafficApp set interval_ 1.0
# Start the client request at 0.1 seconds
$ns at 0.1 "$trafficApp start"
# End the simulation at 5.0 seconds
$ns at 5.0 "puts \"RPC Simulation Complete\""
$ns run

Conclusion:
• In NS2, we simulate the behavior of RPC/RMI by creating a client-server model with
message passing using TCP/UDP agents.
• The client sends a request (similar to an RPC call), and the server responds (similar to
an RPC response).
EXPERIMENT-8
Aim:
Write a code simulating Ping and Trace-route commands
Theory:
• Ping is used to check the reachability of a host and measure round-trip time (RTT) using
ICMP Echo Request/Reply packets.
• Traceroute is used to determine the path packets take to reach a destination, identifying
each hop on the route by incrementing the TTL (Time To Live) field.
While NS2 doesn’t support actual ICMP, we simulate ping using UDP echo packets, and
traceroute by manually manipulating TTL values and capturing intermediate hops.
NS2 Code: Simulating Ping and Traceroute
# Create simulator
set ns [new Simulator]
# Open trace file
set tracefile [open out.tr w]
$ns trace-all $tracefile
# Define finish procedure
proc finish {} {
global ns tracefile
$ns flush-trace
close $tracefile
puts "Simulation completed."
exit 0
}
# Create nodes
set n0 [$ns node] ;# Source (Client)
set n1 [$ns node] ;# Hop 1 (Router 1)
set n2 [$ns node] ;# Hop 2 (Router 2)
set n3 [$ns node] ;# Destination (Server)

# Create links
$ns duplex-link $n0 $n1 1Mb 10ms DropTail
$ns duplex-link $n1 $n2 1Mb 10ms DropTail
$ns duplex-link $n2 $n3 1Mb 10ms DropTail
# Setup UDP agents to simulate ping (echo request/response)
set udp0 [new Agent/UDP]
set null0 [new Agent/Null]
$ns attach-agent $n0 $udp0
$ns attach-agent $n3 $null0
$ns connect $udp0 $null0
# Setup application to simulate ping
set pingApp [new Application/Traffic/CBR]
$pingApp attach-agent $udp0
$pingApp set packetSize_ 64
$pingApp set interval_ 1.0
$pingApp set random_ false
# Schedule ping simulation
$ns at 0.5 "$pingApp start"
$ns at 3.0 "$pingApp stop"
# Simulate traceroute using TTL concept (manual version)
# Here, we would simulate sending packets with increasing TTL values and log which node
drops them.
# For simplicity, simulate reaching each hop and logging time
$ns at 0.6 "puts \"Traceroute: Reached n1 (Router 1) at TTL=1\""
$ns at 0.8 "puts \"Traceroute: Reached n2 (Router 2) at TTL=2\""
$ns at 1.0 "puts \"Traceroute: Reached n3 (Destination) at TTL=3\""
# Finish simulation
$ns at 4.0 "finish"
# Run simulation
$ns run
Conclusion:
In NS2, Ping and Traceroute can be simulated using:
• UDP traffic and echo agents to replicate Ping.
• Manual TTL tracking or time-based messages to replicate Traceroute.
This provides a conceptual and practical understanding of these tools within a simulated
environment.
EXPERIMENT-9
Aim:
Create a Socket for HTTP for webpage upload and download.
Theory:
HTTP (HyperText Transfer Protocol) works over TCP sockets for reliable communication
between clients (web browsers) and servers (web hosts).
• Webpage Download: The client requests a webpage, and the server responds with the
HTML data.
• Webpage Upload: The client sends data (e.g., form submission or file) to the server.
In NS2, while there's no high-level HTTP protocol model, we simulate HTTP behavior using
TCP agents and FTP/Exponential applications to mimic request-response interactions.
NS2 Code: HTTP Socket Simulation
# Create NS2 simulator
set ns [new Simulator]
# Open trace file
set tracefile [open http_socket.tr w]
$ns trace-all $tracefile
# Finish procedure
proc finish {} {
global ns tracefile
$ns flush-trace
close $tracefile
puts "HTTP socket simulation complete."
exit 0
}
# Create nodes: Client and Server
set client [$ns node]
set server [$ns node]
# Create duplex link between client and server
$ns duplex-link $client $server 1Mb 10ms DropTail
# TCP socket from server to client
set tcpDownload [new Agent/TCP]
set sinkDownload [new Agent/TCPSink]
$ns attach-agent $server $tcpDownload
$ns attach-agent $client $sinkDownload
$ns connect $tcpDownload $sinkDownload
# FTP application to simulate HTTP download
set httpDownload [new Application/FTP]
$httpDownload attach-agent $tcpDownload
# TCP socket from client to server
set tcpUpload [new Agent/TCP]
set sinkUpload [new Agent/TCPSink]
$ns attach-agent $client $tcpUpload
$ns attach-agent $server $sinkUpload
$ns connect $tcpUpload $sinkUpload
# FTP application to simulate HTTP upload
set httpUpload [new Application/FTP]
$httpUpload attach-agent $tcpUpload
# Start download at 0.5s and upload at 2s
$ns at 0.5 "$httpDownload start"
$ns at 2.0 "$httpUpload start"
# End simulation at 4s
$ns at 4.0 "finish"
# Run simulation
$ns run
Conclusion:
In NS2, HTTP socket communication for webpage upload and download can be simulated
using:
• TCP sockets between nodes.
• FTP application to model HTTP-like data flow. This provides a simple and effective
way to simulate web communication at the transport layer.
EXPERIMENT-10
Aim:
To perform case study for different routing algorithms to select the network path using
a) LINK STATE ROUTING b) FLOODING c) DISTANCE VECTOR.
Theory:
a) Link State Routing (LSR):
• Each node constructs a complete topology of the network.
• Nodes use Dijkstra's algorithm to compute the shortest path.
• Routes converge quickly and loop-free.
b) Flooding:
• Every incoming packet is sent out on every outgoing link (except the one it arrived
on).
• Simple but leads to heavy redundancy and congestion.
c) Distance Vector Routing (DVR):
• Each node shares its routing table with its neighbors periodically.
• Uses Bellman-Ford algorithm to compute paths.
• Slower convergence, susceptible to routing loops.

Network Topology:

• For this simulation, consider a simple topology with 5 nodes:


n0 -- n1 -- n2
| | |
n3 -- n4 -- n5

NS2 Simulation Code: Comparing Routing Strategies

# Create a simulator object

set ns [new Simulator]

# Open trace file

set f [open routing_case.tr w]

$ns trace-all $f

# Define finish procedure

proc finish {} {
global ns f

$ns flush-trace

close $f

puts "Routing case study simulation complete."

exit 0

# Create 6 nodes

for {set i 0} {$i < 6} {incr i} {

set n($i) [$ns node]

# Create links (sample mesh-like topology)

$ns duplex-link $n(0) $n(1) 1Mb 10ms DropTail

$ns duplex-link $n(1) $n(2) 1Mb 10ms DropTail

$ns duplex-link $n(0) $n(3) 1Mb 10ms DropTail

$ns duplex-link $n(1) $n(4) 1Mb 10ms DropTail

$ns duplex-link $n(2) $n(5) 1Mb 10ms DropTail

$ns duplex-link $n(3) $n(4) 1Mb 10ms DropTail

$ns duplex-link $n(4) $n(5) 1Mb 10ms DropTail

# Traffic source and destination (Client n0 to Server n5)

set tcp [new Agent/TCP]

set sink [new Agent/TCPSink]

$ns attach-agent $n(0) $tcp

$ns attach-agent $n(5) $sink

$ns connect $tcp $sink


set ftp [new Application/FTP]

$ftp attach-agent $tcp

# Schedule FTP start

$ns at 0.5 "$ftp start"

# Different routing logic simulated via explanation and visualization

puts "Routing Case Study:"

puts "1. Link State: Shortest path (n0 → n1 → n2 → n5) will be used"

puts "2. Flooding: Packets will be broadcasted across all paths"

puts "3. Distance Vector: Routing tables shared; paths may fluctuate initially, then stabilize"

# End simulation

$ns at 3.0 "finish"

$ns run

How Each Routing Strategy is Simulated:

• Link State Routing: Use a topology-aware static path (like n0 → n1 → n2 → n5) to


reflect shortest path usage.
• Flooding: Though not natively implemented in NS2, can be visualized by duplicating
traffic across multiple paths or analyzing trace file for heavy packet duplication.
• Distance Vector Routing: Behavior can be discussed by showing fluctuating paths in
dynamic scenarios, or by scripting routing changes.

Conclusion:

This experiment illustrates how different routing algorithms affect:

• Path selection
• Network efficiency
• Scalability and performance

While NS2 doesn't natively offer GUI-level toggling of routing algorithms like
LSR/DVR/Flooding, simulation and trace analysis enable effective understanding of their
theoretical behavior.
EXPERIMENT-11
Aim:
Implementation of Stop and Wait Protocol and Sliding Window Protocol
Theory:
1. Stop and Wait Protocol:
• Sender sends one frame and waits for an acknowledgment (ACK).
• Ensures reliable delivery but leads to underutilization of bandwidth due to idle
waiting.
2. Sliding Window Protocol:
• Allows sender to send multiple frames before requiring an ACK.
• Improves throughput by keeping the channel busy.
• Controlled by window size.
Implementation in NS2:
NS2 doesn't simulate protocols like Stop-and-Wait and Sliding Window at the data link
layer by default. However, we can mimic their behavior using:
• Stop-and-Wait → CBR with large interval (simulates one packet at a time + ACK
wait).
• Sliding Window → TCP with window size set manually (window size > 1).
Network Topology:
[Sender] ---- [Receiver]

NS2 TCL Script: Stop-and-Wait and Sliding Window Protocols


# Create a simulator instance
set ns [new Simulator]
# Trace file
set tracefile [open sw_vs_swp.tr w]
$ns trace-all $tracefile
# Define finish procedure
proc finish {} {
global ns tracefile
$ns flush-trace
close $tracefile
puts "Simulation completed."
exit 0
}
# Create two nodes
set sender [$ns node]
set receiver [$ns node]
# Create duplex link
$ns duplex-link $sender $receiver 1Mb 10ms DropTail
# ===========================
# Stop and Wait Simulation
# ===========================
# UDP agent for stop-and-wait
set udp_sw [new Agent/UDP]
set null_sw [new Agent/Null]
$ns attach-agent $sender $udp_sw
$ns attach-agent $receiver $null_sw
$ns connect $udp_sw $null_sw
# Application to simulate one packet at a time
set stopwait [new Application/Traffic/CBR]
$stopwait attach-agent $udp_sw
$stopwait set packetSize_ 500
$stopwait set interval_ 1.0 ;# simulate long wait per packet (ACK wait)
# ===========================
# Sliding Window Simulation
# ===========================
# TCP agent for sliding window
set tcp [new Agent/TCP]
$tcp set window_ 5 ;# window size for Sliding Window Protocol
set sink [new Agent/TCPSink]
$ns attach-agent $sender $tcp
$ns attach-agent $receiver $sink
$ns connect $tcp $sink
# FTP application to simulate data stream
set swapp [new Application/FTP]
$swapp attach-agent $tcp
# Schedule events
$ns at 0.5 "$stopwait start"
$ns at 2.0 "$swapp start"
# End simulation
$ns at 5.0 "finish"
# Run
$ns run

Observation:
• Stop-and-Wait shows lower throughput due to idle time after each packet.
• Sliding Window maintains higher channel utilization with multiple in-flight packets.

Conclusion:

Using NS2, we can simulate and analyze the behavioral differences between Stop-and-
Wait and Sliding Window protocols, highlighting their trade-offs in reliability vs
throughput.
EXPERIMENT-12
Aim:
Implement Subnetting to generate Range of IP Addresses.
Implementation:
1. Script Overview:
In this experiment, we will create an NS2 simulation script to simulate a network with multiple
subnets. The script will:
• Define a network topology.
• Assign IP addresses to nodes.
• Subnet the given network.
• Display the range of IP addresses for each subnet.
2. Example Network:
Given a class C network: 192.168.1.0/24, we will create subnets with a subnet mask of /26.
3. NS2 Simulation Script:
Here is an example of an NS2 script for subnetting and assigning IP addresses:
# NS2 Script for Subnetting and IP Range Calculation
# Create a simulator object
set ns [new Simulator]
# Define the topology (simple network with nodes)
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
# Define IP addresses and subnet mask for a network (e.g., 192.168.1.0/24)
set baseIP "192.168.1."
set subnetMask "255.255.255.192" # /26 subnet mask (64 addresses per subnet)
set subnetSize 64 # 64 addresses in each subnet
# Function to calculate the network address, broadcast address, and host range for each subnet
proc calculate_subnet {networkAddr subnetMask subnetSize} {
set network [split $networkAddr "."]
set mask [split $subnetMask "."]
# Convert IP and Mask into binary
set networkBin ""
set maskBin ""
for {set i 0} {$i < 4} {incr i} {
set networkBin "$networkBin [format "%08b" [lindex $network $i]]"
set maskBin "$maskBin [format "%08b" [lindex $mask $i]]"
}
# Subnet address calculation (bitwise AND between network and mask)
set subnetBin [string range $networkBin 0 25] ;# First 26 bits are the network portion
set subnetStart [join [split $subnetBin "" 8] "."]
# Broadcast address (flip the host bits to 1)
set broadcastBin [string range $networkBin 0 25] ;# First 26 bits are same
append broadcastBin "11111111" ;# Last 6 bits for host part turned to 1s
set broadcastStart [join [split $broadcastBin "" 8] "."]
# Host IP range calculation
set rangeStart [expr [join [split $subnetStart "." 4] "." - 1]]
set rangeEnd [expr [join [split $broadcastStart "." 4] "." - 2]]
# Return network and broadcast addresses and range
return "$subnetStart - $broadcastStart"
}
# Subnetting calculation for network 192.168.1.0/24 into /26 subnets
set subnets [list "192.168.1.0" "192.168.1.64" "192.168.1.128" "192.168.1.192"]
foreach subnet $subnets {
puts "Subnet: $subnet"
set range [calculate_subnet $subnet $subnetMask $subnetSize]
puts "Range of IP Addresses: $range"
}
# Create and setup links between nodes in the network topology
$ns duplex-link $n1 $n2 10Mb 100ms DropTail
$ns duplex-link $n3 $n4 10Mb 100ms DropTail
# Set up IP addresses for each node using the subnets
$ns at 0.0 "puts \"Assigning IP addresses to nodes\""
$ns at 0.1 "$n1 set ip [expr 192.168.1.2]"
$ns at 0.2 "$n2 set ip [expr 192.168.1.3]"
# Running the simulation
$ns run

Output:
EXPERIMENT-13
Aim:
To implement socket programming date and time display from client to server using TCP and
UDP sockets
Theory:
1. TCP Socket in NS2:
TCP is a connection-oriented protocol, ensuring reliable communication between the client and
server. In NS2, we simulate the TCP behavior by creating connections between nodes, setting
up proper routing, and managing the flow of data using TCP.
2. UDP Socket in NS2:
UDP is a connectionless protocol that allows for faster communication with lower overhead,
but it does not guarantee reliable delivery or data order. In NS2, UDP sockets are simulated by
using the UDP agent that allows for packet transmission without needing a connection setup.

Steps to Simulate Date and Time Transmission Using TCP and UDP in NS2:
1. Topology Setup:
We will create a basic network with:
A server node that will send the current date and time.
A client node that will send requests to the server and receive the date and time.
We will then simulate both TCP and UDP socket connections between the client and server
nodes.
2. NS2 Script for TCP Simulation:
# TCP Socket Programming to Display Date and Time (Client-Server)
set ns [new Simulator]
# Create nodes (server and client)
set server [ $ns node ]
set client [ $ns node ]
# Create a TCP connection between client and server
set tcp [new Agent/TCP]
$ns attach-agent $client $tcp
set sink [new Agent/TCPSink]
$ns attach-agent $server $sink
# Set up the connection (link between client and server)
$ns duplex-link $client $server 10Mb 100ms DropTail
$ns duplex-link-op $client $server queue-limit 50
# Configure TCP and TCP Sink parameters
$ns at 0.1 "$tcp send" ;# Send data after 0.1 seconds
$ns at 0.2 "$ns flush" ;# Flush at 0.2 seconds
# Create a TCP application (for client to request date and time)
set app [new Application/Traffic/ConstantTraffic]
$app attach-agent $tcp
$app set packetSize_ 128
$app set interval_ 0.5
# Start the simulation and run the scenario
$ns at 1.0 "puts \"Client has received the date and time\""
$ns run
3. NS2 Script for UDP Simulation:
# UDP Socket Programming to Display Date and Time (Client-Server)
set ns [new Simulator]
# Create nodes (server and client)
set server [ $ns node ]
set client [ $ns node ]
# Create a UDP agent for the client
set udp [new Agent/UDP]
$ns attach-agent $client $udp
# Create a null agent for the server (UDP does not have a direct sink like TCP)
set null [new Agent/Null]
$ns attach-agent $server $null
# Set up the link between client and server (UDP communication)
$ns duplex-link $client $server 10Mb 100ms DropTail
$ns duplex-link-op $client $server queue-limit 50
# Set up UDP application for constant packet transmission
set app [new Application/Traffic/ConstantTraffic]
$app attach-agent $udp
$app set packetSize_ 128
$app set interval_ 1.0
# Start the simulation
$ns at 1.0 "puts \"Client has sent the date and time request\""
$ns run
EXPERIMENT-14
Aim:
To implement socket programming date and time display from client to server using TCP and
UDP sockets
Theory:
1. Network Simulator 2 (NS2):
NS2 is a discrete event network simulator that is widely used for simulating TCP/IP networks
and congestion control algorithms. It provides support for simulating various networking
protocols, routing, congestion control, and network topologies.
2. Congestion Control Algorithms:
TCP Tahoe:
TCP Tahoe uses slow start, congestion avoidance, and fast retransmit to control congestion.
The main feature of TCP Tahoe is that it resets its congestion window size to 1 packet when
packet loss is detected.
TCP Reno:
TCP Reno improves upon TCP Tahoe by adding the fast recovery mechanism. When packet
loss is detected, the congestion window is reduced but not reset to 1.
TCP Vegas:
TCP Vegas aims to improve TCP by detecting congestion before packet loss occurs. It uses
round-trip time (RTT) measurements to estimate network congestion and adjusts its congestion
window accordingly.
Steps to Simulate Congestion Control Algorithms in NS2:
1. Simulation Topology:
The network topology consists of:
• Source Node: Generates data packets.
• Destination Node: Receives data packets.
• Router Node(s): Simulate network congestion by routing the packets between the
source and destination.
2. NS2 Script to Simulate TCP Congestion Control Algorithms:
Below is an example script to simulate TCP Reno, TCP Tahoe, and TCP Vegas in NS2.
# Define the simulator
set ns [new Simulator]
# Create nodes
set source [ $ns node ]
set destination [ $ns node ]
set router [ $ns node ]
# Set up links between nodes (source, router, destination)
$ns duplex-link $source $router 10Mb 100ms DropTail
$ns duplex-link $router $destination 10Mb 100ms DropTail
# Create a TCP agent for congestion control
set tcpreno [new Agent/TCP/Reno] ;# TCP Reno
set tcptahoe [new Agent/TCP/Tahoe] ;# TCP Tahoe
set tcpvegas [new Agent/TCP/Vegas] ;# TCP Vegas
# Attach the TCP agents to the source node
$ns attach-agent $source $tcpreno
$ns attach-agent $source $tcptahoe
$ns attach-agent $source $tcpvegas
# Create sink agents to receive data at the destination node
set sink [new Agent/TCPSink]
$ns attach-agent $destination $sink
# Set up the TCP connection between source and destination
$ns connect $tcpreno $sink
$ns connect $tcptahoe $sink
$ns connect $tcpvegas $sink
# Set up traffic (Data transmission from source to destination)
set ftp [new Application/FTP]
$ftp attach-agent $tcpreno ;# Attach FTP to TCP Reno
$ftp attach-agent $tcptahoe ;# Attach FTP to TCP Tahoe
$ftp attach-agent $tcpvegas ;# Attach FTP to TCP Vegas
# Start the FTP application at time 0.1
$ns at 0.1 "$ftp start"
# Set simulation time and run
$ns at 10.0 "finish"
$ns run
# Define finish procedure
proc finish {} {
global ns
$ns flush
exit 0
}
Analysis of Congestion Control Algorithms:
The different TCP congestion control algorithms will behave differently in terms of network
performance, particularly in terms of throughput, packet loss, and congestion window size:
1. TCP Reno:
o TCP Reno follows the standard slow-start, congestion avoidance, and fast-
retransmit procedures. The congestion window increases exponentially during
the slow-start phase and linearly during congestion avoidance.
2. TCP Tahoe:
o TCP Tahoe resets its congestion window to 1 packet when packet loss is
detected. This causes a larger drop in throughput after packet loss compared to
Reno.
3. TCP Vegas:
o TCP Vegas attempts to detect congestion before packet loss occurs by
monitoring round-trip times (RTT). It adjusts its window size dynamically,
resulting in more efficient congestion management.
EXPERIMENT-15
Aim:
Applications using TCP Sockets like a. Echo client and echo server b. Chat c. File Transfer.
Theory:
1. Echo Client and Echo Server:
An Echo client sends a message to the server, and the server responds by sending the exact
same message back to the client. This is a simple demonstration of a TCP connection.
2. Chat Application:
In a chat application, both the client and server exchange text messages over a TCP connection,
simulating real-time chat communication.
3. File Transfer Application:
In a file transfer application, a client sends a file to the server, and the server receives and
processes the file. This simulates the basic functionality of a file transfer protocol (FTP).

Steps to Simulate TCP Socket Applications in NS2:


The following scripts will demonstrate the three applications: Echo Client and Server, Chat
Application, and File Transfer Application.
1.Echo Client and Echo Server Simulation in NS2:
# Echo Client and Echo Server Simulation
# Create a new simulator instance
set ns [new Simulator]
# Create nodes for server and client
set server [ $ns node ]
set client [ $ns node ]
# Create a TCP connection
set tcpClient [new Agent/TCP]
set tcpServer [new Agent/TCPSink]
# Attach agents to client and server
$ns attach-agent $client $tcpClient
$ns attach-agent $server $tcpServer
# Set up the link between client and server (10Mb, 100ms)
$ns duplex-link $client $server 10Mb 100ms DropTail
# Set up application to send data (for echo request)
set echoApp [new Application/Traffic/ConstantTraffic]
$echoApp attach-agent $tcpClient
$echoApp set packetSize_ 128
$echoApp set interval_ 0.5
# Start the simulation after 0.1 seconds
$ns at 0.1 "$echoApp start"
$ns at 5.0 "puts \"Server has received the echo message\""
# Run the simulation
$ns run

2. Chat Application Simulation in NS2:


# Chat Application Simulation (Client-Server)
# Create a new simulator instance
set ns [new Simulator]
# Create server and client nodes
set server [ $ns node ]
set client [ $ns node ]
# Set up the TCP agents for client and server
set tcpClient [new Agent/TCP]
set tcpServer [new Agent/TCPSink]
$ns attach-agent $client $tcpClient
$ns attach-agent $server $tcpServer
# Create a duplex link between client and server (10Mb, 100ms)
$ns duplex-link $client $server 10Mb 100ms DropTail
# Set up the application to simulate message sending
set chatApp [new Application/Traffic/ConstantTraffic]
$chatApp attach-agent $tcpClient
$chatApp set packetSize_ 128
$chatApp set interval_ 0.5
# Start chat application after 0.1 seconds
$ns at 0.1 "$chatApp start"
# Run the simulation and output results
$ns at 5.0 "puts \"Chat messages exchanged successfully\""
$ns run

3.File Transfer Application Simulation in NS2:


# File Transfer Application Simulation (Client-Server)
# Create a new simulator instance
set ns [new Simulator]
# Create nodes for server and client
set server [ $ns node ]
set client [ $ns node ]
# Create TCP agents for file transfer
set tcpClient [new Agent/TCP]
set tcpServer [new Agent/TCPSink]
$ns attach-agent $client $tcpClient
$ns attach-agent $server $tcpServer
# Set up a duplex link between client and server (10Mb, 100ms)
$ns duplex-link $client $server 10Mb 100ms DropTail
# Set up file transfer application for the client
set fileApp [new Application/FTP]
$fileApp attach-agent $tcpClient
# Start the FTP file transfer application after 0.1 seconds
$ns at 0.1 "$fileApp start"
# End the simulation after 5 seconds
$ns at 5.0 "puts \"File Transfer Completed\""
$ns run
EXPERIMENT-16
Aim:
Applications using TCP and UDP Sockets like DNS, SNMP,File Transfer
Theory:
1. DNS (Domain Name System):
The Domain Name System (DNS) translates human-readable domain names (like
www.example.com) into IP addresses that computers use to identify each other on the network.
DNS typically works over UDP, as it requires fast, low-overhead communication.
• DNS over UDP: DNS queries are typically made using UDP for quick resolution.
• DNS over TCP: TCP is used when the response data is too large for a single UDP
packet or for reliable communication.
2. SNMP (Simple Network Management Protocol):
SNMP is a widely used protocol for monitoring and managing network devices such as routers,
switches, and servers. SNMP works over UDP as it is designed to be lightweight and efficient,
where devices send traps or requests to a manager.
• SNMP is typically implemented using UDP for simplicity and speed, especially for
monitoring devices that do not require a guaranteed delivery.
3. File Transfer Application:
File transfer between a client and server is one of the most common uses of TCP. The FTP
(File Transfer Protocol) typically uses TCP to ensure reliable transmission of large files. The
client sends a request to the server, and the server responds with the requested file.
• File Transfer over TCP: Guarantees reliable and ordered data transmission.
• File Transfer over UDP: Faster but unreliable (useful for applications that prioritize
speed over reliability).

Steps to Simulate DNS, SNMP, and File Transfer in NS2:


Below are the NS2 scripts to simulate these applications.
1. DNS Simulation Using UDP:
# DNS Client-Server Simulation using UDP
# Create a new simulator instance
set ns [new Simulator]
# Create server and client nodes
set dnsServer [ $ns node ]
set dnsClient [ $ns node ]
# Create a UDP agent for DNS communication
set udpClient [new Agent/UDP]
set udpServer [new Agent/UDP]
# Attach agents to the client and server
$ns attach-agent $dnsClient $udpClient
$ns attach-agent $dnsServer $udpServer
# Set up a link between the client and server (10Mb, 100ms delay)
$ns duplex-link $dnsClient $dnsServer 10Mb 100ms DropTail
# Create a DNS request from the client to the server
set dnsRequest [new Application/Traffic/ConstantTraffic]
$dnsRequest attach-agent $udpClient
$dnsRequest set packetSize_ 128
$dnsRequest set interval_ 1.0
# Start DNS request at 0.1 seconds
$ns at 0.1 "$dnsRequest start"
# End simulation at 10.0 seconds
$ns at 10.0 "puts \"DNS Query Sent\""
$ns run
2. SNMP Simulation Using UDP:
# SNMP Client-Server Simulation using UDP

# Create a new simulator instance


set ns [new Simulator]
# Create client and server nodes
set snmpServer [ $ns node ]
set snmpClient [ $ns node ]
# Create a UDP agent for SNMP communication
set udpSnmpClient [new Agent/UDP]
set udpSnmpServer [new Agent/UDP]
# Attach agents to client and server
$ns attach-agent $snmpClient $udpSnmpClient
$ns attach-agent $snmpServer $udpSnmpServer

# Set up the link between client and server (10Mb, 100ms delay)
$ns duplex-link $snmpClient $snmpServer 10Mb 100ms DropTail
# Create SNMP request from client to server
set snmpRequest [new Application/Traffic/ConstantTraffic]
$snmpRequest attach-agent $udpSnmpClient
$snmpRequest set packetSize_ 128
$snmpRequest set interval_ 1.0
# Start SNMP request at 0.1 seconds
$ns at 0.1 "$snmpRequest start"
# End simulation at 10.0 seconds
$ns at 10.0 "puts \"SNMP Request Sent\""
$ns run

3.File Transfer Application Using TCP:


# File Transfer Application using TCP
# Create a new simulator instance
set ns [new Simulator]
# Create client and server nodes
set fileServer [ $ns node ]
set fileClient [ $ns node ]
# Create TCP agents for client and server
set tcpClient [new Agent/TCP]
set tcpServer [new Agent/TCPSink]
# Attach agents to client and server
$ns attach-agent $fileClient $tcpClient
$ns attach-agent $fileServer $tcpServer
# Set up the link between client and server (10Mb, 100ms delay)
$ns duplex-link $fileClient $fileServer 10Mb 100ms DropTail
# Create File Transfer application for the client
set fileApp [new Application/FTP]
$fileApp attach-agent $tcpClient
# Start file transfer after 0.1 seconds
$ns at 0.1 "$fileApp start"
# End simulation after 5 seconds
$ns at 5.0 "puts \"File Transfer Completed\""
$ns run

Conclusion:
This experiment demonstrates the implementation of basic network applications using TCP
and UDP sockets in NS2:
1. DNS over UDP for efficient domain name resolution.
2. SNMP over UDP for network management and monitoring.
3. File Transfer over TCP for reliable data transmission.
These applications help in understanding the core principles of network
protocols and their implementation in real-world network environments.

You might also like