Nothing Special   »   [go: up one dir, main page]

CN MODAL

Download as pdf or txt
Download as pdf or txt
You are on page 1of 51

B.E / B.Tech.

PRACTICAL END SEMESTER EXAMINATIONS PROGRAMS


CS3591 – COMPUTER NETWORKS

1. Write a program with input “ hello_client” , the server listens for, and
accepts, a single TCP connection; it reads all the data it can from that
connection, and prints it to the screen; then it closes the connection.
Program:
Server Code:
import socket
host = '127.0.0.1'
port = 65432
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((host, port))
server_socket.listen(1)
print("Server is listening...")
conn, addr = server_socket.accept()
print(f"Connected by {addr}")
data = conn.recv(1024)
print("Received:", data.decode())
conn.close()
server_socket.close()
Client code:
import socket
host = '127.0.0.1'
port = 65432
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((host, port))
message = "hello_client"
client_socket.sendall(message.encode())
client_socket.close()

2. Write the Echo client and server programs using UDP. The Echo clients
should verify whether the text string they received from the server is the same
text string that they sent or not.
Program:
Server Code:
import socket
import sys
server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server_address=('localhost", 10000)
server.bind(server_address)
server.listen(1)
connection, client_address=server.accept()
print("Connection established with: ",client_address)
data=connection.recv(1000)
print("Received:", data)
connection.sendall (data)
connection.close()
server.close()
Client Code:
import socket
import sys
client=socket.socket(socket.AF_INET, socket.SOCK_ STREAM)
server_address=('localhost', 10000)
client.connect(server_address)
print("Enter the message")
message=input()
print("Sending", message)
client.sendall (message.encode())
print("ORIGINAL: ", message)
data=client.recv(1000).decode()
print("ECHO: ",data)
client.close()

3. To implement a CHAT application using TCP Socket communication for client


and server. Both can run in the same machine or different machines.
Program:
Server Code:
import socket
def start_server():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '127.0.0.1' # Localhost
port = 12345 # Arbitrary non-privileged port
server_socket.bind((host, port))
server_socket.listen(1) # Accept only 1 connection for simplicity
print(f"Server listening on {host}:{port}...")
conn, addr = server_socket.accept()
print(f"Connected by {addr}")
while True:
data = conn.recv(1024).decode()
if not data:
break
print(f"Client: {data}")
response = input("You (Server): ")
conn.send(response.encode())
conn.close()
if _name_ == "_main_":
start_server()
Client Code:
import socket
def start_client():
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '127.0.0.1' # The server's hostname or IP address
port = 12345 # The same port as used by the server
client_socket.connect((host, port))
while True:
message = input("You (Client): ")
client_socket.send(message.encode())
data = client_socket.recv(1024).decode()
print(f"Server: {data}")
client_socket.close()
if _name_ == "_main_":
start_client()

4. Write program to implement DNS using UDP Sockets by getting any frame
size based on the user request and send the frames to server.
Program:
Server Code:
import socket
def run_dns_server(server_port):
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind(("0.0.0.0", server_port))
print(f"DNS server is running on port {server_port}...")
while True:
frame, client_address = server_socket.recvfrom(2048)
print(f"Received frame from {client_address}: {frame.decode().strip()}")
response = f"Received {len(frame)} bytes".encode()
server_socket.sendto(response, client_address)
if _name_ == "_main_":
import argparse
parser = argparse.ArgumentParser(description="DNS-like UDP server.")
parser.add_argument("--port", type=int, default=5353, help="Port to use")
args = parser.parse_args()
run_dns_server(args.port)
Client Code:
import socket
def run_dns_client(server_address, server_port, frame_size):
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
frame = f"Requesting frame of size {frame_size}".encode()
if len(frame) < frame_size:
frame += b" " * (frame_size - len(frame))
print(f"Sending frame to server: {frame.decode().strip()}")
client_socket.sendto(frame, (server_address, server_port))
response, _ = client_socket.recvfrom(1024)
print(f"Received response from server: {response.decode().strip()}")
finally:
client_socket.close()
if _name_ == "_main_":
import argparse
parser = argparse.ArgumentParser(description="DNS-like UDP client.")
parser.add_argument("--address", default="127.0.0.1", help="Server address")
parser.add_argument("--port", type=int, default=5353, help="Port to use")
parser.add_argument("--frame-size", type=int, default=64, help="Frame size to request")
args = parser.parse_args()
run_dns_client(args.address, args.port, args.frame_size)
5. a) Write a program to implement to transfer the files using TCP socket.
Program:
Server Code:
import socket
def start_server(host='0.0.0.0', port=12345):
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((host, port))
server_socket.listen(1)
print(f"Server listening on {host}:{port}")
conn, addr = server_socket.accept()
print(f"Connection established with {addr}")
with open("received_file", "wb") as file:
print("Receiving file...")
while True:
data = conn.recv(1024)
if not data:
break
file.write(data)
print("File received successfully.")
conn.close()
server_socket.close()
start_server()
Client Code:
import socket
def send_file(file_path, host='127.0.0.1', port=12345):
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((host, port))
print(f"Connected to server at {host}:{port}")
with open(file_path, "rb") as file:
print("Sending file...")
while chunk := file.read(1024):
client_socket.sendall(chunk)
print("File sent successfully.")
client_socket.close()
file_path = input("Enter the file path to send: ")
send_file(file_path)

b) Using Wireshark capture the FTP username and password.

To capture FTP details using Wireshark, follow these step-by-step instructions:


