0% found this document useful (0 votes)
60 views65 pages

Cs3591 Computer Networks Lab Record

Uploaded by

Shanmu Priya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views65 pages

Cs3591 Computer Networks Lab Record

Uploaded by

Shanmu Priya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

THE KAVERY ENGINEERING COLLEGE Page :

THE KAVERY ENGINNERING COLLEGE


MECHERI, SALEM – 636453, TAMIL NADU.

DEPARTMENT OF COMPUTER SCIENCE AND


ENGINEERING

CS3591 COMPUTER NETWORKS


LABORATORY

Student Name:_____________________________
Year / Semester: III / V
THE KAVERY ENGINEERING COLLEGE Page :

Staff Sign
Awarded
Page No.

Marks
Ex. Date Name of the Experiment
No.

1(a) Study of Network Commands

1(b) Simulation of PING Command

1(c) Simulation of tracerouter command


Create a Socket for HTTP for Web page and
2 Upload and Download

3(a) Socket Program For ECHO

3(b) Client- Server application for chat

3(c File Transfer In Client & Server


Implementation of DNS using TCP and
4
UDP sockets
5(a) Implementation of ARP Protocols

5(b) Simulation Of Rarp Protocol

6(a) Study of Network Simulator (NS)


Simulation Of Congestion Control
6(b)
Algorithm Using Ns2
Study of TCP/UDP performance using
7
Simulation tool.
Simulation Of Link State Routing Protocol
8(a)
Using Ns2
Simulation Of Distance Vector Routing
8(b)
Protocol Using Ns2

9 Simulation of error correction code CRC).


THE KAVERY ENGINEERING COLLEGE Page :

EX. NO.:1(a)
STUDY OF NETWORKING COMMANDS
AIM
To study the basic networking commands.

COMMANDS:

C:\>arp –a:
ARP is short form of address resolution protocol, It will show the IP address of
your computer along with the IP address and MAC address of your router.

C:\>hostname:
This is the simplest of all TCP/IP commands. It simply displays the
name of your computer.

C:\>ipconfig:
The ipconfig command displays information about the host (the computer your
sitting at)computer TCP/IP configuration.

C:\>ipconfig /all:
This command displays detailed configuration information about your
TCP/IP connection including Router, Gateway, DNS, DHCP, and type of Ethernet
adapter in your system.

C:\>Ipconfig /renew:
Using this command will renew all your IP addresses that you are currently
(leasing) borrowing from the DHCP server. This command is a quick problem solver
if you are having connection issues, but does not work if you have been configured
with a static IP address.

C:\>Ipconifg /release:
This command allows you to drop the IP lease from the DHCP server.

C:\>ipconfig /flushdns:
This command is only needed if you‟re having trouble with your networks
DNS configuration. The best time to use this command is after network configuration
frustration sets in, and you really need the computer to reply with flushed.

C:\>nbtstat –a:
This command helps solve problems with NetBIOS name resolution. (Nbt
stands for NetBIOS over TCP/IP)
THE KAVERY ENGINEERING COLLEGE Page :

C:\>netdiag:
Netdiag is a network testing utility that performs a variety of network
diagnostic tests, allowing you to pinpoint problems in your network. Netdiag isn‟t
installed by default, but can be installed from the Windows XP CD after saying no to
the install. Navigate to the CD ROM drive letter and open the support\tools folder on
the XP CD and click the setup.exe icon in the support\tools folder.

C:\>netstat:
Netstat displays a variety of statistics about a computers active TCP/IP
connections. This tool is most useful when you‟re having trouble with TCP/IP
applications such as HTTP, and FTP.

C:\>nslookup:
Nslookup is used for diagnosing DNS problems. If you can access a resource by
specifying an IP address but not it‟s DNS you have a DNS problem.

C:\>pathping:
Pathping is unique to Window‟s, and is basically a combination of the Ping
and Tracert commands. Pathping traces the route to the destination address then
launches a 25 second test of each router along the way, gathering statistics on the rate
of data loss along each hop.

C:\>ping:
Ping is the most basic TCP/IP command, and it‟s the same as placing a phone
call to your best friend. You pick up your telephone and dial a number, expecting
your best friend to reply with “Hello” on the other end. Computers make phone calls
to each other over a network by using a Ping command. The Ping commands main
purpose is to place a phone call to another computer on the network, and request an
answer. Ping has 2 options it can use to place a phone call to another computer on the
network. It can use the computers name or IP address.

C:\>route:
The route command displays the computers routing table. A typical computer,
with a single network interface, connected to a LAN, with a router is fairly simple and
generally doesn‟t pose any network problems. But if you‟re having trouble accessing
other computers on your network, you can use the route command to make sure the
entries in the routing table are correct.

C:\>tracert: The tracert command displays a list of all the routers that a packet has to
go through to get from the computer where tracert is run to any other computer on
the internet.

C:\> $ tcpdump -i any

To get the network packets from all network interfaces, run the following command,
THE KAVERY ENGINEERING COLLEGE Page :

C:\> $ tcpdump -i eth0

To get the network packets from a single interface, use

C:\> $ tcpdump -r packets_file

To read an already created, old tcpdump file, use the following command,

C:\> $ tcpdump net 192.168.1.0/24

To get the packets for whole network, execute the following command from terminal

C:\>$ tcpdump src 192.168.1.100

$ tcpdump dst 192.168.1.100

To get packets based on source or destination of an IP address, use

C:\> $ tcpdump ssh

To check all the packets used based on the protocol, run the following command

C:\> $ tcpdump port 22

$ tcpdump portrange 22-125

To get packets for a single port ot for a range of ports, use

RESULT:
Thus the above list of primitive has been studied.
THE KAVERY ENGINEERING COLLEGE Page :

EX. NO.:1(b)
SIMULATION OF PING COMMAND

AIM:
To test the communication between hosts at IP level using Ping command.

Algorithm:

1. Get IP address / domain name from the user.


2. Create a runtime environment.
3. Execute ping command with given input as parameter.
4. Analyse the output
5. Stop

Program:
// PingServer.java : Simple Ping Program

import java.io.*;
import java.net.*;

