V SEMESTER 2022 SCHEME COMPUTER NETWORKS LABORATORY                                  BCS502
1. Implement three nodes point – to – point network with duplex links between them. Set
     the queue size, vary the bandwidth, and find the number of packets dropped.
  2.   Implement transmission of ping messages/trace route over a network topology
       consisting of 6 nodes and find the number of packets dropped due to congestion.
  3.   Implement an Ethernet LAN using n nodes and set multiple traffic nodes and plot
       congestion windowfor different source / destination.
  4.   4 Develop a program for error detecting code using CRC-CCITT (16- bits).
  5.   Develop a program to implement a sliding window protocol in the data link layer.
  6.   Develop a program to find the shortest path between vertices using the Bellman-Ford and
       path vector routing algorithm.
  7.   Using TCP/IP sockets, write a client – server program to make the client send the file
       name and to make the server send back the contents of the requested file if present.
  8.   Develop a program on a datagram socket for client/server to display the
       messages on client side, typed at the server side.
  9.   Develop a program for a simple RSA algorithm to encrypt and decrypt the data.
  10. Develop a program for congestion control using a leaky bucket algorithm
COURSE OUTCOMES
   •    Explain the fundamentals of computer networks.
   •    Apply the concepts of computer networks to demonstrate the working of various
        layers and protocols in communication network.
   •    Analyze the principles of protocol layering in modern communication systems.
   •    Demonstrate various Routing protocols and their services using tools such as Cisco
        packet tracer.
1 Implement three nodes point – to – point network with duplex links between them. Set
the queue size, vary the bandwidth, and find the number of packets dropped.
1. Network Scenario
Overview The
scenario consists of:
 Four nodes: n0, n1, n2, n3
Duplex links connecting
these nodes TCP agents
connected to the nodes TCP
sinks at n3 to receive data
FTP applications running over the TCP
connections Simulation parameters for
duration and trace files
 2. Tcl Script (e1.tcl)
The Tcl script will set up the simulation, configure the nodes, links, agents, and applications,
and specify the behavior of the FTP application. Below is the corrected and structured Tcl
script based on your requirements.
 # e1.tcl
 set ns [new Simulator]
# Create
nodes set n0
[$ns node]
set n1 [$ns
node] set n2
[$ns node]
set n3 [$ns
node]
 # Create duplex links with modified queue sizes
 $ns duplex-link $n0 $n2 1Mb 10ms Queue/DropTail
 $ns duplex-link $n1 $n2 1Mb 10ms Queue/DropTail
 $ns duplex-link $n2 $n3 1Mb 10ms Queue/DropTail
 # Set queue size (in packets) - changed from 50 to 20
 $ns queue-limit $n0 20
 $ns queue-limit $n1 20
 $ns queue-limit $n2 20
 # Create TCP agents
set tcp0 [new
Agent/TCP] set tcp1
[new Agent/TCP]
 # Attach TCP agents to the nodes
 $ns attach-agent $n0 $tcp0
 $ns attach-agent $n1 $tcp1
 # Create TCP sinks
set sink2 [new
Agent/TCPSink] set
sink3 [new
Agent/TCPSink]
 # Attach sinks to node n3
 $ns attach-agent $n3 $sink2
 $ns attach-agent $n3 $sink3
 # Connect TCP agents to sinks
 $ns connect $tcp0 $sink2
 $ns connect $tcp1 $sink3
 # Setup FTP application
set ftp0 [new
Application/FTP] set
ftp1 [new
Application/FTP]
 # Attach FTP to TCP agents
 $ftp0 attach-agent $tcp0
 $ftp1 attach-agent $tcp1
 # Start and stop FTP applications
 $ns at 1.0 "$ftp0 start"
 $ns at 8.0 "$ftp0 stop"
 $ns at 1.0 "$ftp1 start"
 $ns at 8.0 "$ftp1 stop"