Prerequisites:
- Ensure you have Wireshark installed on your system.
- Make sure you have the necessary permissions to capture network traffic on the network
interface you're using.
Steps to Capture FTP Details:
1. Start Wireshark:
- Open Wireshark.
- Select the network interface you want to capture traffic on (e.g., Ethernet or Wi-Fi).
2. Set the Capture Filter:
- To focus on FTP traffic, set a capture filter. FTP typically runs over TCP port 21.
- In the "Capture Filter" field, enter the following:
port 21
- This filter ensures that Wireshark only captures traffic on port 21, which is used by FTP
for control communication.
3. Start the Capture:
- Click on the “Start” button (green shark fin) to begin capturing the network traffic.
4. Initiate FTP Traffic:
- On the target system, open an FTP client (such as FileZilla, command-line FTP, or any
other FTP software).
- Perform FTP operations like logging in, uploading/downloading files, or navigating
directories. For example:
Login: Provide a username and password.
File transfer: Use commands like RETR (retrieve file) or STOR (store file).
5. Observe FTP Traffic:
- As you perform FTP operations, Wireshark will capture the associated packets.
- Look for FTP commands such as:
- USER (username)
- PASS (password)
- RETR (retrieve file)
- STOR (store file)
- These commands, along with the associated data, will be displayed in Wireshark’s packet
list.
6. Apply the Display Filter for FTP:
- To focus on FTP traffic, you can use the display filter: ftp
- This filter shows only FTP protocol packets in the captured traffic.
7. Inspect FTP Details:
- Select a packet related to FTP control (e.g., a USER or PASS command).
- In the packet details pane, expand the FTP section to view the command, parameters,
and any data sent.
- For example:
- *USER* will show the username.
- *PASS* will show the password (if transmitted in plain text, which FTP often does unless
encrypted).
- *RETR* or *STOR* will show the filenames for file transfers.
8. Stop the Capture:
- After you've captured enough data, click on the red square ("Stop") button in Wireshark
to halt the capture session.
9. Save the Capture (Optional):
- If you wish to save the captured data for later analysis, go to *File > Save As* and save the
capture file in your desired format (typically .pcap).
Notes:
- FTP transmits data in *cleartext*, so usernames, passwords, and file contents can be easily
observed in Wireshark.
- If the FTP session is encrypted (using FTPS or FTP over SSL/TLS), the data will not be visible
in Wireshark without the necessary decryption keys.
- Always ensure that you have authorization to capture and analyze network traffic,
especially in production environments.
This process will help you capture FTP session details like logins, commands, and data
transfers.

6. Write the program for simulating the ARP protocol by reading an IP address
and returning the MAC address.
Program:
def simulate_arp(ip_address, arp_table):
return arp_table.get(ip_address, "MAC address not found for the given IP
address.")
arp_table = {
"192.168.1.1": "00:1A:2B:3C:4D:5E",
"192.168.1.2": "00:1A:2B:3C:4D:5F",
"192.168.1.3": "00:1A:2B:3C:4D:60",
}
ip_address = input("Enter the IP address to resolve: ")
mac_address = simulate_arp(ip_address, arp_table)
print(f"MAC address for {ip_address}: {mac_address}")

7. Write a program for simulating RARP protocols using UDP.


Program:
Server Code:
import socket
table = {
'1E.4A.4A.11': '192.168.1.1',
'5E.51.4B.01': '192.168.2.1',
'4B.35.CD.32': '192.168.1.3',
'AF.4D.1F.FF': '192.168.4.1',
'C3.C5.EE.C2': '192.168.3.2'
}
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind(('localhost', 1234))
while True:
data, client_address = server_socket.recvfrom(1024)
mac_address = data.decode('utf-8')
ip_address = table.get(mac_address, 'No entry for given MAC address')
server_socket.sendto(ip_address.encode('utf-8'), client_address)
Client Code:
import socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = ('localhost', 1234)
mac_address = input("Enter the MAC address to find the corresponding IP: ")
client_socket.sendto(mac_address.encode('utf-8'), server_address)
data, _ = client_socket.recvfrom(1024)
ip_address = data.decode('utf-8')
print(f"The IP address for MAC {mac_address} is: {ip_address}")
client_socket.close()

8. Simulate of Congestion Control Algorithms using NS and examine the


performance of algorithm.

1. Objectives:
Simulate different congestion control algorithms like TCP Tahoe, TCP Reno, TCP NewReno,
and TCP Vegas.
Measure and compare metrics such as throughput, packet loss, latency, and fairness.
2. Prerequisites:
Install NS-2 or NS-3:
NS-2: Widely used, but older.
NS-3: More modern with enhanced features.
Basic knowledge of scripting in TCL (for NS-2) or Python/C++ (for NS-3).
Familiarity with Linux-based systems.
3. Steps for NS Simulation:
Step 1: Network Topology
Define a network topology.
Nodes: Sender, Receiver, and Routers.
Links: Wired or wireless with specific bandwidth and delay.
For example: scss
n0 ---- n1 ---- n2 ---- n3
(Src) (R1) (R2) (Dest)
Step 2: Congestion Control Algorithms
Select and configure TCP congestion control algorithms:
For NS-2, you can set the agent type to the desired algorithm (e.g., TCP Reno).
In NS-3, use the TcpSocketFactory to set the congestion algorithm.
Step 3: Write TCL (NS-2) or Python (NS-3) Script
NS-2 Example (TCL):tcl
set ns [new Simulator]
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
# Create links
$ns duplex-link $n0 $n1 10Mb 10ms DropTail
$ns duplex-link $n1 $n2 1.5Mb 20ms DropTail
$ns duplex-link $n2 $n3 10Mb 10ms DropTail
# Define TCP Reno
set tcp [new Agent/TCP/Reno]
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink]
$ns attach-agent $n3 $sink
$ns connect $tcp $sink
NS-3 Example (Python):
import ns.applications as apps
import ns.internet as internet
import ns.core as core
import ns.network as network
# Set TCP Congestion Control
internet.TcpSocketFactory.SetDefault("ns3::TcpNewReno")
# Create Nodes
nodes = network.NodeContainer()
nodes.Create(4)
# Configure topology and applications...
Step 4: Collect Metrics
Use tools like:
Trace files for packet-level details.
FlowMon module (NS-3) to measure throughput and latency.
4. Metrics to Analyze:
Throughput: Rate of successful data delivery.
Packet Loss: Percentage of dropped packets.
Latency: Time taken for a packet to traverse the network.
Fairness Index: Measure of equitable bandwidth sharing among flows.
5. Performance Evaluation:
Run simulations for various scenarios:
Vary link bandwidth and delays.
Test under high traffic loads.
Compare congestion control algorithms side-by-side.
Use tools like MATLAB, Excel, or Python to graph the results.
6. Example Analysis
For TCP Reno vs TCP Vegas:
TCP Reno: High throughput but aggressive; more packet loss.
TCP Vegas: Better latency control but sensitive to RTT.

9. Writer a program to implement the Distance Vector Routing algorithm and


