CN LAB programs
CN LAB programs
CN LAB programs
Network simulators implemented in software are valuable tools for researchers to develop, test,
and diagnose network protocols. Simulation is economical because it can carry out experiments
without the actual hardware. It is flexible because it can, for example, simulate a link with any
bandwidth and propagation delay. Simulation results are easier to analyze than experimental
results because important information at critical points can be easily logged to help researchers
diagnose network protocols.
Network simulators, however, have their limitations. A complete network simulator needs to
simulate networking devices (e.g., hosts and routers) and application programs that generate
network traffic. It also needs to provide network utility programs to configure, monitor, and
gather statistics about a simulated network. Therefore, developing a complete network simulator
is a large effort. Due to limited development resources, traditional network simulators usually
have the following drawbacks:
• Simulation results are not as convincing as those produced by real hardware and software
equipment. In order to constrain their complexity and development cost, most network simulators
usually can only simulate real-life network protocol implementations with limited details, and this
may lead to incorrect results.
• These simulators are not extensible in the sense that they lack the standard UNIX POSIX
application programming interface (API). As such, existing or to-be-developed real-life
application programs cannot run normally to generate traffic for a simulated network.
Instead, they must be rewritten to use the internal API provided by the simulator (if there is any)
and be compiled with the simulator to form a single, big, and complex program.
To overcome these problems, Wang invented a kernel re-entering simulation methodology and
used it to implement the Harvard network simulator. Later on, Wang further improved the
methodology and used it to design and implement the NCTUns network simulator and emulator.
Different types of simulators
Some of the different types of simulators are as follows:-
MIT's NETSIM
NIST
CPSIM
INSANE
NEST
REAL
NS
OPNET
NCTUns
P
GNS3
WireShark
1. Implement three nodes point – to – point network with duplex links between them
for different topologies. 1 Set the queue size, vary the bandwidth and find the
number of packets dropped for various iterations.
Source Code :
pa1.tcl
set ns [new Simulator]
set nf [open pa1.nam w]
$ns namtrace-all $nf
set tf [open pa1.tr w]
$ns trace-all $tf
proc finish {} {
global ns nf tf
$ns flush-trace
close $nf
close $tf
exec nam pa1.nam &
exit 0
}
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
Source Code:
pa1.awk
BEGIN {
c=0;
}
{
if ($1=="d")
{
c++;
printf("%s\t%s\n",$5,$11);
}
}
END {
printf("The number of packet dropped= %d\n",c);
}
Output:
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 in
the network.
Source Code
pa4.tcl
set ns [ new Simulator ]
set nf [ open pa2.nam w ]
proc finish { } {
global ns nf tf
$ns flush-trace
close $nf
close $tf
exec nam pa2.nam &
exit 0
}
Source Code :
pa4.awk
BEGIN{
drop=0;
}
{
if($1=="d")
{
drop++;
}
}
END{
printf("Total number of %s packets dropped due to congestion=%d\n",$5,drop);
}
Output
3. Implement an Ethernet LAN using n nodes and set multiple traffic nodes and plot
congestion window for different source / destination.
Source Code:
pa6.tcl
$ns make-lan "$n0 $n1 $n2 $n3 $n4" 100Mb 100ms LL Queue/DropTail Mac/802_3
$ns duplex-link $n4 $n5 1Mb 1ms DropTail
proc finish { } {
global ns nf tf
$ns flush-trace
close $tf
close $nf
exec nam pa3.nam &
exit 0
}
Source Code:
pa6.awk
BEGIN {
}
{
if($6=="cwnd_")
printf("%f\t%f\t\n",$1,$7);
}
END{
}
Output:
4. Write a program for error detecting code using CRC-CCITT (16- bits).
Cyclic Redundancy Check Code for Error – Detection
The cyclic Redundancy Check (CRC) id a technique for detecting errors in data transmission,
but not for correcting errors when they are detected.
CCITT- Consultative Committee for International Telegraphy and Telephone.
Algorithm:
A) For Computing CRC:
The CRC Algorithm is based on polynomial arithmetic.
Let the message that we have to send has k bits (denoted by M(x) in polynomial form
having degree (k-1)) the sender and the receiver are agreed upon a generator polynomial
having r bits (denoted by G(x) in polynomial form having degree (r-1)). The generator
polynomial is also called “Divisor”.
Now, append (r-1) zero bits to the LSB side of the message M(x) so it will now contain
(k+r- 1) bits and corresponds to the polynomial x(r-1) M (x).
Divide the polynomial x(r-1) M (x) by Divisor, using modulo-2 subtraction (bit by bit XOR
operation). Add the remainder R(x) (called frame check sequence) to x (r-1) M (x), using
modulo -2 additions (bit by bit XOR operation). This is the message that will be
transmitted by the transmitter denoted by T(x).
B) For Error Detection:
Suppose that a transmission error occurs, so that the received message at the receiver is
T(x) +E(x), instead of T(x). Each 1 bit in E(x) corresponds to a bit that has been inverted.
The received message at the receiver end is divided by G(x), i.e. [T(x) + E(x) / G(x) ].
Since T(x)/G(x) is 0, so the result is simply E(x)/G(x).
If E(x)/G(x) =0 than there is no error in the received message, otherwise there is an error.
The following type of errors can be detected using CRC:
If G(x) has more than one bit and the coefficient of x0 is 1, then all single bit errors are
detected.
If G(x) is not divisible by x ( the coefficient of x0 is 1) , and t is the least positive
integer (0<t<n-1) such that G(x) divides x1 + 1, then all isolated double errors are
detected.
If G(x) has a factor (x+1), then all odd numbered errors are detected.
Source code:
import java.io.*;
class crc
{
public static void main(String[] args)
{
InputStreamReader isr=new InputStreamReader (System.in);
BufferedReader br=new BufferedReader(isr);
int[] message;
int[] gen;
int[] app_message;
int[] rem;
int[] trans_message;
int message_bits,gen_bits,total_bits;
System.out.println("\n Enter the no of bits in the message");
message_bits=Integer.parseInt(br.readLine());
message=new int[message_bits];
System.out.println("\n Enter the message bits");
for(int i=o;i<message_bits;i++)
message[i]=Integer.parseInt(br.readLine());
System.out.println("\n Enter the no of bits generated ");
gen_bits=Integer.parseInt(br.readLine());
gen=new int[gen_bits];
System.out.println("\n Enter the generated bits");
for(int i=o;i<gen_bits;i++);
{
gen[i]=Integer.parseInt(br.readLine());
}
total_bits=message_bits+gen_bits-1;
app_message=new int[total_bits];
rem=new int[total_bits];
trans_message=new int[total_bits];
for(int i=0;i<message.length;i++)
{
app_message[i]=message[i];
}
System.out.print("\n Message bits :");
for(int i=o;i<message_bits;i++)
{
System.out.print(message[i]);
}
System.out.print("\n Generated bits :");
for(int i=0;i<gen_bits;i++)
{
System.out.print(gen[i]);
}
System.out.print("\n Appended message :");
for(int i=0;i<app_message.length;i++)
{
System.out.print(app_message[i]);
}
for(int j=0;j<app_message.length;j++)
{
rem[j]=app_message[j];
}
rem=computecrc(app_message.length;i++)
for(int i=0;i<app_message.length;i++)
{
trans_mesage[i]=(app_message[i]^rem[i]);
}
System.out.println("\n Transmitted message from the transmitter :");
for(int i=0;i<trans_message.length;i++)
{
System.out.print(trans_message[i]);
}
System.out.println("\n Message of"+total_bits+"bits received");
for(int i=0;i<trans_message.length;i++)
{
trans_messge[i]=Inter.parseInt(br.readLine());
}
System.out.println("\n Recevied message is :");
for(int i=0;i<trans_message.length;i++)
{
System.out.print(trans_message[i]);
}
for(int j=0;j<trans_message.length;j++)
{
rem[j]=trans_message[j];
}
rem=computercrc(trans_message,gen,rem);
for (int i=0;i<rem.length;i++)
{
if(rem[i]!=0)
{
System.out.println("\n There is error");
break;
}
if(i==rem.length-1)
{
System.out.println("\n There is no error");
}
}
static int[] computecrc(int app_message[],int gen[],int rem[])
{
int current=0;
while(true)
{
for(int i=0;i<gen.length;i++)
{
rem[current+i]=(rem[current+i]^gen[i]);
}
while(rem[current]==0&¤t!=rem.length-1)
{
current++;
}
if(rem.length-current)<gen.length)
{
break;
}
}
return rem;
}
}
}
Output:
Enter the no of bits in the message : 4
Enter the message bits : 1 0 0 1
Enter the no of bits generated : 17
Enter the generated bits :
10001000000100001
Message bits: 1 0 0 1
Generated bits : 1 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 1
Appended message : 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Transmitted message from transmitter : 1 0 0 1 1 0 0 1 0 0 0 1 0 0 1 0 1 0 0 1
Message of 20 bits received :
10011001000100101001
There is no error
class Frame {
int id;
class Sender {
private Queue<Frame> window;
private int windowSize;
private int nextFrameToSend;
private int lastAckReceived;
scanner.close();
}
}
Sample Output
Bell man ford algorithm is a procedure used to find all shortest path in a graph from one
source to all other nodes. The algorithm was introduced by American mathematicians
Richard Bellman and Lester ford. Computes shortest from a single source vertex to all of
the other vertices in a weighted diagraph.
Source Code:
import java.io.*;
import java.util.*;
import java.io.DataInputStream;
class Edge
{
int source;
int dest;
int weight;
}
class Bellman
{
public static void BellmanFord(Edge edges[], int edgecount, int nodecount, int
source)
{
int infinity=50000;
int i, j;
int distance[]=new int[nodecount];
for(i=0; i<nodecount; i++)
distance[i]=infinity;
distance[source]=0;
for(i=0; i<nodecount; i++)
{
boolean somethingchanged=false;
for(j=0; j<edgecount; j++)
{
if(distance[edges[j].source]!=infinity)
{
int new_distance=distance[edges[j].source]+edges[j].weight;
if(new_distance<distance[edges[j].dest])
{
distance[edges[j].dest]=new_distance;
somethingchanged=true;
}
}
}
if(!somethingchanged)
break;
}
for(i=0; i<edgecount; ++i)
{
if(distance[edges[i].dest]>distance[edges[i].source]+edges[i].weight)
System.out.println("Negative edge weightcycles detected!!!");
}
for(i=0; i<nodecount; ++i)
System.out.println("The shortest distance between nodes "
+source+" & "+i+" is "+distance[i]);
}
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
Edge edges[]=new Edge[10];
for( int i=0; i<10; i++)
{
edges[i]=new Edge();
System.out.print("Enter source number ["+i+"] :
");
edges[i].source=in.nextInt();
System.out.print("Enter destination number ["+i+"] :
");
edges[i].dest=in.nextInt();
System.out.print("Enter weight number ["+i+"] :
");
edges[i].weight=in.nextInt();
System.out.println();
}
BellmanFord(edges, 10, 5, 4);
}
}
Output:
Enter the number of vertices : 4
Enter the adjacency matrix:
0 5 999 999
5024
999 2 0 1
999 4 1 0
Socket is an interface which enables the client and the server to communicate and pass on
information from one another. Sockets provide the communication mechanism between
two computers using TCP. A client program creates a socket on its end of the
communication and attempts to connect that socket to a server. When the connection is
made, the server creates a socket object on its end of the communication. The client and the
server can now communicate by writing to and reading from the socket.
TCP Client
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.Scanner;
class Client
{
public static void main(String args[])throws Exception
{
String address = "";
Scanner sc=new Scanner(System.in); System.out.println("Enter Server Address: ");
address=sc.nextLine();
//create the socket on port 5000
Socket s=new Socket(address,5000);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Send Get to start...");
String str="",filename="";
try
{
while(!str.equals("start")) str=br.readLine();
dout.writeUTF(str);
dout.flush();
filename=din.readUTF();
System.out.println("Receving file: "+filename);
filename="client"+filename;
System.out.println("Saving as file: "+filename);
long sz=Long.parseLong(din.readUTF());
System.out.println ("File Size: "+(sz/(1024*1024))+" MB");
byte b[]=new byte [1024]; System.out.println("Receving file..");
TCP Server
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
class Server
{
public static void main(String args[])throws Exception
{
String filename; System.out.println("Enter File Name: ");
Scanner sc=new Scanner(System.in);
filename=sc.nextLine();
sc.close();
while(true)
{
//create server socket on port 5000
ServerSocket ss=new ServerSocket(5000);
System.out.println ("Waiting for request");
Socket s=ss.accept();
System.out.println ("Connected With "+s.getInetAddress().toString());
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
try
{
String str=""; str=din.readUTF();
System.out.println("SendGet....Ok");
if(!str.equals("stop"))
{
System.out.println("Sending File: "+filename);
dout.writeUTF(filename);
dout.flush();
File f=new File(filename);
FileInputStream fin=new FileInputStream(f);
long sz=(int) f.length();
byte b[]=new byte [1024];
int read;
dout.writeUTF(Long.toString(sz));
dout.flush();
System.out.println ("Size: "+sz);
System.out.println ("Buf size: "+ss.getReceiveBufferSize());
while((read = fin.read(b)) != -1)
{
dout.write(b, 0, read);
dout.flush();
}
fin.close(); System.out.println("..ok");
dout.flush();
}
dout.writeUTF("stop");
System.out.println("Send Complete");
dout.flush();
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("An error occured");
}
din.close();
s.close();
ss.close(); } } }
Output
Note:
Create two different files Client.java and Server.java. Follow the steps given:
1. Open a terminal run the server program and provide the filename to send
2. Open one more terminal run the client program and provide the IP address of the
server. We can give localhost address “127.0.0.1” as it is running on same machine
or give the IP address of the machine.
3. Send any start bit to start sending file.
At server side:
At Client side:
8. Develop a program on a datagram socket for client/server to
display the messages on client side, typed at the server
side.
A datagram socket is the one for sending or receiving point for a packet delivery service.
Each packet sent or received on a datagram socket is individually addressed and routed.
Multiple packets sent from one machine to another may be routed differently, and may
arrive in any order.
Code:
UDP Client
import java.io.*; import java.net.*;
public class UDPC
{
public static void main(String[] args)
{
DatagramSocket skt;
try
{
skt=new DatagramSocket();
String msg= "text message ";
byte[] b = msg.getBytes();
InetAddress host=InetAddress.getByName("127.0.0.1");
int serverSocket=6788;
DatagramPacket request =new DatagramPacket (b,b.length,host,serverSocket);
skt.send(request);
byte[] buffer =new byte[1000];
DatagramPacket reply= new DatagramPacket(buffer,buffer.length); skt.receive(reply);
System.out.println("client received:" +new String(reply.getData())); skt.close();
}
catch(Exception ex) { } } }
UDP Server
import java.io.*;
import java.net.*;
public class UDPS
{
public static void main(String[] args)
{
DatagramSocket skt=null;
try {
skt=new DatagramSocket(6788); byte[] buffer = new byte[1000];
while(true)
{
DatagramPacket request = new DatagramPacket(buffer,buffer.length); skt.receive(request);
String[] message = (new String(request.getData())).split(" ");
byte[] sendMsg= (message[1]+ " server processed").getBytes(); DatagramPacket reply =
new DatagramPacket (sendMsg,sendMsg.length,request.getAddress (),request.getPort());
skt.send(reply);
} }
catch(Exception ex) { } } }
Output
1. Open a terminal run the server program.
2. Open one more terminal run the client program, the sent
message will be received.
Create two different files
UDPC.java and UDPS.java
Follow the following steps:
At Server side:
At Client side:
9. Develop a program for a simple RSA algorithm to encrypt
and decrypt the data.
1. Key Generation
2. Encryption
3. Decryption
1. Key Generation
In the RSA scheme, the key length is typically 512 bits, which requires an enormous
computational power. A plaintext is encrypted in blocks, with each block having a binary
value less than some number n. Encryption and decryption are done as follows,
beginning with the generation of a public key and a private key.
2. Encryption
c=mx mod n.
3. Decryption
m=cy mod n.
Traffic shaping or policing: To control the amount and rate of traffic is called Traffic
shaping or policing. Traffic shaping term is used when the traffic leaves a network.
Policing term is used when the data enters the network. Two techniques can shape or police
the traffic leaky bucket and token bucket.
importjava.util.*;
public class leaky
{
public static void main(String[] args)
{
Scanner my = new Scanner(System.in);
intno_groups,bucket_size;
System.out.print("\n Enter the bucket size : \t");
bucket_size = my.nextInt();
System.out.print("\n Enter the no of groups : \t");
no_groups = my.nextInt();
intno_packets[] = new int[no_groups];
intin_bw[] = new int[no_groups];
intout_bw,reqd_bw=0,tot_packets=0;
for(inti=0;i<no_groups;i++)
{
System.out.print("\n Enter the no of packets for group " + (i+1) + "\t");
no_packets[i] = my.nextInt();
System.out.print("\n Enter the input bandwidth for the group " + (i+1) + "\t");
in_bw[i] = my.nextInt();
if((tot_packets+no_packets[i])<=bucket_size)
{
tot_packets += no_packets[i];
}
else
{
do
{
System.out.println(" Bucket Overflow ");
System.out.println(" Enter value less than " + (bucket_size-
tot_packets));
no_packets[i] = my.nextInt();
}while((tot_packets+no_packets[i])>bucket_size);
tot_packets += no_packets[i];
}
reqd_bw += (no_packets[i]*in_bw[i]);
}
while((out_bw<=temp)&&(rem_pkts>0))
{
System.out.println("Data Sent \n" + (--rem_pkts) + " packets remaining");
System.out.println("Remaining Bandwidth " + (temp -= out_bw));
if((out_bw>temp)&&(rem_pkts>0))
System.out.println(rem_pkts + " packet(s) discarded due to insufficient
bandwidth");
}
}
}
Out Put:
Enter bucket size : 20
Enter number of groups :2
Enter number of packets of group 1:2
Enter input bandwidth for group 1:2
Enter number of packets of group 2 :3
Enter input bandwidth for group 2 : 3
Total required bandwidth :13
Enter the output bandwidth:2
Data sent
4 packets remaining
Remaining bandwidth:11
Data sent
3 packets remaining
Remaining bandwidth : 9
Data sent
2 packets remaining
Remaining bandwidth :7
Data sent
1 packets remaining
Remaining bandwidth :5
Data sent
0 packets remaining
Remaining bandwidth :3