# Define trace
files set
trace_file "x1.tr"
  set name_file "x1.nam"
  $ns trace-all $trace_file
  $ns namtrace-all $name_file
 # Run simulation for 10 seconds
 $ns run
 AWK Script (e1.awk)
 The AWK script will process the trace file to count packets received at nodes n2 and n3. Here's
 the corrected
 AWK script:
# e1.awk
BEGIN {
   tcppack = 0; # Initialize packet
     counter for node 3 tcppack1 = 0; #
     Initialize packet counter for node 2
 }
 {
     # Count received packets at node 3
     if ($1 == "r" && $4 == "3" && $5 == "tcp" && $6 ==
        "1540") { tcppack++;
     }
     # Count received packets at node 2
     if ($1 == "d" && $3 == "2" && $5 == "tcp" && $6 ==
        "1540") { tcppack1++;
     }
 }
 END {
   printf("\nTotal number of packets received at node
   3: %d\n", tcppack); printf("Total number of packets
   received at node 2: %d\n", tcppack1);
 }
 Instructions for Running the Simulation Create Directory Structure:
 mkdir -p cn_lab/expt1
 Save the Tcl Script: Save the above Tcl code in a file named e1.tcl inside cn_lab/expt1.
Save the AWK Script: Save the AWK script in a file named e1.awk
inside the same directory. Run the Simulation: Open a terminal and
navigate to the directory:
 cd
 cn_lab/expt
 1 ns e1.tcl
 Snapshot
Process the Trace File: After running the simulation,
process the trace file: awk -f e1.awk x1.tr
Output
total number of packets received
at node3:3840 total number of
packets received at node2:0
2 Implement transmission of ping messages/trace route over a network topology
consisting of 6 nodes and find the number of packets dropped due to congestion.
# Simulation parameters setup
#===================================
set val(stop) 10.0    ;# time of simulation end
  #===================================
  # Initialization
  #===================================
#Create a ns
simulator set ns
[new Simulator]
#Open the NS trace
file set tracefile
[open x1.tr w]
  $ns trace-all $tracefile
#Open the NAM
trace file set namfile
[open x1.nam w]
  $ns namtrace-all $namfile
  #===================================
  # Nodes Definition#===================================
#Create 6 nodes set
n0 [$ns node] set n1
[$ns node] set n2
[$ns node] set n3
[$ns node] set n4
[$ns node] set n5
[$ns node]
  #==================================
  # Links Definition
 #===================================
 #Createlinks between nodes
 $ns duplex-link $n0 $n3 100.0Mb 10ms DropTail
 $ns queue-limit $n0 $n3 50
 $ns duplex-link $n1 $n3 100.0Mb 10ms DropTail
 $ns queue-limit $n1 $n3 50
 $ns duplex-link $n2 $n3 100.0Mb 10ms DropTail
 $ns queue-limit $n2 $n3 50
 $ns duplex-link $n4 $n3 100.0Mb 10ms DropTail
 $ns queue-limit $n4 $n3 2
 $ns duplex-link $n3 $n5 100.0Mb 10ms DropTail
 $ns queue-limit $n3 $n5 2
 #Give node position (for NAM)
 $ns duplex-link-op $n0 $n3 orient right-down
 $ns duplex-link-op $n1 $n3 orient right
 $ns duplex-link-op $n2 $n3 orient right-up
 $ns duplex-link-op $n4 $n3 orient left-down
 $ns duplex-link-op $n3 $n5 orient right-down
 #===================================
 # Agents Definition
 #===================================
#Setup a TCP connection
set p0 [new Agent/Ping]
$ns attach-agent $n0 $p0
set p2 [new
Agent/Ping]$ns attach-
agent $n4 $p2
$ns connect $p0 $p2
$p0 set packetSize_ 1500
#Setup a TCP connection
set p1 [new Agent/Ping]
$ns attach-agent $n1 $p1
set p3 [new Agent/Ping]
 $ns attach-agent $n5 $p3
 $ns connect $p1 $p3
 $p1 set packetSize_ 1500
 Agent/Ping instproc recv {from rtt} {
   $self instvar node_
   puts "node [$node_ id] received response from $from with RTT=$rtt ns"
 }
 #===================================
 # Applications Definition
 #===================================
 for {set i 0} {$i < 4} {incr i} {
   $ns at [expr 0.5 * $i] "$p0 send"
   $ns at [expr 0.5 * $i] "$p1 send"
 }
 #===================================
 # Termination
 #===================================
#Define a 'finish' procedure
proc finish {} {
   global ns tracefile namfile
  $ns flush-trace
  close $tracefile
  close $namfile
  exec nam x1.nam &
  exit 0
 }
 $ns at $val(stop) "$ns nam-end-wireless $val(stop)"
 $ns at $val(stop) "finish"
 $ns at $val(stop) "puts \"done\" ; $ns halt"
 # Run simulation for 10 seconds
 $ns run
 AWK Script (e1.awk)
Type the program and save it as
p2.awk BEGIN{
  drop=0;
  }
  {
  if($1=="d")
  {
  drop++;
  }
}
END{
  printf("Total no of %s packets dropped due to congestion = %d\n", $5,drop);
  }
Process the Trace File: After running the simulation,
process the trace file: awk -f e2.awk x1.tr
Output
Total no of ping packets dropped due to congestion = 0
3 Implement an Ethernet LAN using n nodes and set multiple traffic nodes and
plot congestion window for different source / destination.
#===================================
# Simulation parameters setup
#===================================
set val(stop) 10.0 ;# time of simulation end
#===================================
#     Initialization
#===================================
# Create a ns simulator
set ns [new Simulator]
# Open the NS trace fileImplement an Ethernet LAN using n nodes and set multiple traffic
nodes and plot congestion window for different source / destination.
set tracefile [open "x1.tr" w]
$ns trace-all $tracefile
# Open the NAM trace file
set namfile [open "x1.nam" w]
$ns namtrace-all $namfile
#===================================
#     Nodes Definition
#===================================
# Create 4 nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
#===================================
#     Links Definition
#===================================
# Create links between nodes (e.g., 10ms delay, 1Mb bandwidth)
$ns make-lan "$n0 $n1 $n2 $n3" 10mb 40ms LL Queue/DropTail Mac/802_3
#===================================
#     Agents Definition
#===================================
# Setup a TCP connection between n0 and n3
set tcp0 [new Agent/TCP]
$ns attach-agent $n0 $tcp0
set sink3 [new Agent/TCPSink]
$ns attach-agent $n3 $sink3
$ns connect $tcp0 $sink3
$tcp0 set packetSize_ 15000
# Setup a TCP connection between n2 and n1
set tcp1 [new Agent/TCP]
$ns attach-agent $n2 $tcp1
set sink2 [new Agent/TCPSink]
$ns attach-agent $n1 $sink2
$ns connect $tcp1 $sink2Implement an Ethernet LAN using n nodes and set multiple traffic
nodes and plot congestion window for different source / destination.
$tcp1 set packetSize_ 15000
#===================================
#     Applications Definition
#===================================
# Setup a FTP Application over the TCP connection n0<->n3
set ftp0 [new Application/FTP]
$ftp0 attach-agent $tcp0
$ns at 1.0 "$ftp0 start"
$ns at 2.0 "$ftp0 stop"
$ns at 2.5 "$ftp0 start"
$ns at 5.0 "$ftp0 stop"
# Setup a FTP Application over the TCP connection n2<->n1
set ftp1 [new Application/FTP]
$ftp1 attach-agent $tcp1
$ns at 1.0 "$ftp1 start"
$ns at 2.0 "$ftp1 stop"
$ns at 3.0 "$ftp1 start"
$ns at 6.0 "$ftp1 stop"
#===================================
#     Tracing cwnd
#===================================
# Open files for tracing cwnd
set f1 [open "f1.tr" w]
$tcp0 attach $f1 ;# Corrected from 'attch' to 'attach'
$tcp0 trace cwnd_
set f2 [open "f2.tr" w]
$tcp1 attach $f2 ;# Corrected from 'attch' to 'attach'
$tcp1 trace cwnd_
#===================================
#     Termination
#===================================
# Define a 'finish' procedure
proc finish {} {
  global ns tracefile namfile f1 f2
  $ns flush-trace
  close $tracefile
  close $namfile
  close $f1
  close $f2
  exec nam x1.nam & ;# Visualize the simulation in NAM
  exit 0
}
# Schedule the finish procedure
$ns at $val(stop) "finish"
$ns at $val(stop) "puts \"done\" ; $ns halt"
$ns run
Run the program using
$ns exp3.tcl
 AWK SCRIPT ( exp3.awk)
 BEGIN{
 }
 {
 if($6=="cwnd_")
 printf("%f %f\n",$1,$7);
 }
 END{
 }
Process the Trace File: After running the simulation,
process the trace file:
  awk -f exp3.awk f1.tr>a1
 awk -f exp3.awk f2.tr>a2
 xgraph a1 a2
 4. Develop a program for error detecting code using CRC-CCITT (16- bits).
 Program
 public class CRC16CCITT {
  private static final int POLY = 0x1021;
     public static int calculateCRC(byte[] data) {
         int crc = 0xFFFF;
        for (byte b : data) {
           crc ^= (b << 8);
          for (int i = 0; i < 8; i++) {
            if ((crc & 0x8000) != 0) {
              crc = (crc << 1) ^ POLY;
            } else {
                crc = crc << 1;
            }
          }
       }
       return crc & 0xFFFF;
     }
     public static void main(String[] args) {
       byte[] data = "123456789".getBytes();
       System.out.printf("CRC-CCITT (16-bit): 0x%04X%n", calculateCRC(data));
     }
 }
 Output
 CRC-CCITT (16-bit): 0x29B1
 5. Develop a program to implement a sliding window protocol in the data link layer.
 Program
import java.util.Scanner;
public class SlidingWindowProtocol {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter window size: ");
    int windowSize = scanner.nextInt();
    System.out.print("Enter total frames: ");
    int totalFrames = scanner.nextInt();
    scanner.close();
    int ack = 0;
    while (ack < totalFrames) {
      for (int i = 0; i < windowSize && ack + i < totalFrames; i++) {
         System.out.println("Sending frame " + (ack + i));
      }
      System.out.println("Acknowledgment received for frame " + ack);
      ack++;
    }
    System.out.println("All frames sent and acknowledged.");
  }
}
Output
Enter window size: 3
Enter total frames: 5
Sending frame 0
Sending frame 1
Sending frame 2
Acknowledgment received for frame 0
Sending frame 1
Sending frame 2
Sending frame 3
Acknowledgment received for frame 1
Sending frame 2
Sending frame 3
Sending frame 4
Acknowledgment received for frame 2
Sending frame 3
Sending frame 4
Acknowledgment received for frame 3
Sending frame 4
Acknowledgment received for frame 4
All frames sent and acknowledged.
6. Develop a program to find the shortest path between vertices using the Bellman-Ford
  and path vector routing algorithm.