find out the correct path from client to server where the packets send.
Program:
def bfe(c, intermediate_node, neighbor, no_node):
flag = 0
for i in neighbor:
for j in range(no_node):
if (c[i][intermediate_node] + c[intermediate_node][j]) < c[i][j]:
# Using Bellman Ford Equation
c[i][j] = c[i][intermediate_node] + c[intermediate_node][j]
flag = 1
# c[i][i]=0
if flag == 1:
bfe(c, i, neighbor_set[i], no_node)
if flag == 0 and intermediate_node < no_node - 1:
intermediate_node += 1
bfe(c, intermediate_node, neighbor_set[intermediate_node], no_node)
return
no_node = int(input("Enter the number of nodes: "))
c = [[0 for j in range(no_node)] for i in range(no_node)]
for i in range(no_node):
print(f"Enter initial cost for node {i}: ")
for j in range(no_node):
c[i][j] = int(input())
print("Initial cost matrix:\n")
for i in range(no_node):
for j in range(no_node):
print(c[i][j], end=" ")
print("\n")
neighbor_set = [[] for i in range(no_node)]
for i in range(no_node):
for j in range(no_node):
if i != j: # always reachable from its own node
if c[i][j] != 1000:
neighbor_set[i].append(j)
print("Neighbors:\n", neighbor_set, "\n")
bfe(c, 0, neighbor_set[0], no_node) # initial call
print("Final cost matrix:\n")
for i in range(no_node):
for j in range(no_node):
print(c[i][j], end=" ")
print("\n")

10. Implementation of Link state routing algorithm and analyze the path where
the packets are sending from client to server.
Program:
inf = float("inf")
def neighbour(x): # Finding the neighbors of a given node
neigh_index = []
for j in range(n):
if j != x and LSDB[x][j] < inf: # If not the same node and there is a direct link
neigh_index.append(j)
return neigh_index
def create_temp():
temp = {}
# Create a dictionary corresponding to the root node
# Key as the index of node and values are distance to every other node
for i in range(len(D)):
if i not in tree: # Include only nodes not already in the tree
temp[i] = D[i]
return temp
# Input the number of nodes
print('Enter the number of nodes:')
n = int(input())
# Initialize the Link State Database (LSDB)
LSDB = [[inf for i in range(n)] for j in range(n)]
for i in range(n):
print(f'Enter the distances for node {chr(i + 65)} (use "inf" for no direct connection):')
for j in range(n):
a = input()
if a.lower() != "inf":
LSDB[i][j] = int(a)
# Input the starting node
print('Enter the root node:')
b = ord(input().upper()) - 65
tree = [b] # Start with the root node
print('Tree =>', tree)
# Initialize distance matrix and parent array
D = [inf for i in range(n)] # Distance matrix
parent = [tree[0] for i in range(n)] # Parent matrix
# Fill the D matrix with available info from LSDB
for j in range(n):
if j == tree[0]: # Distance to itself is 0
D[j] = 0
elif LSDB[tree[0]][j] < inf: # If it is a neighbor
D[j] = LSDB[tree[0]][j]
# Link-State Routing Algorithm
while True:
temp = create_temp()
print("temp =", temp)
print("D =", D)
# Find the node with the smallest distance in temp
mini = min(temp.values())
ind = list(temp.values()).index(mini)
w = list(temp.keys())[ind]
# Add the selected node to the tree
tree.append(w)
print("w => tree:", w, tree)
# Update distances for all neighbors of w not already in the tree
for x in neighbour(w):
if x not in tree:
if D[w] + LSDB[w][x] < D[x]:
D[x] = D[w] + LSDB[w][x]
parent[x] = w
if len(tree) == n: # All nodes are processed
break
# Construct the routes
route = [chr(i + 65) for i in range(n)] # Initial paths (node names)
for i in range(n):
ind = i
while True:
route[i] = route[i] + "-->" + chr(parent[ind] + 65)
ind = parent[ind]
if ind == tree[0]: # Stop when the root node is reached
break
# Output the results
print('\nThe Distance of every node from the root node and its path is given below:')
print("Node\tDistance\tPath")
for i in range(n):
print(f"{chr(i + 65)}\t{D[i]}\t\t{route[i]}")

11. To create Scenario and study the performance of CSMA/CD protocol


through simulation For the given data, use CRC. Verify the program for the
cases.
i) Without error.
Program:

import random
import time
# CRC generator polynomial
CRC_POLYNOMIAL = '1101' # Example: CRC-3
# Function to perform CRC
def generate_crc(data, polynomial):
data_with_padding = data + '0' * (len(polynomial) - 1)
while '1' in data_with_padding[:len(data)]:
pos = data_with_padding.index('1')
for i in range(len(polynomial)):
data_with_padding = (
data_with_padding[:pos + i]
+ str(int(data_with_padding[pos + i]) ^ int(polynomial[i]))
+ data_with_padding[pos + i + 1:]
)
return data_with_padding[-(len(polynomial) - 1):]
# Simulate CSMA/CD
def simulate_csma_cd(num_nodes, num_packets):
successful_transmissions = 0
total_collisions = 0
for packet in range(num_packets):
transmitting_nodes = [i for i in range(num_nodes) if random.choice([True, False])]
if len(transmitting_nodes) == 1:
# Successful transmission
data = f'{packet:08b}'
crc = generate_crc(data, CRC_POLYNOMIAL)
transmitted_packet = data + crc
print(f"Node {transmitting_nodes[0]} successfully transmitted: {transmitted_packet}")
successful_transmissions += 1
elif len(transmitting_nodes) > 1:
# Collision detected
print(f"Collision detected among nodes: {transmitting_nodes}")
total_collisions += 1
time.sleep(0.5) # Simulate delay
print("\nSimulation Results:")
print(f"Total packets transmitted: {num_packets}")
print(f"Successful transmissions: {successful_transmissions}")
print(f"Total collisions: {total_collisions}")

# Main function
if __name__ == "__main__":
# Get user input for number of nodes and number of packets
try:
num_nodes = int(input("Enter the number of nodes in the network: "))
num_packets = int(input("Enter the number of packets to be transmitted: "))
# Ensure positive numbers for both values
if num_nodes <= 0 or num_packets <= 0:
print("Both numbers must be positive integers. Exiting.")
else:
simulate_csma_cd(num_nodes, num_packets)
except ValueError:
print("Invalid input. Please enter integers only.")

ii)With error