class PingServer
{
public static void main(String args[])
{
try
{
String str;
System.out.print("Enter IP address/domain name: ");
BufferedReader buf1=new BufferedReader(new InputStreamReader(System.in));
String ip = buf1.readLine();
Runtime rt = Runtime.getRuntime();
Process p = rt.exec("ping " + ip);
InputStream in = p.getInputStream();
BufferedReader buf2 = new BufferedReader(new InputStreamReader(in));
while((str=buf2.readLine()) != null)
{
System.out.println(" " + str);
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
THE KAVERY ENGINEERING COLLEGE Page :

Output:

$ javac PingServer.java
$ java PingServer
Enter IP address/domain name: gmail.com

PING gmail.com (216.58.199.165) 56(84) bytes of data.


64 bytes from bom05s08-in-f5.1e100.net (216.58.199.165): icmp_req=1 ttl=58 time=34.7 ms
64 bytes from bom05s08-in-f5.1e100.net (216.58.199.165): icmp_req=2 ttl=58 time=36.2 ms
64 bytes from bom05s08-in-f5.1e100.net (216.58.199.165): icmp_req=3 ttl=58 time=32.0 ms
64 bytes from bom05s08-in-f5.1e100.net (216.58.199.165): icmp_req=4 ttl=58 time=32.4 ms
64 bytes from bom05s08-in-f5.1e100.net (216.58.199.165): icmp_req=5 ttl=58 time=31.5 ms
64 bytes from bom05s08-in-f5.1e100.net (216.58.199.165): icmp_req=6 ttl=58 time=32.8 ms
64 bytes from bom05s08-in-f5.1e100.net (216.58.199.165): icmp_req=7 ttl=58 time=31.1 ms
64 bytes from bom05s08-in-f5.1e100.net (216.58.199.165): icmp_req=8 ttl=58 time=32.7 ms
64 bytes from bom05s08-in-f5.1e100.net (216.58.199.165): icmp_req=9 ttl=58 time=31.8 ms
64 bytes from bom05s08-in-f5.1e100.net (216.58.199.165): icmp_req=10 ttl=58 time=31.4 ms

--- gmail.com ping statistics ---

10 packets transmitted, 10 received, 0% packet loss, time


9011ms

rtt min/avg/max/mdev = 31.148/32.724/36.287/1.547 ms

Result:
Thus using Ping command, connective and communicative status is determined.
THE KAVERY ENGINEERING COLLEGE Page :

EX.NO.:1(C)
SIMULATION OF TRACEROUTE COMMAND
Aim:
To trace the path traversed by a packet from host to destination using
Traceroute command.

Algorithm:

1. Get domain name from the user.


2. Create a runtime environment.
3. Execute traceroute command with given input as parameter.
4. Analyse the output
5. Stop

Program:
// 4b - TraceServer.java : Traceroute Program

import java.io.*;
import java.net.*;

class TraceServer
{
public static void main(String args[])
{
try
{
String str;
System.out.print("Enter domain name : ");
BufferedReader buf1=new BufferedReader(new InputStreamReader(System.in));
String ip = buf1.readLine();
Runtime rt = Runtime.getRuntime();
Process p = rt.exec("tracert " + ip);
InputStream in = p.getInputStream();
BufferedReader buf2 = new BufferedReader(new InputStreamReader(in));
while((str=buf2.readLine()) != null)
{
System.out.println(" " + str);
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
THE KAVERY ENGINEERING COLLEGE Page :

Output:

$ javac TraceServer.java
$ java TraceServer
Enter domain name: yahoo.com

Tracing route to yahoo.com [206.190.36.45]


over a maximum of 30 hops:

1 <1 ms <1 ms <1 ms 172.16.4.4


2 18 ms 17 ms 10 ms 182.19.59.114
3 154 ms 184 ms 158 ms 182.19.115.233
4 158 ms 156 ms 155 ms ae5-xcr2.lsw.cw.net [166.63.217.41]
5 232 ms 224 ms 230 ms ae11-xcr1.lns.cw.net [195.2.25.206]
6 155 ms 155 ms 170 ms ae1-xcr1.ltw.cw.net [195.2.24.125]
7 233 ms 234 ms 232 ms et-9-1-0-xcr2.nyk.cw.net [195.2.8.46]
8 243 ms 230 ms 228 ms pat1.nyc.yahoo.com [198.32.118.24]
9 230 ms 260 ms 231 ms ae7.pat1.dce.yahoo.com [216.115.104.120]
10 243 ms 245 ms 244 ms ae-6.pat1.che.yahoo.com [216.115.96.81]
11 334 ms 318 ms 294 ms ae-5.pat1.dnx.yahoo.com [216.115.96.34]
12 303 ms 313 ms 335 ms ae-8.pat2.gqb.yahoo.com [216.115.96.204]
13 314 ms 319 ms 316 ms et-18-1-0.msr2.gq1.yahoo.com [66.196.67.115]
14 * 301 ms 304 ms et-19-1-0.clr2-a-gdc.gq1.yahoo.com [67.195.37.99]
15 306 ms 311 ms 305 ms UNKNOWN-67-195-1-X.yahoo.com [67.195.1.251]
16 307 ms 309 ms 300 ms po-16.bas2-7-prd.gq1.yahoo.com [206.190.32.43]
17 303 ms 312 ms 303 ms ir1.fp.vip.gq1.yahoo.com [206.190.36.45]

Trace complete.

Result:
Thus using traceroute command, path traversed by the packet is determined.
THE KAVERY ENGINEERING COLLEGE Page :

EX. NO.: 2

CREATE SOCKET FOR HTTP FOR WEB PAGE UPLOAD AND DOWNLOAD

Aim:
To download a web page using java URL method.

Algorithm:

1. Get URL from the user.


2. Create a file instance to store the downloaded page.
3. Download the page using java URL methods.
4. View the download page
5. Stop

Program:
// DownloadPage.java

import java.io.*;
import java.net.*;

class MyDownload
{
public void Download() throws Exception
{
try
{
String WebPage, MyPage;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

// URL Instance System.out.print("Enter the URL : ");


WebPage = br.readLine();
URL url = new URL(WebPage);

// File Instance
System.out.print("Enter filename to store : ");
MyPage = br.readLine();
File Out = new File(MyPage);
FileOutputStream FOS = new FileOutputStream(Out);

// Dowload the page


InputStream in = url.openStream();
byte buf[] = new byte[1024];
int i, len;
THE KAVERY ENGINEERING COLLEGE Page :

while( (len = in.read(buf)) > 0 )


{
for(i = 0; i < len; i++)
{
FOS.write((char)buf[i]);
}
}

// Close the streams


in.close();
FOS.close();
}
catch (MalformedURLException M)
{
System.out.println(M);
}

catch (Exception E)
{
System.out.println(E);
}
}
}

class DownloadPage
{
public static void main(String args[]) throws Exception
{
String Choice;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
MyDownload MDP = new MyDownload();
MDP.Download();
System.out.println("Download complete. View the file");
}
}
THE KAVERY ENGINEERING COLLEGE Page :

Output

$ javac DownloadPage.java
$ java DownloadPage
Enter the URL :
http://www.google.co.in
Enter filename to store :
mypage.html Download complete. View
the file

Result:
Thus using java URL methods, a webpage is downloaded.
THE KAVERY ENGINEERING COLLEGE Page :

EX. NO.:3(a)
Socket Program For ECHO

AIM
To write a socket program for implementation of echo.

ALGORITHM:

CLIENT SIDE
1. Start the program.
2. Create a socket which binds the Ip address of server and the port address to acquire
service.
3. After establishing connection send a data to server.
4. Receive and print the same data from server.
5. Close the socket.
6. End the program.

SERVER SIDE
1. Start the program.
2. Create a server socket to activate the port address.
3. Create a socket for the server socket which accepts the connection.
4. After establishing connection receive the data from client.
5. Print and send the same data to client.
6. Close the socket.
7. End the program.
THE KAVERY ENGINEERING COLLEGE Page :

PROGRAM: ECHO CLIENT

// eclient.java

import java.io.*;
import java.net.*;
public class eclient
{

public static void main(String args[])


{
Socket c=null;

String line;
DataInputStream is,is1;
PrintStream os;
try
{
c=new Socket("localhost",8080);
}
catch(IOException e)
{

System.out.println(e);
}
try
{
os=new PrintStream(c.getOutputStream());
is=new DataInputStream(System.in);

is1=new DataInputStream(c.getInputStream());

do
{
System.out.println("client");
line=is.readLine(); os.println(line);
if(!line.equals("exit"))
System.out.println("server:"+is1.readLine());
}while(!line.equals("exit"));
}
catch(IOException e)
{
System.out.println("socket closed");
}
}
}
THE KAVERY ENGINEERING COLLEGE Page 15 of 65

PROGRAM: ECHO SERVER


// eserver.java

import java.io.*;
import java.net.*;
import java.lang.*;
public class eserver
{
public static void main(String args[])throws IOException
{

ServerSocket s=null;
String line;

DataInputStream is;
PrintStream ps;
Socket c=null;
try
{
s=new ServerSocket(8080);
}
catch(IOException e)
{
System.out.println(e);
}
try
{
c=s.accept();
is=new DataInputStream(c.getInputStream());
ps=new PrintStream(c.getOutputStream());
while(true)
{
line=is.readLine();
System.out.println("msg received and sent back to client");
ps.println(line);
}
}
catch(IOException e)
{
System.out.println(e);
}
}
}
THE KAVERY ENGINEERING COLLEGE Page :

OUTPUT
CLIENT:

Enter the IP address 127.0.0.1

CONNECTION ESTABLISHED
Enter the data SRM
Client received SRM

SERVER:

CONNECTION ACCEPTED
Server received SRM

RESULT:
Thus the program for simulation of echo server was written & executed
THE KAVERY ENGINEERING COLLEGE Page :

EX. NO.:3(b)
TCP Chat Server/Client

Aim
To implement a chat server and client in java using TCP sockets.

Algorithm:

Server

1. Create a server socket


2. Wait for client to be connected.
3. Read Client's message and display it
4. Get a message from user and send it to client
5. Repeat steps 3-4 until the client sends "end"
6. Close all streams
7. Close the server and client socket
8. Stop

Client

1. Create a client socket and establish connection with the server


2. Get a message from user and send it to server
3. Read server's response and display it
4. Repeat steps 2-3 until chat is terminated with "end" message
5. Close all input/output streams
6. Close the client socket
7. Stop
THE KAVERY ENGINEERING COLLEGE Page :

Program: CHAT SERVER


// TCP Chat Server--tcpchatserver.java

import java.io.*;
import java.net.*;
class tcpchatserver
{
public static void main(String args[])throws Exception
{
PrintWriter toClient;
BufferedReader fromUser, fromClient;
try
{
ServerSocket Srv = new ServerSocket(5555);
System.out.print("\nServer started\n");
Socket Clt = Srv.accept(); System.out.println("Client connected");
toClient = new PrintWriter(new BufferedWriter(new
OutputStreamWriter(Clt.getOutputStream())), true);
fromClient = new BufferedReader(new InputStreamReader(Clt.getInputStream()));
fromUser = new BufferedReader(new InputStreamReader(System.in));
String CltMsg, SrvMsg;
while(true)
{
CltMsg= fromClient.readLine();
if(CltMsg.equals("end"))
break;
else
{
System.out.println("\nServer <<< " + CltMsg);
System.out.print("Message to Client : ");
SrvMsg = fromUser.readLine();
toClient.println(SrvMsg);
}
}
System.out.println("\nClient Disconnected");
fromClient.close();
toClient.close();
fromUser.close();
Clt.close();
Srv.close();
}
catch (Exception E)
{ System.out.println(E.getMessage());
}
}}
THE KAVERY ENGINEERING COLLEGE Page :

Program: CHAT CLIENT


// TCP Chat Client--tcpchatclient.java

import java.io.*;
import java.net.*;
class tcpchatclient
{
public static void main(String args[])throws Exception
{
Socket Clt;
PrintWriter toServer;
BufferedReader fromUser, fromServer;
try
{
if (args.length > 1)
{
System.out.println("Usage: java hostipaddr");
System.exit(-1);
}
if (args.length == 0)
Clt = new Socket(InetAddress.getLocalHost(),5555);
else
Clt = new Socket(InetAddress.getByName(args[0]),5555);
toServer = new PrintWriter(new BufferedWriter(new
OutputStreamWriter(Clt.getOutputStream())), true);
fromServer = new BufferedReader(new InputStreamReader(Clt.getInputStream()));
fromUser = new BufferedReader(new InputStreamReader(System.in));
String CltMsg, SrvMsg;
System.out.println("Type \"end\" to Quit");
while (true)
{
System.out.print("\nMessage to Server : ");
CltMsg = fromUser.readLine();
toServer.println(CltMsg);
if (CltMsg.equals("end"))
break;
SrvMsg = fromServer.readLine();
System.out.println("Client <<< " + SrvMsg);
}
}
catch(Exception E)
{
System.out.println(E.getMessage());
}
}
}
THE KAVERY ENGINEERING COLLEGE Page :

Output

Server Console
$ javac tcpchatserver.java
$ java tcpchatserver
Server started
Client connected

Server <<< hi
Message to Client : hello

Server <<< how r u?


Message to Client :
fine

Server <<< me too


Message to Client : bye

Client Disconnected

Client Console
$ javac tcpchatclient.java
$ java tcpchatclient
Type "end" to Quit

Message to Server : hi
Client <<< hello

Message to Server : how r


u? Client <<< fine

Message to Server : me too


Client <<< bye

Message to Server : end

Result
Thus both the client and server exchange data using TCP socket programming.
THE KAVERY ENGINEERING COLLEGE Page :

EX. NO.:3(c)

TCP File Server/Client

Aim
To implement a file server and client in java using TCP sockets.

Algorithm

Server

1. Create a server socket


2. Wait for client to be connected.
3. Read filename from client
4. Open the file using java File methods
5. Write file contents onto stream until EOF
6. Close all streams
7. Close the server and client socket
8. Stop

Client

1. Create a client socket and establish connection with the server


2. Get filename from user and send it to server
3. Read file contents from server stream and display it
4. Close all input/output streams
5. Close the client socket
6. Stop
THE KAVERY ENGINEERING COLLEGE Page :

Program:
FileServer .java

import java.io.*;
import java.net.*;

public class FileServer


{
public static void main(String[] args) throws Exception
{
File dir;
ServerSocket ss;
Socket conn;
BufferedReader br;
PrintWriter pw;

if(args.length == 0)
dir = new File("./");
else
dir = new File(args[0]);
if(!dir.exists() || !dir.isDirectory())
{
System.out.println("Directory does not exist");
System.exit(-1);
}

try
{
ss = new ServerSocket(3210);
conn = ss.accept();
br = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
pw = new PrintWriter(conn.getOutputStream());

String name = br.readLine().trim();


File F = new File(dir, name);
if((!F.exists()) || F.isDirectory())
pw.println("File does not exists");
else
{
pw.println("\n");
BufferedReader fin = new BufferedReader(new FileReader(F));
while(true)
{
String line = fin.readLine();
if(line == null)
THE KAVERY ENGINEERING COLLEGE Page :

break;
pw.println(line);
}
System.out.println("File Transferred\n");
}
pw.flush();
pw.close();
}
catch(Exception e)
{
System.out.println("Error: " + e);
}
}
}

Program:
FileClient.java

import java.io.*;
import java.net.*;

class FileClient
{
public static void main(String args[])throws Exception
{

try
{

Socket Clt;
if (args.length == 0)
Clt = new Socket(InetAddress.getLocalHost(),3210);

else
Clt = new Socket(InetAddress.getByName(args[0]),3210);

PrintWriter OS =new PrintWriter(new BufferedWriter(new


OutputStreamWriter(Clt.getOutputStream())), true);
BufferedReader IS = new BufferedReader(new InputStreamReader(Clt.getInputStream()));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String CltMsg, SrvMsg;

System.out.print("\nFilename : ");
CltMsg = br.readLine();
THE KAVERY ENGINEERING COLLEGE Page :

OS.println(CltMsg);

while ((SrvMsg = IS.readLine()) != null)


System.out.println(SrvMsg);
}
catch(Exception E)
{
System.out.println(E.getMessage());
}
}
}

Output

Server Console
$ javac FileServer.java
$ java FileServer
File Transferred

Client Console

$ javac FileClient.java
$ java FileClient
Filename : hello.java

import java.io.*;
class hello
{
public static void main(String args[])
{
System.out.println("hello");
}
}

Result:
Thus file contents was sent from server to client using TCP socket programming.
THE KAVERY ENGINEERING COLLEGE Page :

EX.NO.: 4
UDP DNS Server/Client

Aim
To implement a DNS server and client in java using UDP sockets.

Algorithm

Server

1. Define a array of hosts and its corresponding IP address in another array


2. Create a datagram socket
3. Create a datagram packet to receive client request
4. Read the domain name from client to be resolved
5. Lookup the host array for the domain name
6. If found then retrieve corresponding address
7. Construct a datagram packet to send response back to the client
8. Repeat steps 3-7 to resolve further requests from clients
9. Close the server socket
10. Stop

Client

1.Create a datagram socket


2.Get domain name from user
3.Construct a datagram packet to send domain name to the server
4.Create a datagram packet to receive server message
5.If it contains IP address then display it, else display "Domain does not exist"
6.Close the client socket
7.Stop
THE KAVERY ENGINEERING COLLEGE Page :

Program:
udpdnsserver .java

import java.io.*;
import java.net.*;

public class udpdnsserver


{
private static int indexOf(String[] array, String str)
{
str = str.trim();
for (int i=0; i < array.length; i++)
{
if (array[i].equals(str))
return i;
}
return -1;
}

public static void main(String arg[])throws IOException


{
String[] hosts = {"yahoo.com", "gmail.com", "cricinfo.com", "facebook.com"};
String[] ip = {"68.180.206.184", "209.85.148.19", "80.168.92.140", "69.63.189.16"};
System.out.println("Press Ctrl + C to Quit");

while (true)
{
DatagramSocket serversocket=new DatagramSocket(1362);
byte[] senddata = new byte[1021];
byte[] receivedata = new byte[1021];

DatagramPacket recvpack = new DatagramPacket(receivedata, receivedata.length);


serversocket.receive(recvpack);
String sen = new String(recvpack.getData());
InetAddress ipaddress = recvpack.getAddress();
int port = recvpack.getPort();
String capsent;
System.out.println("Request for host " + sen);

if(indexOf (hosts, sen) != -1)


capsent = ip[indexOf (hosts, sen)];
else
capsent = "Host Not Found";
senddata = capsent.getBytes();
DatagramPacket pack = new DatagramPacket(senddata, senddata.length,ipaddress,port);
serversocket.send(pack);
THE KAVERY ENGINEERING COLLEGE Page :

serversocket.close();
}
}
}

Program:
udpdnsclient.java

import java.io.*;
import java.net.*;

public class udpdnsclient


{
public static void main(String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientsocket = new DatagramSocket();
InetAddress ipaddress;
if (args.length == 0)
ipaddress = InetAddress.getLocalHost();
else
ipaddress = InetAddress.getByName(args[0]);
byte[] senddata = new byte[1024];
byte[] receivedata = new byte[1024];
int portaddr = 1362;

System.out.print("Enter the hostname : ");


String sentence = br.readLine();
senddata = sentence.getBytes();
DatagramPacket pack = new DatagramPacket(senddata, senddata.length,
ipaddress,portaddr);
clientsocket.send(pack);

DatagramPacket recvpack =new DatagramPacket(receivedata, receivedata.length);


clientsocket.receive(recvpack);
String modified = new String(recvpack.getData());
System.out.println("IP Address: " + modified);
clientsocket.close();
}
}
THE KAVERY ENGINEERING COLLEGE Page :

Output

Server Console
$ javac udpdnsserver.java
$ java
udpdnsserver
Press Ctrl + C to
Quit Request for
host yahoo.com

Client Console
$ javac udpdnsclient.java
$ java udpdnsclient
Enter the hostname : yahoo.com
IP Address: 68.180.206.184

Result:
Thus domain name requests by the client are resolved into their respective logical
address using lookup method.
THE KAVERY ENGINEERING COLLEGE Page :

EX. NO.:5(a)
ARP Client/Server

Aim:
To know the physical address of a host when its logical address is known using
ARP protocol.

Algorithm:

Target/Server
1. Create a server socket.
2. Accept client connection.
3. Read IP address from the client request
4. Check its configuration file and compare with its logical address.
5. If there is a match, send the host physical address.
6. Stop

Client
1.Create a socket.
2.Send IP address to the target machine
3.Receive target's response
4.If it is a MAC address then display it and go to step 6
5.Display "Host not found"
6.Stop
THE KAVERY ENGINEERING COLLEGE Page :

Program:
Client: Clientarp.java

import java.io.*;
import java.net.*;
import java.util.*;
class Clientarp
{
public static void main(String args[])
{
try
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));

Socket clsct=new Socket("127.0.0.1",139);


DataInputStream din=new DataInputStream(clsct.getInputStream());
DataOutputStream dout=new DataOutputStream(clsct.getOutputStream());
System.out.println("Enter the Logical address(IP):");
String str1=in.readLine();
dout.writeBytes(str1+'\n');
String str=din.readLine();
System.out.println("The Physical Address is: "+str);
clsct.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}

Server:

import java.io.*;
import java.net.*;
import java.util.*;
class Serverarp
{
public static void main(String args[])
{
try
{
ServerSocket obj=new ServerSocket(139);
Socket obj1=obj.accept();
THE KAVERY ENGINEERING COLLEGE Page :

while(true)
{
DataInputStream din=new DataInputStream(obj1.getInputStream());
DataOutputStream dout=new DataOutputStream(obj1.getOutputStream());
String str=din.readLine();
String ip[]={"165.165.80.80","165.165.79.1"};
String mac[]={"6A:08:AA:C2","8A:BC:E3:FA"};
for(int i=0;i<ip.length;i++)
{
if(str.equals(ip[i]))
{
dout.writeBytes(mac[i]+'\n');
break;
}
}
obj.close();
}

}
catch(Exception e)
{
System.out.println(e);
}
}
}

Output:
E:\networks>java Serverarp
E:\networks>java Clientarp
Enter the Logical address(IP):
165.165.80.80
The Physical Address is: 6A:08:AA:C2

Result:
Thus using ARP protocol, server’s MAC address is obtained.
THE KAVERY ENGINEERING COLLEGE Page :

EX. NO.:5(b)
RARP Client/Server
Aim:
To know the logical address of a host when its physical address is known using RARP
protocol.

Algorithm:

Target/Server
1. Create a server socket.
2. Accept client connection.
3. Read MAC address from the client request
4. Check its configuration file and compare with its physical address.
5. If there is a match, send the host logical address.
6. Stop

Client
1. Create a socket.
2. Send physical address to the target machine
3. Receive target's response
4. If it is a IP address then display it and go to step 6
5. Display "Host not found"
6. Stop
THE KAVERY ENGINEERING COLLEGE Page :

Program:
Client: Clientrarp.java

import java.io.*;
import java.net.*;
import java.util.*;
class Clientrarp
{
public static void main(String args[])
{
try
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
Socket clsct=new Socket("127.0.0.1",139);

DataInputStream din=new DataInputStream(clsct.getInputStream());


DataOutputStream dout=new DataOutputStream(clsct.getOutputStream());
System.out.println("Enter the Physical Addres (MAC):");
String str1=in.readLine();
dout.writeBytes(str1+'\n');
String str=din.readLine();
System.out.println("The Logical address is(IP): "+str);
clsct.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}

Server: Serverrarp.java

import java.io.*;
import java.net.*;
import java.util.*;
class Serverrarp
{
public static void main(String args[])
{
try
{
ServerSocket obj=new ServerSocket(139);
Socket obj1=obj.accept();
THE KAVERY ENGINEERING COLLEGE Page :

while(true)
{
DataInputStream din=new DataInputStream(obj1.getInputStream());
DataOutputStream dout=new DataOutputStream(obj1.getOutputStream());
String str=din.readLine();
String ip[]={"165.165.80.80","165.165.79.1"};
String mac[]={"6A:08:AA:C2","8A:BC:E3:FA"};
for(int i=0;i<mac.length;i++)
{
if(str.equals(mac[i]))
{
dout.writeBytes(ip[i]+'\n');
break;
}
}
obj.close();
}

}
catch(Exception e)
{
System.out.println(e);
}
}
}

Output:
E:\networks>java Serverrarp
E:\networks>java Clientrarp
Enter the Physical Address (MAC):
6A:08:AA:C2
The is Logical address(IP): 165.165.80.80

Result:
Thus using RARP protocol, IP address of the server is obtained.
THE KAVERY ENGINEERING COLLEGE Page :

EX. NO.:6(a)
Study of Network Simulator (NS)

Introduction

Network Simulator (Version 2), widely known as NS2, is simply an event


driven simulation tool that has proved useful in studying the dynamic nature of
communication networks. Simulation of wired as well as wireless network functions
and protocols (e.g., routing algorithms, TCP, UDP) can be done using NS2. In general,
NS2 provides users with a way of specifying such network protocols and simulating
their corresponding behaviors. Due to its flexibility and modular nature, NS2 has
gained constant popularity in the networking research community since its birth in
1989. Ever since, several revolutions and revisions have marked the growing maturity
of the tool, thanks to substantial contributions from the players in the field. Among
these are the University of California and Cornell University who developed the
REAL network simulator,1 the foundation which NS is based on.

Since 1995 the Defense Advanced Research Projects Agency (DARPA)


supported development of NS through the Virtual Inter Network Test bed (VINT)
project. Currently the National Science Foundation (NSF) has joined the ride in
development. Last but not the least, the group of Researchers and developers in the
community are constantly working to keep NS2 strong and versatile.

Basic Architecture

Figure 6.1 shows the basic architecture of NS2. NS2 provides users with
anexecutable command ns
THE KAVERY ENGINEERING COLLEGE Page :

which take on input argument, the name of a Tcl simulation scripting file. Users
are feeding the name of a Tcl simulation script (which sets up a simulation) as an input
argument of an NS2 executable command ns.

In most cases, a simulation trace file is created, and is used to plot graph
and/or to create animation. NS2 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 objects as well as scheduling discrete events (i.e., a
frontend).

The C++ and the OTcl are linked together using TclCL. Mapped to a C++ object,
variables in the OTcl domains are sometimes referred to as handles. Conceptually, a
handle (e.g., n as a Node handle) is just a string (e.g.,_o10) in the OTcl domain, and
does not contain any functionality. Instead, the functionality (e.g., receiving a packet) is
defined in the mapped C++ object (e.g., of class Connector). In the OTcl domain, a
handle acts as a frontend which interacts with users and other OTcl objects. It may
defines its own procedures and variables to facilitate the interaction. Note that the
member procedures and variables in the OTcl domain are called instance procedures
(instprocs) and instance variables (instvars), respectively. Before proceeding further, the
readers are encouraged to learn C++ and OTcl languages. We refer the readers to [14] for
the detail of C++, while a brief tutorial of Tcl and OTcl tutorial are given in Appendices
A.1 and A.2, respectively.

NS2 provides a large number of built-in C++ objects. It is advisable to use these
C++ objects to set up a simulation using a Tcl simulation script. However, advance users
may find these objects insufficient. They need to develop their own C++ objects, and use
a OTcl configuration interface to put together these objects. After simulation, NS2
outputs either text-based or animation-based simulation results. To interpret these results
graphically and interactively, tools such as NAM (Network AniMator) and XGraph are
used. To analyze a particular behavior of the network, users can extract a relevant subset
of text-based data and transform it to a more conceivable presentation.
THE KAVERY ENGINEERING COLLEGE Page :

CONCEPT OVERVIEW

NS uses two languages because simulator has two different kinds of things it needs to do.
On one hand, a detailed simulation of protocols requires a systems programming language
which can efficiently

manipulate bytes, packet headers, and implement algorithms that run over large
data sets. For these tasks run-time speed is important and turn-around time (run
simulation, find bug, fix bug, recompile, re- run) is less important. On the other hand, a
large part of network research involves slightly varying parameters or configurations, or
quickly exploring a number of scenarios.

In these cases, iteration time (change the model and re-run) is more important.
Since configuration runs once (at the beginning of the simulation), run-time of this part
of the task is less important. NS meets both of these needs with two languages, C++ and
OTcl.

SIMULATOR INITIALIZATION

When a new simulation object is created in tcl, the initialization procedure


performs the following operations:

• initialize the packet format (calls create_packetformat)

• create a scheduler (defaults to a calendar scheduler)

• create a “null agent” (a discard sink used in various places)

SCHEDULERS AND EVENTS

The simulator is an event-driven simulator. There are presently four schedulers


available in the simulator, each of which is implemented using a different data
structure: a simple linked-list, heap, calendar queue (default), and a special type call
called “real-time”. Each of these is described below.

The scheduler runs by selecting the next earliest event, executing it to completion
and returning to execute the next event. Unit of time used by scheduler is seconds.
Presently, the simulator is single- threaded and only one event in execution at any
given time. If more than one event are scheduled to execute at the same time, their
THE KAVERY ENGINEERING COLLEGE Page :

execution is performed on the first scheduled – first dispatched manner. Simultaneous


events are not reordered anymore by schedulers (as it was in earlier versions) and all
schedulers should yield the same order of dispatching given the same input.

NODE BASICS

The basic primitive for creating a node is set ns [new Simulator] $ns node
The instance procedure node constructs a node out of simpler classifier objects
(Section 5.4). The Node itself is a standalone class in OTcl. However, most of the
components of the node are themselves

TclObjects. The typical structure of a (unicast) node is as shown in Figure 5.1. This
simple structure consists of two TclObjects: an address classifer (classifer_) and a port
classifier (dmux_). The function of these classifiers is to distribute incoming packets to
the correct agent or outgoing link.
All nodes contain at least the following components:

• An address or id_, monotonically increasing by 1 (from initial value 0) across


the simulation namespace as nodes are created,

• A list of neighbors (neighbor_),


BASIC COMMANDS IN NS2

Set ns [new Simulator]: generates an NS simulator object instance, and assigns it


to variable ns.The
"Simulator" objects has member functions that

do the following: Create compound objects such

as nodes and links (described later) Connect

network component objects created (ex. attach-

agent)

Set network component parameters (mostly for compound objects)

Create connections between agents (ex. make connection between a "tcp" and "sink")
THE KAVERY ENGINEERING COLLEGE Page :

Specify NAM display options

Most of member functions are for simulation setup (referred to as plumbing functions in
the Overview section) and scheduling, however some of them are for the NAM display.
The "Simulator" object member function implementations are located in the
"ns-2/tcl/lib/ns-lib.tcl"file.

$ns color fid color: is to set color of the packets for a flow specified by the flow id (fid).
This member function of "Simulator" object is for the NAM display, and has no effect on
the actual simulation.

$ns namtrace-all file-descriptor: This member function tells the simulator to record
simulation traces in NAM input format. It also gives the file name that the trace will be
written to later by the command $ns flush-trace. Similarly, the member function trace-all is
for recording the simulation trace in a general
format.

Procfinish {}: is called after this simulation is over by the command $ns at 5.0
"finish". In this function, post-simulation processes are specified.

setn0 [$ns node]: The member function node creates a node. A node in NS is
compound object made of address and port classifiers (described in a later section).
Users can create a node by separately creating an address and a port classifier objects
and connecting them together. However, this member function of Simulator object
makes the job easier. To see how a node is created, look at the files: "ns-
2/tcl/libs/ns-lib.tcl"andns-2/tcl/libs/ns-node.tcl".

$ns duplex-link node1 node2 bandwidth delay queue-type: creates two simplex
links of specified bandwidth and delay, and connects the two specified nodes. In NS, the
output queue of a node isimplemented as a part of a link; therefore users should specify
the queue-type when creating links. In the above simulation script, DropTail queue is
used. If the reader wants to use a RED queue, simply replace the word DropTail with
RED. The NS implementation of a link is shown in a later section. Like a node, a link is
THE KAVERY ENGINEERING COLLEGE Page :

a compound object, and users can create its sub-objects and connect them and the
nodes. Link source codes can be found in "ns-2/tcl/libs/ns-lib.tcl" and "ns-2/tcl/libs/ns-
link.tcl" files. One thing to note is that you can insert error modules in a link component
to simulate a lossy link (actually users can make and insert any network objects). Refer
to the NS documentation to find out how to do this.

$ns queue-limit node1 node2 number: This line sets the queue limit of the two
simplex links that connect node1 and node2 to the number specified. At this point, the
authors do not know how many of these kinds of member functions of Simulator objects
are available and what they are. Please take a look at "ns-2/tcl/libs/ns-lib.tcl" and "ns-
2/tcl/libs/ns-link.tcl", or NS.

$ns duplex-link-op node1 node2 ...: The next couple of lines are used for the
NAM display. To see the effects of these lines, users can comment these lines out and try
the simulation.

Now that the basic network setup is done, the next thing to do is to setup traffic agents
such as TCP and UDP, traffic sources such as FTP and CBR, and attach them to nodes
and agents respectively.

settcp [new Agent/TCP]: This line shows how to create a TCP agent. But in
general, users can create any agent or traffic sources in this way. Agents and traffic
sources are in fact basic objects (not compound objects), mostly implemented in C++
and linked to OTcl. Therefore, there are no specific Simulator object member
functions that create these object instances.
To create agents or traffic sources, a user should know the class names these objects
(Agent/TCP,

Agnet/TCPSink, Application/FTP and so on). This information can be found in


the NS documentation or partly in this documentation. But one shortcut is to look at the
"ns2/tcl/libs/ns- default.tcl" file. This file contains the default configurable parameter
value settings for available network objects. Therefore, it works as a good indicator of
what kind of network objects are available in NS and what are the configurable
parameters.

$ns attach-agent node agent: The attach-agent member function attaches an agent
THE KAVERY ENGINEERING COLLEGE Page :

object created to a node object. Actually, what this function does is call the attach
member function of specified node, which attaches the given agent to itself.
Therefore, a user can do the same thing by, for example, $n0 attach $tcp. Similarly,
each agent object has a member function.

$ns connect agent1 agent2: After two agents that will communicate with each
other are created, the next thing is to establish a logical network connection between
them. This line establishes a network connection by setting the destination address to
each others' network and port address pair.

Assuming that all the network configuration is done, the next thing to do is write a
simulation scenario (i.e. simulation scheduling). The Simulator object has many
scheduling member functions. However, the one that is mostly used is the following:

$ns at time "string": This member function of a Simulator object makes the
scheduler (scheduler_ is the variable that points the scheduler object created by [new
Scheduler] command at the beginning of the script) to schedule the execution of the
specified string at given simulation time.

After all network configuration, scheduling and post-simulation procedure


specifications are done, the only thing left is to run the simulation. This is done by $ns
run.
Installation Procedures for NS-2 (ns-allinone- 2.34)
Download NS-2.34 from the following link: This also includes installation guidelines

http://nsnam.isi.edu/nsnam/index.php/Downloading_and_installing_ns-2

After downloading, copy of ns-allinone-2.34.tar.gz from above link, the following steps
executed:

% tar -xzf ns-allinone-2.34.tar.gz


% cd ns-allinone-2.34

% ./install
Once following message comes:
Nam has been installed successfully.
Ns-allinone package has been installed successfully.
THE KAVERY ENGINEERING COLLEGE Page :

(Note: In case there is a failure, as it happens with me, you first need to check what Linux
platform you
are using. In my case it is Ubuntu-9.10 version. And in such case you need to provide the
UNIX command
and make some modification in „configuration‟ file as suggested in following link:
http://lotti.netsons.org/2009/12/install-ns-allinone-2-34-on-ubuntu-9-10/
Then again type following command: (under directory: /ns-allinone-2.34)
% ./install
This hopefully will complete successful installation and he below message will come.
Nam has been installed successfully.
Ns-allinone package has been installed successfully.

Next step is to link LD_LIBRARY_PATH environment variable by giving following


commands: (if you
are using „sh‟ or „bash‟ – as in my case).

%export LD-LIRARY-PATH=/home/raja/NS2/ ns-allinone-2.34/bin


%export LD-LIRARY-PATH=/home/raja/NS2/ ns-allinone-2.34/lib
%export TCL-LIRARY=/home/raja/NS2/ ns-allinone-2.34/tcl8.4.11/library

OR (if you are using „cshrc‟)


%setenv LD-LIRARY-PATH /home/raja/NS2/ ns-allinone-2.34/bin
%setenv LD-LIRARY-PATH /home/raja/NS2/ ns-allinone-2.34/lib
%setenv TCL-LIRARY /home/raja/NS2/ ns-allinone-2.34/tcl8.4.11/library

Then give command:


% cd ns-2.34
% ./validate
This will complete the successful installation.
THE KAVERY ENGINEERING COLLEGE Page :

EX. NO.:6(b)

SIMULATION OF CONGESTION CONTROL ALGORITHM USING NS2


OBJECTIVE
Acquire TCL scripting skills to Implement and simulate congestion control using NS2
simulator.
ALGORITHM
Step 1: Start the program
Step 2: Create the trace file and NAM file. Step 3: Setup the topology object
Step 4: Create nodes and set duplex links between the nodes. Step 5: Create nodes and
attach them to the queue, DROPTAIL
Step 6: Configure the nodes and provides initial location of nodes. Generation of
movements is done.
Step 7: Setup a TCP Connection between nodes
Step 8: Define a initialize positions for the nam window. Step 9: Telling nodes when the
simulation ends
Step 10: Ending nam and the simulation

PROGRAM

set ns [new Simulator]


set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]

set n5 [$ns node]

$n0 color "purple"


$n1 color "purple"
$n2 color "violet"
THE KAVERY ENGINEERING COLLEGE Page :

$n3 color "violet"


$n4 color "chocolate"
$n5 color "chocolate"

set f [open stopwait.tr w]


$ns trace-all $f
set nf [open stopwait.nam w]
$ns namtrace-all $nf
$ns at 0.0 "$n0 label SYS0"

$ns at 0.0 "$n1 label SYS1"


$ns at 0.0 "$n2 label SYS2"
$ns at 0.0 "$n3 label SYS3"
$ns at 0.0 "$n4 label SYS4"
$ns at 0.0 "$n5 label SYS5"

$ns duplex-link $n0 $n2 0.2Mb 20ms DropTail


$ns duplex-link $n1 $n2 0.2Mb 20ms DropTail
$ns duplex-link $n2 $n3 0.2Mb 20ms DropTail
$ns duplex-link $n3 $n4 0.2Mb 20ms DropTail
$ns duplex-link $n3 $n5 0.2Mb 20ms DropTail

$ns duplex-link-op $n0 $n2 orient right-down


$ns duplex-link-op $n1 $n2 orient right-up
$ns duplex-link-op $n2 $n3 orient right
$ns duplex-link-op $n3 $n4 orient right-up
$ns duplex-link-op $n3 $n5 orient right-down
$ns queue-limit $n0 $n2 10

Agent/TCP
set_nam_tracevar_true
set tcp [new
Agent/TCP]
$tcp set window 1
$tcp set maxcwnd 1
$tcp set fid 1

$ns attach-agent $n0 $tcp

set sink [new Agent/TCPSink]


$ns attach-agent $n5 $s ink
THE KAVERY ENGINEERING COLLEGE Page :

$ns connect $tcp $sink


set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ns add-agent-trace $tcp tcp
$ns monitor-agent-trace $tcp
$tcp tracevar cwnd
$ns at 0.1 "$ftp start"
$ns at 0.53 "$ns queue-limit $n3 $n5 0"

$ns at 0.80 "$ns queue-limit $n3 $n5 5"


$ns at 2.0 "$ns detach-agent $n0 $tcp ; $ns detach-agent $n5 $sink"
$ns at 2.5 "finish"

#$ns at 0.0 "$ns trace-annotate \"STOPWAIT\""


$ns at 0.01 "$ns trace-annotate \"FTP starts at 0.01\""
$ns at 0.10 "$ns trace-annotate \"Send Request SYS0 to SYS5\""
$ns at 0.18 "$ns trace-annotate \"Receive Request SYS5 to SYS0\""
$ns at 0.24 "$ns trace-annotate \"Send Packet_0 SYS0 to SYS5\""
$ns at 0.42 "$ns trace-annotate \"Receive Ack_0\""
$ns at 0.48 "$ns trace-annotate \"Send Packet_1\""
$ns at 0.60 "$ns trace-annotate \"Disconnect N2 So loss the packet1\""
$ns at 0.67 "$ns trace-annotate \"Waiting for Ack_1\""
$ns at 0.95 "$ns trace-annotate \"Send Packet_1 again\""
$ns at 1.95 "$ns trace-annotate \"Deattach SYS3,Packet_1 again\""
$ns at 2.09 "$ns trace-annotate \"Receive Ack_1\""
$ns at 2.10 "$ns trace-annotate \"SEnd Packet_2\""
$ns at 2.38 "$ns trace-annotate \"Receive Ack_2\""
$ns at 2.5 "$ns trace-annotate \"FTP stops\""
proc finish {}
{
global ns nf
$ns flush-trace
close $nf

exec nam stopwait.nam &


exit 0
}
$ns run
THE KAVERY ENGINEERING COLLEGE Page :

OUTPUT

STOP WAIT PROTOCOL

CONCLUSION
Thus tcl programs were executed to simulate the performance of stop wait protocol
using ns2.
THE KAVERY ENGINEERING COLLEGE Page :

Exp# 7a Study of TCP Performance


Date:

Aim
To study the performance of a TCP network with droptail queue mechanism
on the gateway

Algorithm
1. Create a simulator object
2. Define different flows for data flows
3. Trace all events in a nam file and text file
4. Create source nodes (s1, s2, s3), gateway (G) and receiver (r)
5. Describe their layout topology
6. Specify the link between nodes
7. Define the queue size between nodes G and r as 5
8. Monitor queue on all links vertically 90°
9. Create TCP agents tcp1, tcp2, tcp3 and attach it to nodes s1, s2 and s3
respectively
10. Create three TCP sinks and attach it to node r
11. Connect traffic sources to the sink
12. Create FTP agents ftp1, ftp2, ftp3 and attach it to tcp1, tcp2 and tcp3
respectively
13. Label the nodes at start time
14. Schedule ftp1, ftp2, ftp3 to start at 0.1 and stop at 5.0 seconds
15. Call finish procedure at 5.25 seconds
16. Run the simulation
17. Execute NAM on the trace file
18. Observe the simulated events on the NAM editor and packet flow on link G to
r
19. View the trace file and analyse the events
THE KAVERY ENGINEERING COLLEGE Page :

Program

#Study of TCP performance - TCP.tcl

#Create a simulator
object set ns [new
Simulator]

#Open trace files


set f [open droptail-queue-out.tr w]
$ns trace-all $f

#Open the nam trace file


set nf [open droptail-queue-out.nam w]
$ns namtrace-all $nf

#s1, s2 and s3 act as


sources. set s1 [$ns node]
set s2 [$ns node]
set s3 [$ns node]

#G acts as a
gateway set G [$ns
node]
#r acts as a receiver
set r [$ns node]

#Define different colors for data flows


$ns color 1 red
$ns color 2 SeaGreen
$ns color 3 blue

#Create links between the nodes


$ns duplex-link $s1 $G 6Mb 10ms DropTail
$ns duplex-link $s2 $G 6Mb 10ms DropTail
$ns duplex-link $s3 $G 6Mb 10ms DropTail
$ns duplex-link $G $r 3Mb 10ms DropTail

#Define the layout of the nodes


$ns duplex-link-op $s1 $G orient right-up
$ns duplex-link-op $s2 $G orient right
$ns duplex-link-op $s3 $G orient right-down
$ns duplex-link-op $G $r orient right
THE KAVERY ENGINEERING COLLEGE Page :

#Define the queue size for the link between node G and r
$ns queue-limit $G $r 5

#Monitor the queues for links vertically


$ns duplex-link-op $s1 $G queuePos 0.5
$ns duplex-link-op $s2 $G queuePos 0.5
$ns duplex-link-op $s3 $G queuePos 0.5
$ns duplex-link-op $G$r queuePos 0.5

#Create a TCP agent and attach it to node


s1 set tcp1 [new Agent/TCP/Reno]
$ns attach-agent $s1 $tcp1
$tcp1 set window_ 8
$tcp1 set fid_ 1

#Create a TCP agent and attach it to node


s2 set tcp2 [new Agent/TCP/Reno]
$ns attach-agent $s2 $tcp2
$tcp2 set window_ 8
$tcp2 set fid_ 2

#Create a TCP agent and attach it to node


s3 set tcp3 [new Agent/TCP/Reno]
$ns attach-agent $s3 $tcp3
$tcp3 set window_ 4
$tcp3 set fid_ 3

#Create TCP sink agents and attach them to


node r set sink1 [new Agent/TCPSink]
set sink2 [new Agent/TCPSink]
set sink3 [new Agent/TCPSink]
$ns attach-agent $r $sink1
$ns attach-agent $r $sink2
$ns attach-agent $r $sink3

#Connect the traffic sources with the traffic sinks


$ns connect $tcp1 $sink1
$ns connect $tcp2 $sink2
$ns connect $tcp3 $sink3

#Create FTP applications and attach them to


agents set ftp1 [new Application/FTP]
$ftp1 attach-agent $tcp1
set ftp2 [new Application/FTP]
$ftp2 attach-agent $tcp2
set ftp3 [new Application/FTP]
THE KAVERY ENGINEERING COLLEGE Page :

$ftp3 attach-agent $tcp3

#Define a 'finish'
procedure proc finish {} {
global ns
$ns flush-trace
puts "running
nam..."
exec nam -a droptail-queue-out.nam &
exit 0
}

#Define label for nodes


$ns at 0.0 "$s1 label Sender1"
$ns at 0.0 "$s2 label Sender2"
$ns at 0.0 "$s3 label Sender3"
$ns at 0.0 "$G label Gateway"
$ns at 0.0 "$r label Receiver"

#Schedule ftp events


$ns at 0.1 "$ftp1 start"
$ns at 0.1 "$ftp2 start"
$ns at 0.1 "$ftp3 start"
$ns at 5.0 "$ftp1 stop"
$ns at 5.0 "$ftp2 stop"
$ns at 5.0 "$ftp3 stop"

#Call finish procedure after 5 seconds of simulation time


$ns at 5.25 "finish"

#Run the simulation


$ns run
THE KAVERY ENGINEERING COLLEGE Page :

Output

$ ns TCP.tcl

Result
Thus the behaviour of TCP was observed and the basic terminologies of
TCP transmission were understood.
THE KAVERY ENGINEERING COLLEGE Page :

Exp# 7b Study of UDP Performance


Date:

Aim
To study the performance of UDP by simulating a simple network

Algorithm
1. Create a simulator object
2. Define different color for data flows
3. Trace all events in a nam file.
4. Create four nodes n0, n1, n2 and n3
5. Describe their layout topology
6. Specify the link capacity between nodes
7. Monitor queue on the link n2 to n3 vertically 90°
8. Create a UDP agents udp0, udp1 and attach it to nodes n0 and n1 respectively
9. Create a CBR traffic cbr0, cbr1 and attach it to udp0 and udp1 respectively
10. Create a traffic sink and attach it to node n3
11. Connect sources to the sink
12. Label the nodes
13. Schedule cbr0 to start at 0.5 and stop at 4.5 seconds
14. Schedule cbr1 to start at 1.0 and stop at 4.0 seconds
15. Call finish procedure at 5.0 seconds
16. Run the simulation
17. Execute NAM on the trace file
18. Observe simulated events on the NAM and packet flow on link n2 to n3
19. Stop
THE KAVERY ENGINEERING COLLEGE Page :

Program

#Study of UDP performance - UDP.tcl

#Create a simulator
object set ns [new
Simulator]

#Define different colors for data flows


$ns color 1 Blue
$ns color 2 Red

#Open the nam trace


file set nf [open
out.nam w]
$ns namtrace-all $nf

#Create four
nodes set n0 [$ns
node] set n1 [$ns
node] set n2 [$ns
node] set n3 [$ns
node]

#Create links between the nodes


$ns duplex-link $n0 $n2 1Mb 10ms DropTail
$ns duplex-link $n1 $n2 1Mb 10ms DropTail
$ns duplex-link $n3 $n2 1Mb 10ms SFQ

#Specify layout of nodes


$ns duplex-link-op $n0 $n2 orient right-down
$ns duplex-link-op $n1 $n2 orient right-up
$ns duplex-link-op $n2 $n3 orient right

#Monitor the queue for the link 2ņ3 vertically


$ns duplex-link-op $n2 $n3 queuePos 0.5

#Create a UDP agent and attach it to node


n0 set udp0 [new Agent/UDP]
$udp0 set class_ 1
$ns attach-agent $n0 $udp0

# Create a CBR traffic source and attach it to


udp0 set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
THE KAVERY ENGINEERING COLLEGE Page :

$cbr0 attach-agent $udp0

#Create a UDP agent and attach it to node


n1 set udp1 [new Agent/UDP]
$udp1 set class_ 2
$ns attach-agent $n1 $udp1

# Create a CBR traffic source and attach it to


udp1 set cbr1 [new Application/Traffic/CBR]
$cbr1 set packetSize_ 500
$cbr1 set interval_ 0.005
$cbr1 attach-agent $udp1

#Create a Null agent (a traffic sink) and attach it to


node n3 set null0 [new Agent/Null]
$ns attach-agent $n3 $null0

#Connect traffic sources with the traffic sink


$ns connect $udp0 $null0
$ns connect $udp1 $null0

#Define finish
procedure proc finish
{} {
global ns nf
$ns flush-trace

#Close the trace


file close $nf

#Execute nam on the trace


file exec nam -a out.nam &
exit 0
}

#Define label for nodes


$ns at 0.0 "$n0 label Sender1"
$ns at 0.0 "$n1 label Sender2"
$ns at 0.0 "$n2 label Router"
$ns at 0.0 "$n3 label Receiver"

#Schedule events for the CBR agents


$ns at 0.5 "$cbr0 start"
$ns at 1.0 "$cbr1 start"
$ns at 4.0 "$cbr1 stop"
$ns at 4.5 "$cbr0 stop"
THE KAVERY ENGINEERING COLLEGE Page :

#Call finish procedure after 5 seconds of simulation time


$ns at 5.0 "finish"

#Run the simulation


$ns run

Output

$ ns UDP.tcl

Result
Thus the behaviour of UDP was observed and the basic terminologies of UDP
transmission were understood.
THE KAVERY ENGINEERING COLLEGE Page :

EX.NO.:8(a)

SIMULATION OF LINK STATE ROUTING PROTOCOL USING NS2

OBJECTIVE

Acquire tcl scripting skills to simulate link state routing protocol using NS2
simulator.

PROGRAM

set ns [new Simulator]


set nr [open thro.tr w]
$ns trace-all $nr
set nf [open thro.nam w]

$ns namtrace-all
$nf proc finish { } { global ns nr nf
$ns flush-trace close $nf
close $nr
exec nam thro.nam &
exit 0
}
for { set i 0 } { $i < 12} { incr i 1 } {
set n($i) [$ns node]}
for {set i 0} {$i < 8} {incr i} {
$ns duplex-link $n($i) $n([expr $i+1]) 1Mb 10ms DropTail }

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


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

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

set udp0 [new Agent/UDP]


$ns attach-agent $n(0) $udp0
THE KAVERY ENGINEERING COLLEGE Page :

set cbr0 [new Application/Traffic/CBR]


$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-
agent $udp0 set
null0 [new
Agent/Null]
$ns attach-agent $n(5) $null0
$ns connect $udp0 $null0

set udp1 [new Agent/UDP]


$ns attach-agent $n(1) $udp1
set cbr1 [new Application/Traffic/CBR]
$cbr1 set packetSize_ 500
$cbr1 set interval_ 0.005
$cbr1 attach-
agent $udp1 set
null0 [new
Agent/Null]
$ns attach-agent $n(5) $null0
$ns connect $udp1 $null0
$ns rtproto LS
$ns rtmodel-at 10.0 down $n(11) $n(5)
$ns rtmodel-at 15.0 down $n(7) $n(6)
$ns rtmodel-at 30.0 up $n(11) $n(5)
$ns rtmodel-at 20.0 up $n(7) $n(6)
$udp0 set fid_ 1
$udp1 set fid_ 2
$ns color 1 Red
$ns color 2 Green
$ns at 1.0 "$cbr0 start"
$ns at 2.0 "$cbr1 start"
$ns at 45 "finish"
$ns run
THE KAVERY ENGINEERING COLLEGE Page :

OUTPUT

CONCLUSION
Thus tcl programs were executed to simulate the performance of link state routing protocol
using ns2
THE KAVERY ENGINEERING COLLEGE Page :

Exp# 8b
SIMULATION OF DISTANCE VECTOR ROUTING PROTOCOL USING
NS2
OBJECTIVE

Acquire tcl scripting skills to simulate distance vector routing protocol using NS2
simulator.

PROGRAM
set ns [new Simulator]
set nf [open out.nam w]
$ns namtrace-all $nf set tr [open out.tr w]
$ns trace-all $tr

proc finish {}
{
global nf ns tr
$ns flush-trace close $tr
exec nam out.nam &
exit 0
}

set n0 [$ns node] set n1 [$ns node] set n2 [$ns node] set n3 [$ns node]

$ns duplex-link $n0 $n1 10Mb 10ms DropTail


$ns duplex-link $n1 $n3 10Mb 10ms DropTail
$ns duplex-link $n2 $n1 10Mb 10ms DropTail

$ns duplex-link-op $n0 $n1 orient right-down


$ns duplex-link-op $n1 $n3 orient right
$ns duplex-link-op $n2 $n1 orient right-up

set tcp [new Agent/TCP]


$ns attach-agent $n0 $tcp

set ftp [new Application/FTP]


$ftp attach-agent $tcp

set sink [new Agent/TCPSink]


$ns attach-agent $n3 $sink
THE KAVERY ENGINEERING COLLEGE Page :

set udp [new Agent/UDP]


$ns attach-agent $n2 $udp

set cbr [new Application/Traffic/CBR]


$cbr attach-agent $udp
set null [new Agent/Null]
$ns attach-agent $n3 $null

$ns connect $tcp $sink


$ns connect $udp $null

$ns rtmodel-at 1.0 down $n1 $n3


$ns rtmodel-at 2.0 up $n1 $n3

$ns rtproto DV
$ns at 0.0 "$ftp start"
$ns at 0.0 "$cbr start"
$ns at 5.0 "finish"

$ns run

OUTPUT:

CONCLUSION

Thus tcl programs were executed to simulate the performance of distance vector routing
protocol using ns2.
THE KAVERY ENGINEERING COLLEGE Page :

EX. NO.: 9

SIMULATION OF ERROR CORRECTION CODES (CRC)

OBJECTIVE
To implement error correction Using CRC( Cyclic redundancy check)

ALGORITHM

1.Start the program


2. Create an object for the class process.
3. Get the number of bits to be send.
4. Get the divisor value.
5. Generate the dividend value with appending the value of (n-1) number of bits
of divisor.
6. Make a change in the message (bits) in sender side.
7. Generate a result whether there is error or not in the message
8. Stop the program.

PROGRAM
import java.io.*;
import java.util.*;
class crc_gen
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int[] data;
int[] div;
int[] divisor;
int[] rem;
int[] crc;
int data_bits, divisor_bits, tot_length;
System.out.println("Enter number of data bits : ");
data_bits=Integer.parseInt(br.readLine());
data=new int[data_bits];

System.out.println("Enter data bits : ");


for(int i=0; i<data_bits; i++)
data[i]=Integer.parseInt(br.readLine());

System.out.println("Enter number of bits in divisor : ");


divisor_bits=Integer.parseInt(br.readLine());
THE KAVERY ENGINEERING COLLEGE Page :

divisor=new int[divisor_bits];

System.out.println("Enter Divisor bits : ");


for(int i=0; i<divisor_bits; i++)
divisor[i]=Integer.parseInt(br.readLine());

/* System.out.print("Data bits are : ");


for(int i=0; i< data_bits; i++)
System.out.print(data[i]);
System.out.println();

System.out.print("divisor bits are : ");


for(int i=0; i< divisor_bits; i++)
System.out.print(divisor[i]);
System.out.println();

*/ tot_length=data_bits+divisor_bits-1;

div=new int[tot_length];
rem=new int[tot_length];
crc=new int[tot_length];
/*------------------ CRC GENERATION-----------------------*/
for(int i=0;i<data.length;i++)
div[i]=data[i];

System.out.print("Dividend (after appending 0's) are : ");


for(int i=0; i< div.length; i++)
System.out.print(div[i]);
System.out.println();

for(int j=0; j<div.length; j++)


{
rem[j] = div[j];
}

rem=divide(div, divisor, rem);

for(int i=0;i<div.length;i++)
//append dividend and ramainder
{
crc[i]=(div[i]^rem[i]);
}
THE KAVERY ENGINEERING COLLEGE Page :

System.out.println();
System.out.println("CRC code : ");
for(int i=0;i<crc.length;i++)
System.out.print(crc[i]);

/*-------------------ERROR DETECTION---------------------*/
System.out.println();
System.out.println("Enter CRC code of "+tot_length+" bits : ");
for(int i=0; i<crc.length; i++)
crc[i]=Integer.parseInt(br.readLine());

/*
System.out.print("crc bits are : ");
for(int i=0; i< crc.length; i++) System.out.print(crc[i]);
System.out.println();
*/

for(int j=0; j<crc.length; j++)


{
rem[j] = crc[j];
}

rem=divide(crc, divisor, rem);

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


{
if(rem[i]!=0)
{
System.out.println("Error");
break;
}
if(i==rem.length-1)
System.out.println("No Error");
}
System.out.println("THANK YOU.... :)");
}
THE KAVERY ENGINEERING COLLEGE Page :

static int[] divide(int div[],int divisor[], int rem[])

{
int cur=0;
while(true)
{
for(int i=0;i<divisor.length;i++)
rem[cur+i]=(rem[cur+i]^divisor[i]);

while(rem[cur]==0 && cur!=rem.length-1)


cur++;

if((rem.length-cur)<divisor.length)
break;
}
return rem;
}
}

OUTPUT:
THE KAVERY ENGINEERING COLLEGE Page :

CONCLUSION
Thus the java program to simulate error correction using CRC was executed successfully

You might also like