Program
import java.util.Arrays;
public class BellmanFord {
 static void bellmanFord(int V, int[][] edges, int src) {
   int[] dist = new int[V];
   Arrays.fill(dist, Integer.MAX_VALUE);
   dist[src] = 0;
   for (int i = 0; i < V - 1; i++) {
     for (int[] edge : edges) {
       if (dist[edge[0]] != Integer.MAX_VALUE && dist[edge[0]] + edge[2] <
         dist[edge[1]]) { dist[edge[1]] = dist[edge[0]] + edge[2];
       }
     }
   }
   for (int[] edge : edges) {
     if (dist[edge[0]] != Integer.MAX_VALUE && dist[edge[0]] + edge[2] <
       dist[edge[1]]) { System.out.println("Negative weight cycle
       detected");
       return;
     }
   }
         for (int i = 0; i < V; i++) System.out.println("Vertex " + i + ": " + dist[i]);
     }
         public static void main(String[]
                         args) {
         int[][] edges = {
            {0, 1, -1}, {0, 2, 4}, {1, 2, 3}, {1, 3, 2}, {1, 4, 2},
            {3, 2, 5}, {3, 1, 1}, {4, 3, -3}
         };
         bellmanFord(5, edges, 0);
     }
 }
Output Vertex
0: 0
 Vertex 1: -1
 Vertex 2: 2
 Vertex 3: -2
 Vertex 4: 1
 7.Using TCP/IP sockets, write a client – server program to make the client send the file
 name and to make the server send back the contents of the requested file if present.
Program
import java.io.*;
import
java.net.*;
 public class Server1 {
  public static void main(String[] args) throws IOException {
    try (ServerSocket serverSocket = new
      ServerSocket(8080)) {
      System.out.println("Server is listening on
      port 8080..."); Socket socket =
      serverSocket.accept();
            try (BufferedReader in = new BufferedReader(new
              InputStreamReader(socket.getInputStream())); PrintWriter out = new
              PrintWriter(socket.getOutputStream(), true);
              BufferedOutputStream fileOut = new BufferedOutputStream(new
              FileOutputStream("received_file.txt"))) {
              // Read the file name from
              client String fileName =
              in.readLine();
              out.println("Saving file: " +
              fileName);
              // Read the file content from the client and save it to
              server's file system String line;
              while ((line = in.readLine()) != null) {
                fileOut.write(line.getBytes());
                fileOut.write(System.lineSeparator().getBytes
                ()); // Add newline
              }
               out.println("File " + fileName + " saved
               successfully."); System.out.println("File
               received and saved as 'received_file.txt'.");
             } catch (IOException e) {
               System.err.println("Error while receiving file: " + e.getMessage());
             }
         }
     }
 }
import java.io.*;
import
java.net.*;
 public class Client1 {
  public static void main(String[] args)
    throws IOException { try (Socket socket
    = new Socket("localhost", 8080);
       BufferedReader consoleReader = new BufferedReader(new
       InputStreamReader(System.in)); PrintWriter out = new
       PrintWriter(socket.getOutputStream(), true);
       BufferedReader in = new BufferedReader(new
       InputStreamReader(socket.getInputStream()))) {
             // Read file name from the console
             System.out.print("Enter the file name
             to send: "); String fileName =
             consoleReader.readLine();
             out.println(fileName);
             // Open the file and send its contents
             to the server File file = new
             File(fileName);
             if (file.exists()) {
                try (BufferedReader fileReader = new BufferedReader(new
                  FileReader(file))) { String line;
                  while ((line = fileReader.readLine()) !=
                    null) { out.println(line);
                  }
                }
               // Get server's response after sending file
               System.out.println("Server: " + in.readLine());
             } else {
               System.out.println("File not found.");
             }
         }
     }
     }
 Output
Create any file
(example.txt) first run
the server program
Server is listening on
port 8080...
then run the client
program Server is
listening on port 8080...
  File received and saved as 'received_file.txt'.
 8 Develop a program on a datagram socket for client/server to display the messages on
 client side, typed at the server side.
 Program
import
java.net.*; import
java.io.*;
 public class Server {
  public static void main(String[]
    args) { DatagramSocket socket =
    null; BufferedReader reader =
    null;
    try {
      socket = new DatagramSocket(9876); // Server
      listens on port 9876 reader = new
      BufferedReader(new
      InputStreamReader(System.in));
      InetAddress clientAddress = InetAddress.getByName("localhost"); // Client running on
      localhost
      while (true) {
       System.out.print("Enter message to send to client: ");
       String message = reader.readLine(); // Read
       message from server console if
       (message.equalsIgnoreCase("exit")) {
         System.out.println("Server
         exiting..."); break;
       }
           byte[] sendData = message.getBytes();
           DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
    port clientAddress, 9877); // Send to client at
   9877
           socket.send(sendPacket); // Send
           packet to client
       } System.out.println("Message sent
           to client.");
     } catch (IOException
       e) {
       e.printStackTrace(
       );
     } finally {
        if (socket != null &&
           !socket.isClosed()) {
           socket.close();
       }
       try {
           if (reader !=
                null) {
                reader.close();
               }
             } catch (IOException e) {
               e.printStackTrace();
             }
         }
     }
 }
import
java.io.IOException;
import java.net.*;
 public class Client {
  public static void main(String[]
    args) { DatagramSocket socket =
    null;
    try {
      socket = new DatagramSocket(9877); // Client
      listens on port 9877 byte[] receiveData = new
      byte[1024]; // Buffer to store received data
             while (true) {
              DatagramPacket receivePacket = new DatagramPacket(receiveData,
              receiveData.length); socket.receive(receivePacket); // Receive packet from
              serverString message = new String(receivePacket.getData(), 0,
              receivePacket.getLength()); System.out.println("Message from server: " +
              message);
              if (message.equalsIgnoreCase("exit")) {
                 System.out.println("Client exiting...");
                 break;
              }
           }
         } catch (IOException e) {
           e.printStackTrace();
         } finally {
            if (socket != null &&
               !socket.isClosed()) {
               socket.close();
           }
         }
     }
 }
 Output
Enter message to send to client: hello how
are you Message from server: hello how
are you
 9 Develop a program for a simple RSA algorithm to encrypt and decrypt the data.
 Program
 import java.math.BigInteger;
 import java.util.Scanner;
 public class SimpleRsa {
  public static void main(String[] args) {
   Scanner scanner = new
   Scanner(System.in);
    // Public and private keys
    BigInteger      p      =      new
    BigInteger("61"); BigInteger q =
    new             BigInteger("53");
    BigInteger n = p.multiply(q);
    BigInteger phi =
    p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
    BigInteger e = new BigInteger("17");
    BigInteger d = e.modInverse(phi);
    // Input message
    System.out.print("Enter a message to encrypt
    (number): "); BigInteger message = new
    BigInteger(scanner.nextLine());
    // Encryption: c = m^e mod n
    BigInteger encrypted = message.modPow(e, n);
    System.out.println("Encrypted message: " +
    encrypted);
    // Decryption: m = c^d mod n
    BigInteger decrypted = encrypted.modPow(d, n);
    System.out.println("Decrypted message: " +
    decrypted);
    scanner.close();
   }
 }
 Output
Enter a message to encrypt (number): 42
Encrypted message: 2557
 Decrypted message: 42
 10. Develop a program for congestion control using a leaky bucket algorithm
Program
 import java.util.Scanner;
 public class LeakyBucket {
  public static void main(String[] args) {
   int bucketSize = 10, outputRate = 4, stored = 0;
    Scanner scanner = new Scanner(System.in); System.out.print("Enter the number of packets
         arriving: "); int n = scanner.nextInt();
         int[] packets = new int[n];
         System.out.println("Enter the size of each packet:");
         for (int i = 0; i < n; i++) {
           packets[i] =
           scanner.nextInt();
         }
         for (int packet : packets) {
           if (packet <= (bucketSize - stored)) {
             stored += packet;
           } else {
             System.out.println("Packet of size " + packet + " is dropped.");
           }
           System.out.println("Bucket stores " + stored + "
           units."); stored = Math.max(0, stored -
           outputRate);
         }
         scanner.close();
     }
 }
Output
Enter the number of packets arriving:
5 Enter the size of each packet:
 3
 6
 2
 8
 5
Bucket stores 3 units.
Bucket stores 6 units.
Bucket stores 4 units.
Bucket stores 8 units.
Bucket stores 9 units.