import random
# CRC Functionality
def generate_crc(data, divisor):
"""Generate CRC code."""
data = data + '0' * (len(divisor) - 1)
data = list(data)
divisor = list(divisor)
for i in range(len(data) - len(divisor) + 1):
if data[i] == '1': # Perform XOR if bit is 1
for j in range(len(divisor)):
data[i + j] = str(int(data[i + j]) ^ int(divisor[j]))
return ''.join(data[-(len(divisor)-1):])
def verify_crc(data, divisor, crc):
"""Verify CRC code."""
return generate_crc(data + crc, divisor) == '0' * (len(divisor) - 1)
# CSMA/CD Simulation
def csma_cd_simulation(nodes, divisor, with_error=False):
"""Simulate CSMA/CD with CRC."""
channel = None # Channel state: None means idle, otherwise contains the transmitting
node
collisions = 0
successful_transmissions = 0
# Simulate multiple transmission attempts
for attempt in range(100):
# Randomly select nodes to attempt transmission
transmitting_nodes = [i for i in range(nodes) if random.random() < 0.2]
if len(transmitting_nodes) > 1: # Collision occurs
collisions += 1
continue
if len(transmitting_nodes) == 1:
sender = transmitting_nodes[0]
data = f"Node{sender}Data{attempt}"
crc = generate_crc(data, divisor)
if with_error and random.random() < 0.1: # Introduce error
data = data[:-1] + ('1' if data[-1] == '0' else '0')
# Receiver verifies CRC
if verify_crc(data, divisor, crc):
successful_transmissions += 1
return collisions, successful_transmissions
# Main Execution
if _name_ == "_main_":
nodes = 10 # Number of nodes in the network
divisor = "1101" # Example CRC divisor polynomial
print("Simulation with Error:")
collisions, successes = csma_cd_simulation(nodes, divisor, with_error=True)
print(f"Collisions: {collisions}, Successful Transmissions: {successes}")
print("\nSimulation without Error:")
collisions, successes = csma_cd_simulation(nodes, divisor, with_error=False)
print(f"Collisions: {collisions}, Successful Transmissions: {successes}")

12. Implement Stop and Wait Protocol and Sliding Window Protocol in a C
program and execute the same and display the result using Stop and Wait
Protocol.
Program:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h> // For sleep function
// Stop-and-Wait Protocol with Retransmission
void stopAndWaitWithRetransmission() {
int totalFrames, i;
int ackReceived; // Flag to simulate acknowledgment
int maxRetries = 3; // Maximum number of retransmissions allowed
int retryCount;
printf("Enter the number of frames to send: ");
scanf("%d", &totalFrames);
srand(time(NULL)); // Seed for random acknowledgment simulation

for (i = 0; i < totalFrames; i++) {


retryCount = 0;
ackReceived = 0; // Reset acknowledgment flag

while (!ackReceived && retryCount <= maxRetries) {


printf("\nSending frame %d...", i + 1);
sleep(1); // Simulate delay
// Simulate acknowledgment (50% chance of failure)
if (rand() % 2 == 0) {
ackReceived = 1; // ACK received
printf(" Acknowledgment received for frame %d.\n", i + 1);
} else {
retryCount++;
if (retryCount <= maxRetries) {
printf(" No acknowledgment received. Retrying (%d/%d)...\n", retryCount,
maxRetries);
}
}
// Timeout if maximum retries exceeded
if (retryCount > maxRetries) {
printf(" Frame %d failed to send after %d retries. Moving to next frame.\n", i + 1,
maxRetries);
break;
}
}
}
printf("\nAll frames processed with Stop-and-Wait Protocol (with retransmission).\n");
}
// Sliding Window Protocol
void slidingWindowProtocol() {
int totalFrames, windowSize, i, ack = 0;
int ackReceived; // Flag to simulate acknowledgment
printf("Enter the number of frames to send: ");
scanf("%d", &totalFrames);
printf("Enter the window size: ");
scanf("%d", &windowSize);
srand(time(NULL)); // Seed for random acknowledgment simulation
for (i = 0; i < totalFrames; i++) {
if ((i - ack) < windowSize) {
printf("\nSending frame %d...", i + 1);
sleep(1); // Simulate delay

// Simulate acknowledgment (70% chance of success)


if (rand() % 10 < 7) {
printf(" Acknowledgment received for frame %d.\n", i + 1);
ack++;
} else {
printf(" No acknowledgment received for frame %d.\n", i + 1);
}
} else {
printf("\nWaiting for acknowledgment for frame %d...", ack + 1);
sleep(1); // Simulate delay
printf(" Acknowledgment received for frame %d.\n", ack + 1);
ack++;
}
}
while (ack < totalFrames) {
printf("\nWaiting for acknowledgment for frame %d...", ack + 1);
sleep(1); // Simulate delay
printf(" Acknowledgment received for frame %d.\n", ack + 1);
ack++;
}
printf("\nAll frames sent successfully using Sliding Window Protocol.\n");
}
// Main Function
int main() {
int choice;
while (1) {
printf("\nChoose the protocol to use:\n");
printf("1. Stop-and-Wait Protocol (with retransmission)\n");
printf("2. Sliding Window Protocol\n");
printf("3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
stopAndWaitWithRetransmission();
break;
case 2:
slidingWindowProtocol();
break;
case 3:
printf("Exiting the program.\n");
exit(0);
default:
printf("Invalid choice! Please try again.\n");
}
}
return 0;
}

13. Implement a four node point to point network with links n0-n2, n1-n2 and
n2-n3. Apply TCP agent between n0-n3 and UDP between n1-n3. Apply
relevant applications over TCP and UDP agents changing the parameter and
determine the number of packets sent by TCP/UDP.
Program:

# Create a simulator instance


set ns [new Simulator]
# Define the output trace file
set tracefile [open out.tr w]
$ns trace-all $tracefile
# Create nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
# Create point-to-point 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
# Define TCP agent between n0 and n3
set tcp [new Agent/TCP]
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink]
$ns attach-agent $n3 $sink
$ns connect $tcp $sink
# Define UDP agent between n1 and n3
set udp [new Agent/UDP]
$ns attach-agent $n1 $udp
set null [new Agent/Null]
$ns attach-agent $n3 $null
$ns connect $udp $null
# Define an application over TCP
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ftp set interval_ 0.2 ;# FTP sends data at regular intervals

# Define an application over UDP


set cbr [new Application/Traffic/CBR]
$cbr attach-agent $udp
$cbr set packetSize_ 512 ;# Set packet size for CBR
$cbr set rate_ 1Mb ;# Set data rate for CBR

# Schedule events
$ns at 0.1 "$ftp start"
$ns at 0.2 "$cbr start"
$ns at 4.0 "$ftp stop"
$ns at 4.0 "$cbr stop"

# Run the simulation


$ns at 4.5 "finish"
proc finish {} {
global ns tracefile
$ns flush-trace
close $tracefile
exit 0
}

# Run the simulator


