CN Lab Manual 2023 2
CN Lab Manual 2023 2
1. Introduction to NS-2
NS-2 consists of two key languages: C++ and Object-oriented Tool Command
Language (OTcl). While the C++ defines the internal mechanism (i.e., a backend) of
the simulation objects, the OTcl sets up simulation by assembling and configuring the
NS2 consists of two key languages: C++ and Object-oriented Tool Command
Language (OTcl).
The C++ defines the internal mechanism (i.e.,a backend) of the simulation objects.
The OTcl sets up simulation by configuring the objects as well as scheduling
discrete events (i.e., a frontend).
The C++ and the OTcl are linked together using TclCL.
NS2 uses OTcl to create and configure a network, and uses C++ to run simulation.
C++ is fast to run but slow to change.
OTcl, on the other hand, is slow to run but fast to change.
We write a Tcl simulation script and feeditas an input argument to NS2 when
running a simulation (e.g., executing “ns myfirst_ns.tcl”).
Here, “ns” is a C++ executable file obtained from the compilation.
myfirst_ns.tcl is an input configuration file specifying system parameters and
configuration such as nodes, link, and how they are connected.
C++ is used for the creation of objects because of speed and efficiency.
OTcl is used as a front-end to setup the simulator, configure objects and
schedule events because of its ease of use.
Tcl scripting
2. Working of NS-2
Once the simulation is complete, we can see two files: “trace.tr”, and “nam.out”.
The trace file (trace.tr) is a standard format used by ns2.
In ns2, each time a packet moves from one node to another, or onto a link, or
into a buffer, etc., it gets recorded in this trace file.
1. Open Source
2. Complex scenarios can be easily tested.
3. Results can be quickly obtained – more ideas can be tested in a smaller time frame.
4. Supported protocols
5. Supported platforms
6. Modularity
Disadvantages
UDP Agent :To use UDP in simulation, the sender sets the Agent as UDP Agent
while the receiver sets to Null Agent. Null Agents do nothing except receiving the
set tcp [new Agent/TCP] # tcp and sink Agent are set for n1 and n3, respectively
$ns attach-agent $n1 $tcp
set sink [new Agent/TCPSink]
$ns attach-agent $n3 $sink
$ns connect $tcp $sink #declares the transmission between tcp and sink.
$tcp set fid_ 1 #sets the number for data flow of tcp. This number will be
recorded to all packet which are sent from tcp
$ns color 1 red #mark the color to discrete packet for showing result on
Nam.
$ns at 1.0 "$cbr start" cbr transmits data from 1.0[sec] to 3.5[sec]
$ns at 3.5 "$cbr stop"
$ns at 1.5 "$ftp start" ftp transmits data from 1.5[sec] to 3.0[sec].
$ns at 3.0 "$ftp stop"
ns sample.tcl
nam out.nam
View trace file
(out.tr)
1. The first field is the event type. It is given by one of four possible symbols r, +, -, d
which correspond respectively to receive (at the output of the link), enqueued,
dequeued and dropped.
2. The second field gives the time at which the event occurs.
3. Gives the input node of the link at which the event occurs.
4. Gives the output node of the link at which the event occurs.
5. Gives the packet type (eg CBR or TCP)
6. Gives the packet size
7. Some flags
8. This is the flow id (fid) of IPv6 that a user can set for each flow at the input OTcl
AWK file:
The basic function of awk is to search files for lines (or other units of text) that contain
certain patterns. When a line matches one of the patterns, awk performs specified
actions on that line. awk keeps processing input lines in this way until the end of the
input files are reached. Programs in awk are different from programs in most
other languages, because awk programs are data-driven; that is, we describe the data
to work with, and then what to do when we find it. Most other languages are
procedural. When working with procedural languages, it is usually much harder to
clearly describe the data of our program will process. For this reason, awk programs
are often refreshingly easy to both write and read. When we run awk, we can specify
an awk program that tells awk what to do. The program consists of a series of rules.
(It may also contain function definitions, an advanced feature which we will ignore
for now. Each rule specifies one pattern to search for, and one action to perform when
that pattern is found). Syntactically, a rule consists of a pattern followed by an action.
The action is enclosed in curly braces to separate it from the pattern. Rules are usually
separated by newlines. Therefore, an awk program looks like this:
pattern { action } pattern { action }
Since we are dealing with column oriented data, AWK is probably the easiest tool we
can use to format our data. AWK is a simple scripting language that scans through a
file line by line. It allows to access any column in the current line by using special
variables $1, $2, $3, etc. for the first, second and third columns. The definition of each
column of the trace file is shown above, so we can use the AWK script to check the
value of each column and collect the data we need.
NS Simulation Script
This network consists of 4 nodes (n0, n1, n2, n3) as shown in Fig. 5. The duplex links
between n0 and n2, and n1 and n2 have 2 Mbps of bandwidth and 10 ms of delay. The
duplex link between n2 and n3 has 1.7 Mbps of bandwidth and 20 ms of delay. Each
node uses a DropTail queue, of which the maximum size is 10. A "tcp" agent is
The "cbr" is set to start at 0.1 sec and stop at 4.5 sec, and "ftp" is set to start at 1.0
sec and stop at 4.0 sec.
An Example Simulation
Script
#Create a simulator object
set ns [new Simulator]
#Create four
nodes set n0 [$ns
node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
#Bus Topology
#Create a simulator object
set ns [new Simulator]
Open gedit and type program. Program name should have the extension “. tcl ”
[root@localhost ~] gedit topo1.tcl
Save the program.
Open gedit and type awk program. Program name should have the extension “. awk ”
[root@localhost ~] gedit topo1.awk
Save the program.
Run the simulation program [root@localhost~] ns topo1.tcl
Here “ns” indicates network simulator. We get the topology shown in the snapshot.
Now press the play button in the simulation window and the simulation will begin.
Snapshot 2
Program:
set ns [ new Simulator ]
set tf [ open lab1.tr w ]
$ns trace-all $tf
set nf [ open lab1.nam w ]
$ns namtrace-all $nf
# The below code is used to create the nodes.
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
#This is used to give color to the packets.
$ns color 1 "red"
$ns color 2 "blue"
$n0 label "Source/udp0"
$n1 label "Source/udp1"
$n2 label "Router"
BEGIN{
#include<stdio.
h>
count=0;
}
{
if($1=="d") #d stands for the packets
drops.
count++
}
EN
D{
printf("The Total no of Packets Dropped due to Congestion :%d\n\n", count)
}
Open gedit and type program. Program name should have the extension “. tcl ”
[root@localhost ~] gedit lab1.tcl
Save the program.
Open gedit and type awk program. Program name should have the extension “. awk ”
[root@localhost ~] gedit lab1.awk
Save the program.
Run the simulation program [root@localhost~] ns lab1.tcl
Here “ns” indicates network simulator. We get the topology shown in the snapshot.
Now press the play button in the simulation window and the simulation will begin.
After simulation is completed run awk file to see the output,
[root@localhost~] awk –f lab1.awk lab1.tr
To see the trace file contents open the file as , [root@localhost~] gedit lab1.tr
Output:
The Total no of packets Dropped due to congestion: 456
Snapshot 2
Program:
Source 1:
Set Protocol: TCP
Set Traffic Type: FTP
N1
Destination 1:
Set Traffic Type: Sink
N0 N5 N7
(1Mbps, 20ms)
(2Mbps, 10ms)* LAN
N2
Source 2:
Set Protocol: TCP N4 N6 N8
Set Traffic Type: FTP
Destination 2:
Set Traffic Type: Sink
AWK File:
BEGIN {
}
{
if($6=="cwnd_") {
Output Commands:
Snapshot 1:
Snapshot 2:
Snapshot 3:
# destructor
proc finish {} {
global ns nf
$ns flush-trace
close $nf
exec nam out.nam &
exit 0
}
Snapshot 1
Snapshot 2
Destination 1:
Source 2: Set Traffic Type: Sink
Set Protocol: TCP
Set Traffic Type: FTP n2
n1
Destination 1:
Set Traffic Type: Sink
n0
Source 1:
Set Protocol: TCP
Set Traffic Type: FTP
Program:
set ns [new Simulator]
set val(chan) Channel/WirelessChannel;
set val(prop) Propagation/TwoRayGround;
set val(netif) Phy/WirelessPhy;
set val(mac) Mac/802_11;
set val(ifq) Queue/DropTail/PriQueue;
set val(ll) LL;
set val(ant) Antenna/OmniAntenna;
set val(ifqlen) 50;
set val(nn) 2;
set val(rp) DSDV;
set val(x) 1000.0;
set val(y) 1000.0;
# channel type
# radio-propagation model
# network interface type
# MAC type
# interface queue type
# link layer type
# antenna model
# max packet in ifq
# number of mobilenodes
# routing protocol
set tf [open lab4.tr w]
$ns trace-all $tf
set topo [new Topography]
$topo load_flatgrid 1000 1000
set nf [open lab4.nam w]
AWK FILE:
BEGIN {
#include<stdio.h>
count1=count2=pack1=pack2= time1=time2=0
}
{
if($1 == "r"&&$3 == "_1_"&&$4 == "AGT")
{
count1++
pack1=pack1+$8
time1=$2
}
if($1=="r"&&$3=="_2_"&&$4=="AGT")
{
count2++
pack2 = pack2+$8
time2=$2
}
}
END{
printf("The Throughput from n0 to n1: %f Mbps\n",((count1 * pack1 *8)/(time1*1000000)));
printf("The Throughput from n1 to n2: %f Mbps", ((count2 * pack2 * 8) /(time2*1000000)));
}
Output Commands:
[root@localhost ~]# ns prg4.tcl
[root@localhost ~]# awk –f prg4.awk lab4.tr
Output:
The Throughput from n0 to n1: 5444Mbps
The Throughput from n1 to n2: 345Mbps
Snapshot 2:
Snapshot 3:
ALGORITHM:
1. Start
2. Declare a variable ‘ip’ as a static InetAddress.
3. Using the function getLocalHost() to find the address of the system.
4. Get the name of the system by using the getHostName() function.
5. By specifying the system name,find out the IP address of the system using
the function getByName().
6. Stop.
SOURCE CODE:
import java.io.*;
import java.net.*;
class address
{
public InetAddress ip;
public static void main(String args[])throws UnknownHostException
{
InetAddress ip=InetAddress.getLocalHost();
System.out.println("\n IP address is :"+ip);
String s1=ip.getHostName();
System.out.println("system number is:"+s1);
InetAddress ip1=InetAddress.getByName("system 10");
System.out.println("\n name of other system is :"+ip1);
}
}
Output:
class FibonacciExample1
{
public static void main(String args[])
{
int n1=0,n2=1,n3,i,count=10;
System.out.print(n1+" "+n2);//printing 0 and 1
for(i=2;i<count;++i)//loop starts from 2 because 0 and 1 are already printed
{
n3=n1+n2;
Output:
0112358
The idea behind CRC calculation is to look at the data as one large binary number.
This number is divided by generator and the remainder of the calculation is called the CRC.
All of the CRC formulas you will encounter are based on modulo-2 binary division
where we ignore carry bits and in effect the subtraction will be equal to an exclusive or
operation. Though some differences exist in the specifics across different CRC formulas, the
basic mathematical process is always the same:
The message bits are appended with k-1 zero bits; this augmented message is the
dividend
A predetermined k-bit binary sequence, called the generator polynomial, is the divisor
The checksum is the c-bit remainder that results from the division operation
Table 1 lists some of the most commonly used generator polynomials for 16- and 32-bit
CRCs. Remember that the width of the divisor is always one bit wider than the remainder.
So, for example, you’d use a 17-bit generator polynomial whenever a 16-bit checksum is
required.
Generator
1000100000010 110000000000001 10000010011000001000111011011
Polynomial
0001 01 0111
in bits
Table 1. International Standard CRC Polynomials
x8+x2+x+1
o Used in: 802.16 (along with error correction).
CRC-12: x12 + x11 + x3 + x2 + x + 1
Program:
import java.util.Scanner;
class CRC
{
static String datastream;
static String generator= "10001000000100001";
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("---At the Sender---\n Enter data stream: ");
String datastream = sc.nextLine();
int datalen=datastream.length();
int genlen =generator.length();
int data[] = new int[datalen + genlen - 1];
int codeword[] = new int[datalen + genlen - 1];
int div[] = new int[generator.length()];
for(int i=0;i<datastream.length();i++)
data[i] = Integer.parseInt(datastream.charAt(i)+"");
for(int i=0;i<generator.length();i++)
div[i] = Integer.parseInt(generator.charAt(i)+"");
codeword = calculateCrc(data,div,datalen);
System.out.println("The CRC(Final Codeword) code is: "); //Display CRC-final codeword
Distance Vector Algorithm is a decentralized routing algorithm that requires that each
router simply inform its neighbors of its routing table. For each network path, the receiving
routers pick the neighbor advertising the lowest cost, then add this entry into its routing table
for re-advertisement. To find the shortest path, Distance Vector Algorithm is based on one of
two basic algorithms: The Bellman-Ford and the Dijkstra algorithms. Routers that use this
algorithm have to maintain the distance tables (which is a one- dimension array -- "a vector"),
which tell the dist and shortest path to sending packets to each node in the network. The
information in the distance table is always up date by exchanging information with the
neighboring nodes. The number of data in the table equals to that of all nodes in networks
(excluded itself). The columns of table represent the directly attached neighbors whereas the
rows represent all destinations in the network. Each data contains the path for sending packets
to each destination in the network and distance/or time to transmit on that path (we call this as
"cost"). The measurements in this algorithm are the number of hops, latency, the number of
outgoing packets, etc.
The Bellman–Ford algorithm is an algorithm that computes shortest paths from a
single source v to all of the other vertices in a weighted digraph. It is slower than Dijkstra's
algorithm for the same problem, but more versatile, as it is capable of handling graphs in
which some of the edge weights are negative numbers. Negative edge weights are found in
various applications of graphs, hence the usefulness of this algorithm. If a graph contains a
"negative cycle" (i.e. a cycle whose edges sum to a negative value) that is reachable from the
source, then there is no cheapest path: any path that has a point on the negative cycle can be
made cheaper by one more walk around the negative cycle. In such a case, the Bellman–Ford
algorithm can detect negative cycles and report their existence.
}
}
}
}
for (int sourcenode = 1; sourcenode <= numberofvertices; sourcenode++)
{
for (int destinationnode = 1; destinationnode <= numberofvertices; destinationnode++)
{
if (adjacencymatrix[sourcenode][destinationnode] != MAX_VALUE)
{
if (distances[destinationnode] > distances[sourcenode]
+ adjacencymatrix[sourcenode][destinationnode])
System.out.println("The Graph contains negative egde cycle");
}
}
}
for (int vertex = 1; vertex <= numberofvertices; vertex++)
{
System.out.println("distance of source " + source + " to " + vertex + " is " + distances[vertex]);
}
}
public static void main(String... arg)
{
int numberofvertices = 0;
int source;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of vertices");
numberofvertices = scanner.nextInt()
int adjacencymatrix[][] = new int[numberofvertices + 1][numberofvertices + 1];
System.out.println("Enter the adjacency matrix");
for (int sourcenode = 1; sourcenode <= numberofvertices; sourcenode++)
{
for (int destinationnode = 1; destinationnode <= numberofvertices; destinationnode++)
{
adjacencymatrix[sourcenode][destinationnode] = scanner.nextInt();
if (sourcenode == destinationnode)
{
adjacencymatrix[sourcenode][destinationnode] = 0;
continue;
Output Sample 2:
Enter the number of vertices
6
Enter the adjacency matrix
0 4 1 999 999 999
999 0 999 999 1 2
999 999 0 3 999 999
999 999 999 0 999 999
-6 999 2 4 0 999
999 999 999 5 999 0
Enter the source vertex 1
After (N-1)th Iteration
distance of source 1 to 1 is -5
distance of source 1 to 2 is 0
distance of source 1 to 3 is -3
The main concept of the leaky bucket algorithm is that the output data flow remains
constant despite the variant input traffic, such as the water flow in a bucket with a small hole
at the bottom. In case the bucket contains water (or packets) then the output flow follows a
constant rate, while if the bucket is full any additional load will be lost because of spillover.
In a similar way if the bucket is empty the output will be zero.
From network perspective, leaky bucket consists of a finite queue (bucket) where all the
incoming packets are stored in case there is space in the queue, otherwise the packets are
discarded. In order to regulate the output flow, leaky bucket transmits one packet from the
queue in a fixed time (e.g. at every clock tick). In the following figure we can notice the
main rationale of leaky bucket algorithm, for both the two approaches (e.g. leaky bucket with
water (a) and with packets (b)).
n=p*q;
z=(p-1)*(q-1);
System.out.println("the value of z = "+z);
for(e=2;e<z;e++)
{
if(gcd(e,z)==1) // e is for public key exponent
{
break;
}
}
System.out.println("the value of e = "+e);
for(i=0;i<=9;i++)
{
int x=1+(i*z);
if(x%e==0) //d is for private key exponent
{
d=x/e;
break;
}
}
System.out.println("the value of d = "+d);
c=(Math.pow(msg,e))%n;
System.out.println("Encrypted message is : -");
System.out.println(c);
//converting int value of n to BigInteger
BigInteger N = BigInteger.valueOf(n);
//converting float value of c to BigInteger
BigInteger C = BigDecimal.valueOf(c).toBigInteger();
msgback = (C.pow(d)).mod(N);
System.out.println("Derypted message is : -");
System.out.println(msgback);
}
static int gcd(int e, int z)
{
if(e==0)
return z;
else
return gcd(z%e,e);
}
}
The term network programming refers to writing programs that execute across multiple
devices (computers), in which the devices are all connected to each other using a network.
The java.net package of the J2SE APIs contains a collection of classes and interfaces that
provide the low-level communication details, allowing you to write programs that focus on
solving the problem at hand.
The java.net package provides support for the two common network protocols −
TCP − TCP stands for Transmission Control Protocol, which allows for reliable
communication between two applications. TCP is typically used over the Internet
Protocol, which is referred to as TCP/IP.
UDP − UDP stands for User Datagram Protocol, a connection-less protocol that
allows for packets of data to be transmitted between applications.
Socket characteristics
Sockets are characterized by their domain, type and transport protocol. Common domains
are:
AF_UNIX: address format is UNIX pathname
AF_INET: address format is host and port number
Common types are:
virtual circuit: received in order transmitted and reliably
datagram: arbitrary order, unreliable
Each socket type has one or more protocols. Ex:
TCP/IP (virtual circuits)
UDP (datagram)
The server invokes the accept() method of the ServerSocket class. This method waits
until a client connects to the server on the given port.
After the server is waiting, a client instantiates a Socket object, specifying the server
name and the port number to connect to.
The constructor of the Socket class attempts to connect the client to the specified
server and the port number. If communication is established, the client now has a
Socket object capable of communicating with the server.
On the server side, the accept() method returns a reference to a new socket on the
server that is connected to the client's socket.
Program:
Server SideProgram:
import java.io.*;
import java.net.*;
public class FileServer
{
public static void main(String[] args)
{
new FileServer();
}
public FileServer()
{
try
{
ServerSocket serversocket=new ServerSocket(8000);
System.out.println("Server Started....");
System.out.println("-----------------------------------------------");
Socket socket=serversocket.accept();
DataInputStream input=new DataInputStream(socket.getInputStream());
DataOutputStream output=new DataOutputStream(socket.getOutputStream());
String str=input.readUTF();
System.out.println("Requested File Name:"+str);
System.out.println("-----------------------------------------------");
String everything;
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.
4. Refer https://www.tutorialspoint.com/java/java_networking.htm for all the parameters,
methods description in socket communication.
Output:
Server Side:
Server Started....
-----------------------------------------------
Requested File Name: abc.txt
-----------------------------------------------
Client Side:
Enter IP address of the server:
localhost
Connecting to Server....
Enter File Name:
abc.txt
-----------------------------------------------
Content of a File:
ALGORITHM:
SERVER:
1. Start the Program.
2. Import .net package and other packages.
3. Declare objects for ServerScoket, Socket and printStream to transfer server data.
4. Declare objects for Scoket and DataInputStream to receive client data.
5. Using printStream transfer the data in OutputStream via a port.
6. Run loop to send data from server until an”end or exit” String is transferred.
7. Using the same loop receive data from server and store it in a StringUsing
dataInputStream.
8. print the String to display the server data and exit when an”end or exit” Message is
encountered.
CLIENT:
1. Start the program.
2. Import .net package and other packages.
3. Declare objects for Socket, Socket and PrintStream to transfer54 the client data.
4. Declare objects for Socket and DataInputStream to receive server the data.
5. Using PrintStream transfer the data in OutputStream via a port.
6. Run loop to send data from server until an “end or exit” string is transferred.
7. Using the same loop receive data from server and store it in a String using
DataInputStream.
8. Print the string to display the server data and exit when “send or exit” Message is
encountered.
SOURCE CODE:
CLIENT
import java.io.*;
import java.net.*;
import java.lang.*;
class client1
{
public static void main(String a[])throws IOException
{
Socket s=new Socket("LocalHost",8000);
DataInputStream in=new DataInputStream(s.getInputStream());
DataInputStream inn=new DataInputStream(System.in);
PrintStream dos=new PrintStream(s.getOutputStream());
{
String str=in.readLine();
System.out.println("message received:"+str);
if(str.equals("end"))
{
s.close();
break;
}
System.out.println("enter the message to send: ");
String str1=inn.readLine();
dos.println(str1);
if(str1.equals("end"))
{
s.close();
break;
} } } }
SERVER
import java.io.*;
import java.net.*;
import java.lang.*;
class server1
{
public static void main(String a[])throws IOException
{
ServerSocket ss=new ServerSocket(8000);
Socket s=ss.accept();
PrintStream dos=new PrintStream(s.getOutputStream());
DataInputStream in=new DataInputStream(System.in);
DataInputStream inn=new DataInputStream(s.getInputStream());
while(true)
{
System.out.println("enter the message to send: ");
String str=in.readLine();
dos.println(str);
if(str.equals("end"))
{
ss.close();
break;
}
String str1=inn.readLine();
System.out.println("message received"+str1);
if(str1.equals("end"))
{
ss.close();
break;
} } } }
SERVER
enter the message to send: HAI FRIENDS
message received: HELLO
enter the message to send: end
CLIENT
message received: HAI FRIENDS
enter the message to send: HELLO
enter the message to send: end
AIM: To write a java program to perform two way message transfer using the user
datagram protocol (UDP).
ALGORITHM:
SERVER:
1. Start the program
2. Import .net and other necessary packages.
3. Declare objects for datagramSocket and DatagramPacket to receive packet
data from server.
4. Receive an object for InetAddress of the LocalHost.
5. Receive the client data using receive() method and store it to a string.
6. Run a loop and store the data in the string until the received message points end.
7. Print the string unless it encounters end.
8. Get user input in the same loop and send data until the user input points end.
9. Convert the user input into bytes and send the byte using DatagramPacket and
DatagramSocket.
10. If end is encountered, exit sending data and program.
CLIENT:
1. Start the program
2. Import .net and other necessary packages.
3. Declare objects for datagramSocket and DatagramPacket to receive packet
data from server.
4. Declare an object for InetAddress of the Local Host.
5. Receive the Server data using receive() method and store it to a st ring.
6. Run a loop and store the data in the string until the received message points
the end.
7 . Print the string unless it encounters end.
8. Get user input in the same loop and send data until the user input points end.
9. Convert the user input into b ytes and send the byte using DatagramPacket and
DatagramSocket.
10. If end is encountered, exit sending data and program.
SENDER
import java.io.*;
import java.net.*;
class sender
{
public static void main(String a[])throws Exception
{
while(true)
{
DatagramSocket ds=new DatagramSocket();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the message:");
String message=br.readLine();
byte bl[]=message.getBytes();
InetAddress add=InetAddress.getLocalHost();
DatagramPacket dp=new DatagramPacket(bl,bl.length,add,1234);
ds.send(dp);
if(message.equals("exit"))
System.exit(0);
byte b[]=new byte[255];
DatagramPacket dp1=new DatagramPacket(bl,bl.length);
ds.receive(dp1);String message1=new String(dp1.getData());
System.out.println("received message:" +message1);
}
}
}
RECEIVER
import java.io.*;
import java.net.*;
import java.lang.*;
class receiver
{
public static void main(String a[])throws IOException
{
DatagramSocket ds=new DatagramSocket(1234);
byte b[]=new byte[255];
while(true)
{
DatagramPacket dp=new DatagramPacket(b,b.length);
ds.receive(dp);
String message=new String(dp.getData());
System.out.println("Message Received:"+message);
InetAddress add=dp.getAddress();
int port=dp.getPort();
System.out.println("Enter a line of text to send:");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
OUTPUT:
SENDER :
enter the message: GOOD MORNING
received message: HAVE A NICE DAY
enter the message: end
RECEIVER:
Message Received: GOOD MORNING
Enter a line of text to send: HAVE A NICE DAY
Message Received: end
The energy of the mobile node is fixed in ns2 using energy model. The components required
for designing for energy model includes initialEnergy, txPower, rxPower, and idlePower.