$ns run
14. Write a HTTP web client program to download any web page using TCP
sockets.
Program:
import socket
def download_web_page(host, page="/", output_file="output.html"):
try:
# Create a TCP socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print(f"Resolving host: {host}")
# Connect to the server on port 80 (HTTP)
s.connect((host, 80))
print(f"Connected to {host} on port 80")
# Prepare the HTTP GET request
request = f"GET {page} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n"
s.sendall(request.encode('utf-8'))
# Receive the response
response = b""
part = s.recv(4096)
response += part
# Decode and separate headers from the body
response_text = response.decode('utf-8', errors='ignore')
headers, body = response_text.split("\r\n\r\n", 1)
# Save the body to a file
with open(output_file, "w", encoding="utf-8") as f:
f.write(body)
print(f"Web page downloaded successfully! Saved to {output_file}")

except socket.gaierror as e:
print(f"Socket error: {e}")
except Exception as e:
print(f"An error occurred: {e}")
finally:
# Close the socket
s.close()
# Example usage
download_web_page("google.com", "/")

15. Write a program to implement the TCP echo client server for send the
message input from the user and display the data received from the server.
Program:
Server Code:
import socket
def start_server(host='127.0.0.1', port=65432):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:
server_socket.bind((host, port))
server_socket.listen()
print(f"Server listening on {host}:{port}")
while True:
conn, addr = server_socket.accept()
with conn:
print(f"Connected by {addr}")
while True:
data = conn.recv(1024)
if not data:
break
print(f"Received from client: {data.decode()}")
conn.sendall(data) # Echo back the received data
if __name__ == "__main__":
start_server()
Client Code:
import socket
def start_client(host='127.0.0.1', port=65432):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client_socket:
client_socket.connect((host, port))
print(f"Connected to server {host}:{port}")
while True:
message = input("Enter message to send (type 'exit' to quit): ")
if message.lower() == 'exit':
print("Closing connection.")
break
client_socket.sendall(message.encode())
data = client_socket.recv(1024)
print(f"Received from server: {data.decode()}")
if __name__ == "__main__":
start_client()

16. Write a program for UDP echo client server for send the message input
from the user and display the data received from the server.
Program:
Server Code:
import socket
def udp_echo_server():
server_address = ('localhost', 12345) # Server address and port
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind(server_address)
print(f"Server listening on {server_address}")
while True:
message, client_address = server_socket.recvfrom(4096)
print(f"Received message: {message.decode()} from {client_address}")
# Echo the message back to the client
server_socket.sendto(message, client_address)

# Directly call the function


udp_echo_server()

Client Code:
import socket
def udp_echo_client():
server_address = ('localhost', 12345) # Server address and port
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
message = input("Enter message to send to server (type 'exit' to quit): ")
if message.lower() == 'exit':
break
# Send message to server
client_socket.sendto(message.encode(), server_address)

# Receive the echoed message from the server


data, server = client_socket.recvfrom(4096)
print(f"Received from server: {data.decode()}")
client_socket.close()
# Directly call the function
udp_echo_client()

17. Analyze the TCP/UDP performance using Simulation tool and compare it
with suitable data.
ALGORITHM:
STEP 1: Configure the IP address and the DNS server for all the clients (Web, Email, FTP and
DNS) and the multi-server.
STEP 2: In the Email client and the web client, go to mail and configure the email id.
STEP 3: In the server, under services, switch on http and edit the index.html file.
STEP 4: In the server, under services, switch on DNS and add the domain name and the IP
address corresponding to the server.
STEP 5: In the server, under services, switch on the SMTP and POP3 services and specify the
domain name of the email address. Also, configure the email username and password.
STEP 6: In the server, under services, switch on FTP, create a username and password and
specify the rights for that user.
STEP 7: In the DNS client, using the nslookup command check for the IP address of the
server.
STEP 8: In the FTP client, using the ftp command, connect to the FTP server.
STEP 9: In the email client, compose a new email to another email id that is already created
and send it.
STEP 10: In the web client, login using the other email id and check if the email was
received.
STEP 11: In the web client, open the browser and enter the domain name of the webserver
and load the web page.

18. Write a program to implement CRC error detection techniques .Identify the
errors and display the error message.

Program:
package Ten;
import java.util.*;
public class CRC {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int n;
System.out.println("Enter the size of the data:");
n = scan.nextInt();
int data[] = new int[n];
System.out.println("Enter the data, bit by bit:");
for (int i = 0; i < n; i++) {
System.out.println("Enter bit number " + (i + 1) + ":");
data[i] = scan.nextInt();
}
System.out.println("Enter the size of the divisor:");
int m = scan.nextInt();
int divisor[] = new int[m];
System.out.println("Enter the divisor, bit by bit:");
for (int i = 0; i < m; i++) {
System.out.println("Enter bit number " + (i + 1) + ":");
divisor[i] = scan.nextInt();
}
int remainder[] = divide(data, divisor);
System.out.println("The CRC code generated is:");
for (int i = 0; i < data.length; i++) {
System.out.print(data[i]);
}
for (int i = 0; i < remainder.length - 1; i++) {
System.out.print(remainder[i]);
}
System.out.println();
int sent_data[] = new int[data.length + remainder.length - 1];
System.arraycopy(data, 0, sent_data, 0, data.length);
System.arraycopy(remainder, 0, sent_data, data.length, remainder.length - 1);
receive(sent_data, divisor);
}
static int[] divide(int old_data[], int divisor[]) {
int remainder[] = new int[divisor.length]; // Initialize remainder array
int data[] = new int[old_data.length + divisor.length];
System.arraycopy(old_data, 0, data, 0, old_data.length);
System.arraycopy(data, 0, remainder, 0, divisor.length);

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


if (remainder[0] == 1) {
for (int j = 1; j < divisor.length; j++) {
remainder[j - 1] = exor(remainder[j], divisor[j]);
}
} else {
for (int j = 1; j < divisor.length; j++) {
remainder[j - 1] = exor(remainder[j], 0);
}
}
if (i + divisor.length < data.length) {
remainder[divisor.length - 1] = data[i + divisor.length];
}
}
return remainder;
}
static int exor(int a, int b) {
return (a == b) ? 0 : 1;
}
static void receive(int data[], int divisor[]) {
int remainder[] = divide(data, divisor);
for (int i = 0; i < remainder.length; i++) {
if (remainder[i] != 0) {
System.out.println("There is an error in received data...");
return;
}
}
System.out.println("Data was received without any error.");
}
}

19. Write a program to make the TCP server to receive a request, to process the
request, and to send back the response. The server program needs to accept
the request string, change all lowercase letters to uppercase letters, and return
the result.
Program:
#include <stdio.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h> // read(), write(), close()
#define MAX 80
#define PORT 8080
#define SA struct sockaddr
// Function designed for chat between client and server.
void func(int connfd)
{
char buff[MAX];
int n;
// infinite loop for chat
for (;;) {
bzero(buff, MAX);
read(connfd, buff, sizeof(buff));
printf("From client: %s\t To client : ", buff);
bzero(buff, MAX);
n = 0;
// copy server message in the buffer
while ((buff[n++] = getchar()) != '\n')
;
write(connfd, buff, sizeof(buff));
if (strncmp("exit", buff, 4) == 0) {
printf("Server Exit...\n");
break;
}
}
}
int main()
{
int sockfd, connfd, len;
struct sockaddr_in servaddr, cli;

// socket create and verification


sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
printf("socket creation failed...\n");
exit(0);
}
else
printf("Socket successfully created..\n");
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);
if ((bind(sockfd, (SA*)&servaddr, sizeof(servaddr))) != 0) {
printf("socket bind failed...\n");
exit(0);
}
else
printf("Socket successfully binded..\n");

// Now server is ready to listen and verification


if ((listen(sockfd, 5)) != 0) {
printf("Listen failed...\n");
exit(0);
}
else
printf("Server listening..\n");
len = sizeof(cli);
// Accept the data packet from client and verification
connfd = accept(sockfd, (SA*)&cli, &len);
if (connfd < 0) {
printf("server accept failed...\n");
exit(0);
}
else
printf("server accept the client...\n");
func(connfd);
close(sockfd);
}
20. Write the performance evaluation of any two routing protocol using any
simulation tool and compare it with your own data.
The performance evaluation:
# Create simulator instance and set up files
set ns_ [new Simulator]
set tracefd [open sim.tr w]
set namtrace [open sim.nam w]
$ns_ trace-all $tracefd
$ns_ namtrace-all-wireless $namtrace 500 500

# Setup topography
set topo [new Topography]
$topo load_flatgrid 500 500

# General node settings


$ns_ node-config -adhocRouting AODV \
-llType LL \
-macType Mac/802_11 \
-ifqType Queue/DropTail/PriQueue \
-ifqLen 50 \
-antType Antenna/OmniAntenna \
-propType Propagation/TwoRayGround \
-phyType Phy/WirelessPhy \
-channel [new Channel/WirelessChannel] \
-topoInstance $topo \
-agentTrace ON \
-routerTrace ON \
-macTrace ON
# Create nodes
set n1 [$ns_ node]
set n2 [$ns_ node]
set n3 [$ns_ node]

# Position nodes
$n1 set X_ 100; $n1 set Y_ 100; $n1 set Z_ 0
$n2 set X_ 200; $n2 set Y_ 200; $n2 set Z_ 0
$n3 set X_ 300; $n3 set Y_ 300; $n3 set Z_ 0

# Configure mobility
$ns_ at 1.0 "$n2 setdest 250 250 10.0"
$ns_ at 2.0 "$n3 setdest 150 150 15.0"

# Create traffic connections


set udp0 [$ns_ create-connection UDP $n1 LossMonitor $n2 0]
set cbr0 [$udp0 attach-app Traffic/CBR]
$cbr0 set packetSize_ 512
$cbr0 set interval_ 0.2
$ns_ at 0.5 "$cbr0 start"
$ns_ at 4.0 "$cbr0 stop"

# Stop simulation
proc stop {} {
global ns_ tracefd
$ns_ flush-trace
close $tracefd
exec nam sim.nam &
exit 0
}
puts "Starting Simulation"
$ns_ at 10.0 "stop"
$ns_ run

(OR)
### Setting The Simulator Objects
set ns_ [new Simulator]
#create the nam and trace file:
set tracefd [open aodv.tr w]
$ns_ trace-all $tracefd
set namtrace [open aodv.nam w]
$ns_ namtrace-all-wireless $namtrace $val(x) $val(y)
set topo [new Topography]
$topo load_flatgrid $val(x) $val(y)
create-god $val(nn)
set chan_1_ [new $val(chan)]
#### Setting The Distance Variables
# For model &#39;TwoRayGround&#39;
set dist(5m) 7.69113e-06
set dist(9m) 2.37381e-06
set dist(10m) 1.92278e-06
set dist(11m) 1.58908e-06
set dist(12m) 1.33527e-06
set dist(13m) 1.13774e-06
set dist(14m) 9.81011e-07
set dist(15m) 8.54570e-07

100
set dist(16m) 7.51087e-07
set dist(20m) 4.80696e-07
set dist(25m) 3.07645e-07
set dist(30m) 2.13643e-07
set dist(35m) 1.56962e-07
set dist(40m) 1.56962e-10
set dist(45m) 1.56962e-11
set dist(50m) 1.20174e-13
Phy/WirelessPhy set CSThresh_ $dist(50m)
Phy/WirelessPhy set RXThresh_ $dist(50m)
# Defining Node Configuration

$ns_ node-config -adhocRouting $val(rp) \


-llType $val(ll) \
-macType $val(mac) \
-ifqType $val(ifq) \
-ifqLen $val(ifqlen) \
-antType $val(ant) \
-propType $val(prop) \
-phyType $val(netif) \
-topoInstance $topo \
-agentTrace ON \
-routerTrace ON \
-macTrace ON \
-movementTrace ON \
-channel $chan_1_
### Creating The WIRELESS NODES
set Server1 [$ns_ node]
set Server2 [$ns_ node]
set n2 [$ns_ node]
set n3 [$ns_ node]
set n4 [$ns_ node]
set n5 [$ns_ node]
set n6 [$ns_ node]
set n7 [$ns_ node]
set n8 [$ns_ node]
set n9 [$ns_ node]
set n10 [$ns_ node]
set n11 [$ns_ node]
set n12 [$ns_ node]
set n13 [$ns_ node]
set n14 [$ns_ node]
set n15 [$ns_ node]
set n16 [$ns_ node]
set n17 [$ns_ node]

100

set n18 [$ns_ node]


set n19 [$ns_ node]
set n20 [$ns_ node]
set n21 [$ns_ node]
set n22 [$ns_ node]
set opt(seed) 0.1
set a [ns-random $opt(seed)]
set i 0
while {$i &lt; 5} {
incr i
}
### Setting The Initial Positions of Nodes
$Server1 set X_ 513.0
$Server1 set Y_ 517.0
$Server1 set Z_ 0.0
$Server2 set X_ 1445.0
$Server2 set Y_ 474.0
$Server2 set Z_ 0.0
$n2 set X_ 36.0
$n2 set Y_ 529.0
$n2 set Z_ 0.0
$n3 set X_ 143.0
$n3 set Y_ 666.0
$n3 set Z_ 0.0
$n4 set X_ 201.0
$n4 set Y_ 552.0
$n4 set Z_ 0.0
$n5 set X_ 147.0
$n5 set Y_ 403.0
$n5 set Z_ 0.0
$n6 set X_ 230.0
$n6 set Y_ 291.0
$n6 set Z_ 0.0
$n7 set X_ 295.0
$n7 set Y_ 419.0
$n7 set Z_ 0.0

100
$n8 set X_ 363.0
$n8 set Y_ 335.0
$n8 set Z_ 0.0
$n9 set X_ 334.0
$n9 set Y_ 647.0
$n9 set Z_ 0.0
$n10 set X_ 304.0
$n10 set Y_ 777.0
$n10 set Z_ 0.0
$n11 set X_ 412.0
$n11 set Y_ 194.0
$n11 set Z_ 0.0
$n12 set X_ 519.0
$n12 set Y_ 361.0
$n12 set Z_ 0.0
$n13 set X_ 569.0
$n13 set Y_ 167.0
$n13 set Z_ 0.0
$n14 set X_ 349.0
$n14 set Y_ 546.0
$n14 set Z_ 0.0
$n15 set X_ 466.0
$n15 set Y_ 668.0
$n15 set Z_ 0.0
$n16 set X_ 489.0
$n16 set Y_ 794.0
$n16 set Z_ 0.0
$n17 set X_ 606.0
$n17 set Y_ 711.0
$n17 set Z_ 0.0
$n18 set X_ 630.0
$n18 set Y_ 626.0
$n18 set Z_ 0.0
$n19 set X_ 666.0
$n19 set Y_ 347.0
$n19 set Z_ 0.0
$n20 set X_ 741.0
$n20 set Y_ 152.0
$n20 set Z_ 0.0

100

$n21 set X_ 882.0


$n21 set Y_ 264.0
$n21 set Z_ 0.0
$n22 set X_ 761.0
$n22 set Y_ 441.0
$n22 set Z_ 0.0
## Giving Mobility to Nodes
$ns_ at 0.75 &quot;$n2 setdest 379.0 349.0 20.0&quot;
$ns_ at 0.75 &quot;$n3 setdest 556.0 302.0 20.0&quot;
$ns_ at 0.20 &quot;$n4 setdest 309.0 211.0 20.0&quot;
$ns_ at 1.25 &quot;$n5 setdest 179.0 333.0 20.0&quot;
$ns_ at 0.75 &quot;$n6 setdest 139.0 63.0 20.0&quot;
$ns_ at 0.75 &quot;$n7 setdest 320.0 27.0 20.0&quot;
$ns_ at 1.50 &quot;$n8 setdest 505.0 124.0 20.0&quot;
$ns_ at 1.25 &quot;$n9 setdest 274.0 487.0 20.0&quot;
$ns_ at 1.25 &quot;$n10 setdest 494.0 475.0 20.0&quot;
$ns_ at 1.25 &quot;$n11 setdest 899.0 757.0 25.0&quot;
$ns_ at 0.50 &quot;$n12 setdest 598.0 728.0 25.0&quot;
$ns_ at 0.25 &quot;$n13 setdest 551.0 624.0 25.0&quot;
$ns_ at 1.25 &quot;$n14 setdest 397.0 647.0 25.0&quot;
$ns_ at 1.25 &quot;$n15 setdest 748.0 688.0 25.0&quot;
$ns_ at 1.25 &quot;$n16 setdest 842.0 623.0 25.0&quot;
$ns_ at 1.25 &quot;$n17 setdest 678.0 548.0 25.0&quot;
$ns_ at 0.75 &quot;$n18 setdest 741.0 809.0 20.0&quot;
$ns_ at 0.75 &quot;$n19 setdest 437.0 799.0 20.0&quot;
$ns_ at 0.20 &quot;$n20 setdest 159.0 722.0 20.0&quot;
$ns_ at 1.25 &quot;$n21 setdest 700.0 350.0 20.0&quot;
$ns_ at 0.75 &quot;$n22 setdest 839.0 444.0 20.0&quot;
## Setting The Node Size
$ns_ initial_node_pos $Server1 75
$ns_ initial_node_pos $Server2 75
$ns_ initial_node_pos $n2 40
$ns_ initial_node_pos $n3 40
$ns_ initial_node_pos $n4 40
$ns_ initial_node_pos $n5 40
$ns_ initial_node_pos $n6 40
$ns_ initial_node_pos $n7 40
$ns_ initial_node_pos $n8 40
$ns_ initial_node_pos $n9 40
$ns_ initial_node_pos $n10 40
$ns_ initial_node_pos $n11 40
$ns_ initial_node_pos $n12 40

100
$ns_ initial_node_pos $n13 40
$ns_ initial_node_pos $n14 40
$ns_ initial_node_pos $n15 40
$ns_ initial_node_pos $n16 40
$ns_ initial_node_pos $n17 40
$ns_ initial_node_pos $n18 40
$ns_ initial_node_pos $n19 40
$ns_ initial_node_pos $n20 40
$ns_ initial_node_pos $n21 40
$ns_ initial_node_pos $n22 40
#### Setting The Labels For Nodes
$ns_ at 0.0 &quot;$Server1 label Server1&quot;
$ns_ at 0.0 &quot;$Server2 label Server2&quot;
#Setting Color For Server
$Server1 color maroon
$ns_ at 0.0 &quot;$Server1 color maroon&quot;
$Server2 color maroon
$ns_ at 0.0 &quot;$Server2 color maroon&quot;
## SETTING ANIMATION RATE
$ns_ at 0.0 &quot;$ns_ set-animation-rate 15.0ms&quot;
# COLORING THE NODES
$n9 color blue
$ns_ at 4.71 &quot;$n9 color blue&quot;
$n5 color blue
$ns_ at 7.0 &quot;$n5 color blue&quot;
$n2 color blue
$ns_ at 7.29 &quot;$n2 color blue&quot;
$n16 color blue
$ns_ at 7.59 &quot;$n16 color blue&quot;
$n9 color maroon
$ns_ at 7.44 &quot;$n9 color maroon&quot;
$ns_ at 7.43 &quot;$n9 label TTLover&quot;
$ns_ at 7.55 &quot;$n9 label \&quot;\&quot;&quot;
$n12 color blue
$ns_ at 7.85 &quot;$n12 color blue&quot;
#### Establishing Communication

100

set udp0 [$ns_ create-connection UDP $Server1 LossMonitor $n18 0]


$udp0 set fid_ 1
set cbr0 [$udp0 attach-app Traffic/CBR]
$cbr0 set packetSize_ 1000
$cbr0 set interval_ .07
$ns_ at 0.0 &quot;$cbr0 start&quot;
$ns_ at 4.0 &quot;$cbr0 stop&quot;
set udp1 [$ns_ create-connection UDP $Server1 LossMonitor $n22 0]
$udp1 set fid_ 1
set cbr1 [$udp1 attach-app Traffic/CBR]
$cbr1 set packetSize_ 1000
$cbr1 set interval_ .07
$ns_ at 0.1 &quot;$cbr1 start&quot;
$ns_ at 4.1 &quot;$cbr1 stop&quot;

set udp2 [$ns_ create-connection UDP $n21 LossMonitor $n20 0]


$udp2 set fid_ 1
set cbr2 [$udp2 attach-app Traffic/CBR]
$cbr2 set packetSize_ 1000
$cbr2 set interval_ .07
$ns_ at 2.4 &quot;$cbr2 start&quot;
$ns_ at 4.1 &quot;$cbr2 stop&quot;
set udp3 [$ns_ create-connection UDP $Server1 LossMonitor $n15 0]
$udp3 set fid_ 1
set cbr3 [$udp3 attach-app Traffic/CBR]
$cbr3 set packetSize_ 1000
$cbr3 set interval_ 5
$ns_ at 4.0 &quot;$cbr3 start&quot;
$ns_ at 4.1 &quot;$cbr3 stop&quot;
set udp4 [$ns_ create-connection UDP $Server1 LossMonitor $n14 0]
$udp4 set fid_ 1
set cbr4 [$udp4 attach-app Traffic/CBR]
$cbr4 set packetSize_ 1000
$cbr4 set interval_ 5
$ns_ at 4.0 &quot;$cbr4 start&quot;
$ns_ at 4.1 &quot;$cbr4 stop&quot;
set udp5 [$ns_ create-connection UDP $n15 LossMonitor $n16 0]
$udp5 set fid_ 1
set cbr5 [$udp5 attach-app Traffic/CBR]
$cbr5 set packetSize_ 1000
$cbr5 set interval_ 5
$ns_ at 4.0 &quot;$cbr5 start&quot;

100

$ns_ at 4.1 &quot;$cbr5 stop&quot;


set udp6 [$ns_ create-connection UDP $n15 LossMonitor $n17 0]
$udp6 set fid_ 1
set cbr6 [$udp6 attach-app Traffic/CBR]
$cbr6 set packetSize_ 1000
$cbr6 set interval_ 5
$ns_ at 4.0 &quot;$cbr6 start&quot;
$ns_ at 4.1 &quot;$cbr6 stop&quot;
set udp7 [$ns_ create-connection UDP $n14 LossMonitor $n4 0]
$udp7 set fid_ 1
set cbr7 [$udp7 attach-app Traffic/CBR]
$cbr7 set packetSize_ 1000
$cbr7 set interval_ 5
$ns_ at 4.0 &quot;$cbr7 start&quot;
$ns_ at 4.1 &quot;$cbr7 stop&quot;
set udp8 [$ns_ create-connection UDP $n14 LossMonitor $n9 0]
$udp8 set fid_ 1
set cbr8 [$udp8 attach-app Traffic/CBR]
$cbr8 set packetSize_ 1000
$cbr8 set interval_ 5
$ns_ at 4.0 &quot;$cbr8 start&quot;
$ns_ at 4.1 &quot;$cbr8 stop&quot;
set udp9 [$ns_ create-connection UDP $n4 LossMonitor $n3 0]
$udp9 set fid_ 1
set cbr9 [$udp9 attach-app Traffic/CBR]
$cbr9 set packetSize_ 1000
$cbr9 set interval_ 5
$ns_ at 4.0 &quot;$cbr9 start&quot;
$ns_ at 4.1 &quot;$cbr9 stop&quot;
set udp10 [$ns_ create-connection UDP $n4 LossMonitor $n2 0]
$udp10 set fid_ 1
set cbr10 [$udp10 attach-app Traffic/CBR]
$cbr10 set packetSize_ 1000
$cbr10 set interval_ 5
$ns_ at 4.0 &quot;$cbr10 start&quot;
$ns_ at 4.1 &quot;$cbr10 stop&quot;
set udp11 [$ns_ create-connection UDP $n9 LossMonitor $n16 0]
$udp11 set fid_ 1
set cbr11 [$udp11 attach-app Traffic/CBR]
$cbr11 set packetSize_ 1000
$cbr11 set interval_ 5

100

$ns_ at 4.0 &quot;$cbr11 start&quot;


$ns_ at 4.1 &quot;$cbr11 stop&quot;
set udp12 [$ns_ create-connection UDP $n9 LossMonitor $n10 0]
$udp12 set fid_ 1
set cbr12 [$udp12 attach-app Traffic/CBR]
$cbr12 set packetSize_ 1000
$cbr12 set interval_ 5
$ns_ at 4.0 &quot;$cbr12 start&quot;
$ns_ at 4.1 &quot;$cbr12 stop&quot;
#ANNOTATIONS DETAILS
$ns_ at 0.0 &quot;$ns_ trace-annotate \&quot;MOBILE NODE MOVEMENTS\&quot;&quot;
$ns_ at 4.1 &quot;$ns_ trace-annotate \&quot;NODE27 CACHE THE DATA FRO
SERVER\&quot;&quot;
#$ns_ at 4.59 &quot;$ns_ trace-annotate \&quot;PACKET LOSS AT NODE27\&quot;&quot;
$ns_ at 4.71 &quot;$ns_ trace-annotate \&quot;NODE10 CACHE THE DATA\&quot;&quot;
### PROCEDURE TO STOP
proc stop {} {
global ns_ tracefd
$ns_ flush-trace
close $tracefd
exec nam datacache.nam &amp;
exit 0
}
puts &quot;Starting Simulation &quot;
$ns_ at 25.0 &quot;stop&quot;
$ns_ run

You might also like