0% found this document useful (0 votes)
87 views71 pages

PDF To Word

The document outlines experiments conducted on networking concepts and protocols. It contains 10 experiments with objectives to help students learn socket programming, simulation tools, and gain hands-on experience with various networking protocols. Each experiment is assigned a unique number and date of completion. The document tracks key details like the name of the experiment, objectives, outcomes, algorithms, programs, and scores. The overall goal is to help students gain practical knowledge of networking fundamentals.

Uploaded by

Syed Shaarikh
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)
87 views71 pages

PDF To Word

The document outlines experiments conducted on networking concepts and protocols. It contains 10 experiments with objectives to help students learn socket programming, simulation tools, and gain hands-on experience with various networking protocols. Each experiment is assigned a unique number and date of completion. The document tracks key details like the name of the experiment, objectives, outcomes, algorithms, programs, and scores. The overall goal is to help students gain practical knowledge of networking fundamentals.

Uploaded by

Syed Shaarikh
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
You are on page 1/ 71

CONTENTS

Pag Marks
Ex. Date Name of the Experiment e Date of Awarde Staff Rem
No. No. Completion d Sign arks

1(a) Study of Network Commands

Simulation of PING Command


1(b)

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

Client- Server application for


3(b)
chat

3(c File Transfer In Client & Server


)

4 Implementation of DNS using TCP and


UDP sockets

5(a) Implementation of ARP Protocols

5(b) Simulation Of Rarp Protocol

6(a) Study of Network Simulator (NS)

6(b) Simulation Of Congestion Control


Algorithm Using Ns2

7 Study of TCP/UDP performance using


Simulation tool.

8(a) Simulation Of Link State Routing Protocol


Using Ns2

8(b) Simulation Of Distance Vector Routing


Protocol Using Ns2

9 Performance evaluation of Routing


protocols using Simulation tool.

10 Simulation of error correction code CRC).

RECORD COMPLETION DATE: AVERAGE MARKSSCORED:


LAB-IN-CHARGE:
OBJECTIVES:

The student should be made to:

​ Learn socket programming.

​ Be familiar with simulation tools.

​ Have hands on experience on various networking protocols


Experiment Score /10
EX. NO.:1(a) Date of
Completion Additional Credits

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.

1
C:\>nbtstat –a: This command helps solve problems with NetBIOS name resolution. (Nbt stands for
NetBIOS over TCP/IP)
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.

2
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,

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.

3
Experiment Score /10
EX. NO.:1(b) Date of
Completion Additional Credits

SIMULATION OF PING COMMAND


OBJECTIVE
To simulate ping command using java language.
OUTCOME
Students gain knowledge in understanding HTTP client/server and implement using
Java.

ALGORITHM

1. Start the program


2. Create an object for the class process.
3. Get IP address from the user using getInputStream().
4. Execute the ping command using Runtime.getRuntime().
5. Stop the program.
PROGRAM
import java.util.*;
public class PingDemo
{
public void ping(String host)
{
try
{
Process p = Runtime.getRuntime().exec("ping
"+host); Scanner scan = new
Scanner(p.getInputStream());
while(scan.hasNextLine())
{
System.out.println(scan.nextLine());
}
}
catch(Exception ex){
System.out.println("Error "+ex);
}
}
public static void main(String args[]){
PingDemo p=new PingDemo();
p.ping(args[0]);
}
}
4
OUTPUT

CONCLUSION

Thus the java program to simulate ping command was executed successfully.

8
Experiment Score /10
EX.NO.:1(C) Date of
Completion Additional Credits

SIMULATION OF TRACEROUTE COMMAND

OBJECTIVE
To simulate traceroute command using java language.

OUTCOME
Students gain knowledge of traceroute command using java

ALGORITHM

1. Start the program


2. Create an object for the class process.
3. Get IP address from the user using getInputStream().
4. Execute the Tracert command using Runtime.getRuntime().
5. Stop the program.

PROGRAM
import java.util.*;
public class TraceDemo
{
public void trace(String host)
{
try {
Process p = Runtime.getRuntime().exec("Tracert "+host);
Scanner scan = new Scanner(p.getInputStream());
while(scan.hasNextLine())
{
System.out.println(scan.nextLine());

}
}
catch(Exception ex){
System.out.println("Error "+ex);
}}
public static void main(String args[]){
TraceDemo p=new TraceDemo();
p.trace(args[0]);
}
}

OUTPUT

CONCLUSION

Thus the java program to simulate trace route command was executed successfully.

13
Experiment Score /10
EX. NO.:2 Date of
Completion Additional Credits

CREATE SOCKET FOR HTTP FOR WEB PAGE UPLOAD AND DOWNLOAD

OBJECTIVE
To create the HTTP socket for web page upload and download using java programming.
OUTCOME
Students gain knowledge in understanding subnetting and implement using JAVA.

ALGORITHM

1. Start the program


2. Read the input file name.
3. Create connection with HTTP server
4. Login HTTP server with username and password
5. Set the upload file path in HTT server.
6. Upload the file.
7. Read the name of the file to be downloaded and the path at where file to be stored
8. Download the file stream and store in the file in specified path.
9. Stop the program.

PROGRAM
//File Upload and Download Code Example
import javax.swing.*;
import java.net.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;

import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import


java.io.File;

import java.io.IOException; import javax.imageio.ImageIO;

public class Client{

public static void main(String args[]) throws Exception{ Socket soc;

14
BufferedImage img = null;
soc=new Socket("localhost",4000);

System.out.println("Client is running. ");


try {

System.out.println("Reading image from disk. ");

img = ImageIO.read(new File("digital_image_processing.jpg")); ByteArrayOutputStream baos =


new ByteArrayOutputStream();
ImageIO.write(img, "jpg", baos);
baos.flush();

byte[] bytes = baos.toByteArray(); baos.close();

System.out.println("Sending image to server. ");


OutputStream out = soc.getOutputStream();
DataOutputStream dos = new
DataOutputStream(out);
dos.writeInt(bytes.length);

dos.write(bytes, 0, bytes.length);
System.out.println("Image sent to server. ");
dos.close();
out.close();

}catch (Exception e) { System.out.println("Exception: " + e.getMessage());


soc.close();
}

soc.close();
}
}
Server

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

import java.awt.image.*;
import javax.imageio.*;
import javax.swing.*;

class Server {

public static void main(String args[]) throws


Exception{ ServerSocket server=null;
15
Socket socket;

server=new ServerSocket(4000);
System.out.println("Server Waiting for image");
socket=server.accept(); System.out.println("Client
connected."); InputStream in = socket.getInputStream();
DataInputStream dis = new DataInputStream(in);
int len = dis.readInt();

System.out.println("Image Size: " + len/1024 + "KB"); byte[] data = new byte[len];

dis.readFully(data);
dis.close();
in.close();
InputStream ian = new
ByteArrayInputStream(data); BufferedImage
bImage = ImageIO.read(ian); JFrame f = new
JFrame("Server"); ImageIcon icon = new
ImageIcon(bImage);
JLabel l = new JLabel();
f.add(l);

f.pack();
f.setVisible(true);
}
}

OUTPUT

16
CONCLUSION

Thus HTTP socket for web page upload and download using java was written and executed
successfully.
17
Experiment Score /10
EX. NO.:3(a) Date of
Completion Additional Credits

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.
PROGRAM

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

public static void main(String args[])


21
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");
}}}
Echo Server:
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;
22
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);
}
}
}
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

23
Experiment Score /10
EX. NO.:3(b) Date of
Completion Additional Credits

Client- Server application for chat

AIM

To write a client-server application for chat using TCP

ALGORITHM

CLIENT
1. Start the program
2. Include necessary package in java
3. To create a socket in client to server.
4. The client establishes a connection to the server.
5. The client accept the connection and to send the data from client to server.
6. The client communicates the server to send the end of the message
7. Stop the program.

SERVER
1. Start the program
2. Include necessary package in java
3. To create a socket in server to client
4. The server establishes a connection to the client.
5. The server accept the connection and to send the data from server to client and
6. vice versa
7. The server communicate the client to send the end of the message.
8. Stop the program.

PROGRAM

TCPserver1.java
24
import java.net.*;
import java.io.*;
public class TCPserver1
{
public static void main(String arg[])
{
ServerSocket s=null;
String line;
DataInputStream is=null,is1=null;
PrintStream os=null;
Socket c=null;
try
{
s=new ServerSocket(9999);
}catch(IOException e)

System.out.println(e);
} try
{
c=s.accept();
is=new
DataInputStream(c.getInputStream());
is1=new DataInputStream(System.in);
os=new
PrintStream(c.getOutputStream()); do
{
line=is.readLine();
System.out.println("Client:"+line);
System.out.println("Server:");
line=is1.readLine();
os.println(line);
25
}
while(line.equalsIgnoreCase("quit")==false);
is.close();
os.close();
}
catch(IOException e)
{
System.out.println(e);
}
}
}
TCPclient1.java
import java.net.*;
import java.io.*;
public class TCPclient1

{
public static void main(String arg[])
{
Socket c=null;
String line;
DataInputStream is,is1;
PrintStream os;
try
{
c=new Socket("10.0.200.36",9999);

}
catch(IOException e)
{

26
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);
System.out.println("Server:" + is1.readLine());
}
while(line.equalsIgnoreCase("quit")==false);
is1.close();
os.close();
}
catch(IOException e)
{
System.out.println("Socket Closed!Message Passing is over");
}}
OUTPUT:
SERVER
C:\Program Files\Java\jdk1.5.0\bin>javac TCPserver1.java
Note: TCPserver1.java uses or overrides a deprecated API.
Note: Recompile with -deprecation for details.
C:\Program Files\Java\jdk1.5.0\bin>java TCPserver1

27
Client: Hai Server
Server:Hai Client
Client: How are you
Server:Fine
Client: quit
Server:quit

CLIENT
C:\Program Files\Java\jdk1.5.0\bin>javac TCPclient1.java
Note: TCPclient1.java uses or overrides a deprecated API.
Note: Recompile with -deprecation for details.
C:\Program Files\Java\jdk1.5.0\bin>java TCPclient1
Client:Hai Server
Server: Hai Client
Client:How are you
Server: Fine
Client:quit
Server: quit

RESULT

Thus the above program a client-server application for chat using TCP / IP was and
successfully.executed

28
Experiment Score /10
EX. NO.:3(c) Date of
Completion Additional Credits

File Transfer In Client & Server

AIM
To Perform File Transfer in Client & Server Using TCP/IP.

ALGORITHM
CLIENT SIDE
1. Start.
2. Establish a connection between the Client and Server.
3. Socket ss=new Socket(InetAddress.getLocalHost(),1100);
4. Implement a client that can send two requests.
i) To get a file from the server.
ii) To put or send a file to the server.
5. After getting approval from the server ,the client either get file from the server or send
6. file to the server.

SERVER SIDE
1. Start.
2. Implement a server socket that listens to a particular port number.
3. Server reads the filename and sends the data stored in the file for the„get‟ request.
4. It reads the data from the input stream and writes it to a file in theserver for the „put‟
instruction.
5. Exit upon client‟s request.
6. Stop.

PROGRAM
CLIENT SIDE
import java.net.*;

29
import java.io.*;
public class FileClient{
public static void main (String [] args ) throws
IOException { int filesize=6022386; // filesize temporary
hardcoded long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
// localhost for testing
Socket sock = new Socket("127.0.0.1",13267);

System.out.println("Connecting...");
// receive file
byte [] mybytearray = new byte [filesize];
InputStream is = sock.getInputStream();
FileOutputStream fos = new
FileOutputStream("source-copy.pdf"); BufferedOutputStream
bos = new BufferedOutputStream(fos); bytesRead =
is.read(mybytearray,0,mybytearray.length); current =
bytesRead;
do {
bytesRead =
is.read(mybytearray, current,
(mybytearray.length-current)); if(bytesRead >= 0) current
+= bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray, 0 ,
current);
bos.flush();
long end =
System.currentTimeMillis();
System.out.println(end-start);
bos.close();
30
sock.close();
}}

SERVER SIDE
import java.net.*;
import java.io.*;
public class FileServer
{
public static void main (String [] args ) throws
IOException { ServerSocket servsock = new
ServerSocket(13267); while (true) {
System.out.println("Waiting..."); Socket sock =
servsock.accept(); System.out.println("Accepted
connection : " + sock); File myFile = new File
("source.pdf");
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
sock.close();
}}}

OUTPUT

SERVER OUTPUT
C:\Program Files\Java\jdk1.6.0\bin>javac FServer.java

31
C:\Program Files\Java\jdk1.6.0\bin>java FServer
Waiting for clients...
Connection Established
Client wants file:network.txt

CLIENT OUTPUT
C:\Program Files\Java\jdk1.6.0\bin>javac
FClient.java C:\Program
Files\Java\jdk1.6.0\bin>java FClient Connection
request.....Connected Enter the filename:
network.txt
Computer networks: A computer network, often simply referred to as a network, is acollection of
computers and devices connected by communications channels thatfacilitates communications
among users and allows users to shareresources with other user

RESULT

Thus the File transfer Operation is done & executed successfully

32
Experiment Score /10
EX.NO.: 4 Date of
Completion Additional Credits

IMPLEMENTATION OF DNS USING UDP SOCKETS

OBJECTIVE
To implement a DNS server and client in java using UDP sockets.
OUTCOME
Students become expertise to write socket program for DNS 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.

33
PROGRAM

// UDP DNS Server --


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";

34
senddata = capsent.getBytes();
DatagramPacket pack = new
DatagramPacket(senddata,
senddata.length,ipaddress,port);

serversocket.send(pack);
serversocket.close();
}}}

//UDP DNS Client -- 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();
}}
35
OUTPUT

CONCLUSION

Thus domain name requests by the client are resolved into their respective logical address
using lookup method.

36
Experiment Score /10
EX. NO.:5(a) Date of
Completion Additional Credits

Implementation of ARP Protocols

OBJECTIVE
Acquire knowledge on ARP and UDP concepts and can easily exhibit it using Java programming.

OUTCOME
Students gain knowledge in understanding ARP and implement using Java.

ALGORITHM

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

PROGRAM
//ARP Server -- arpserver.java
import java.io.*;
import java.net.*;
class arpserver
{
public static void main(String args[])throws IOException
{
try
{
ServerSocket soc = new ServerSocket(2500);
System.out.println("Server started");
40
Socket client = null;
client = soc.accept();
String str;
PrintStream ps = new PrintStream(client.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
Runtime r = Runtime.getRuntime();
Process p = r.exec("ifconfig eth0");
BufferedReader pin=new BufferedReader(new
InputStreamReader(p.getInputStream())); String haddr = "";
String ipaddr = br.readLine();
int flag = 0;
while((str = pin.readLine())!=null)
{
System.out.println(str);
if((str.indexOf("HWaddr")) != -1)
{
int tlen = str.length();
int hlen = tlen - 19;
haddr = str.substring(hlen,tlen);
}
else if ((str.indexOf(ipaddr)) != -1)
{
flag = 1;
}
}
if (flag == 1)
ps.println(haddr);
ps.close();
br.close();
pin.close();
client.close();
soc.close();
}
catch(IOException io)
{
System.err.println("Exception : " + io.toString());
}}}

//ARP Client -- arpclient.java


import java.io.*;
import java.net.*;
class arpclient
{
public static void main(String args[])
41
{
try
{
Socket client = new Socket("localhost", 2500);
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in)); PrintStream ps = new
PrintStream(client.getOutputStream()); String ipaddr,haddr = null;
BufferedReader sin = new BufferedReader(new InputStreamReader(client.getInputStream()));
System.out.print("Enter the IP address : ");
ipaddr = br.readLine();
ps.println(ipaddr);
haddr = sin.readLine();
if (haddr == null)
System.out.println("Host does not exist");
else
System.out.println("Physical Address " + haddr);
ps.close();
br.close();
client.close();
}
catch(IOException io)
{
System.err.println(io.toString());
}}}

OUTPUT

42
CONCLUSION
Thus the java program to simulate ARP protocol was executed successfully.

45
Experiment Score /10
EX. NO.:5(b) Date of
Completion Additional Credits

SIMULATION OF RARP PROTOCOL

OBJECTIVE
To simulate RARP protocol using java language.
OUTCOME
Students gain knowledge in understanding RARP protocol using Java.
ALGORITHM
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

PROGRAM
//RARP Server -- rarpserver.java
import java.io.*;
import java.net.*;
class rarpserver
{
public static void main(String args[])throws IOException
{
try
{
ServerSocket soc = new ServerSocket(5000);
System.out.println("Server started");
Socket client = null;
client = soc.accept();
46
String str;
PrintStream ps = new
PrintStream(client.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
Runtime r = Runtime.getRuntime();
Process p = r.exec("ifconfig eth0");
BufferedReader pin = new BufferedReader(new
InputStreamReader(p.getInputStream())); String ipaddr = "";
String haddr = br.readLine();
int flag = 0;
while((str = pin.readLine())!=null)
{
System.out.println(str);
if ((str.indexOf(haddr)) != -1)
{
flag = 1;
}
else if((str.indexOf("inet addr")) != -1)
{
int pos = str.indexOf("inet addr:") + 10;
int offset = pos + 13;
ipaddr = str.substring(pos,offset);
}
}
if (flag == 1)
ps.println(ipaddr);
ps.close();
br.close();
pin.close();
client.close();
soc.close();
}
catch(IOException io)
{
System.err.println("Exception : " + io.toString());
}
}
}
//RARP Client -- rarpclient.java
import java.io.*;
import java.net.*;
class rarpclient
{
public static void main(String args[])
{
47
try
{
Socket client = new Socket("localhost", 5000);
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
PrintStream ps = new
PrintStream(client.getOutputStream());
String haddr,ipaddr = null;
BufferedReader sin = new BufferedReader(new
InputStreamReader(client.getInputStream()));
System.out.print("Enter the physical address : ");
haddr = br.readLine();
ps.println(haddr);
ipaddr = sin.readLine();
if (ipaddr == null)
System.out.println("Host does not exist");
else
System.out.println("Logical Address " + ipaddr);
ps.close();
br.close();
client.close();
}
catch(IOException io)
{
System.err.println(io.toString());
}}}

OUTPUT

48
Experiment Score /10
EX. NO.:6(a) Date of
Completion Additional Credits

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 2.1 shows the basic architecture of NS2. NS2 provides users with anexecutable
command ns
52
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.

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

53
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 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

54
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")

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.

55
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 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.

56
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 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

57
% ./install
Once following message comes:

Nam has been installed successfully.


Ns-allinone package has been installed successfully.

(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.

58
Experiment Score /10
EX. NO.:6(b) Date of
Completion Additional Credits

SIMULATION OF CONGESTION CONTROL ALGORITHM USING NS2

OBJECTIVE
Acquire TCL scripting skills to Implement and simulate congestion control using NS2
simulator.

OUTCOME:
Students become expertise to write tcl script 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]
59
set n3 [$ns node]
set n4 [$ns node]

set n5 [$ns node]

$n0 color "purple"


$n1 color "purple"
$n2 color "violet"
$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
60
$ns attach-agent $n0 $tcp

set sink [new Agent/TCPSink]


$ns attach-agent $n5 $s
ink
$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
61
}
$ns run

OUTPUT
STOP WAIT PROTOCOL

PROGRAM://GO BACK
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"
$n3 color "violet"
$n4 color "chocolate"
$n5 color "chocolate"
set f [open goback.tr w]
62
$ns trace-all $f
set nf [open goback.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 1Mb 10ms DropTail


$ns duplex-link $n1 $n2 1Mb 10ms DropTail
$ns duplex-link $n2 $n3 1Mb 10ms DropTail
$ns duplex-link $n3 $n4 1Mb 10ms DropTail
$ns duplex-link $n3 $n5 1Mb 10ms 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 5


#Agent/TCP set nam_tracevar_true
set tcp [new Agent/TCP]
$tcp set fid 1
$ns attach-agent $n1 $tcp

set sink [new Agent/TCPSink]


$ns attach-agent $n4 $sink
$ns connect $tcp $sink
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ns at 0.05 "$ftp start"
$ns at 0.06 "$tcp set windowlnit 6"
$ns at 0.06 "$tcp set maxcwnd 6"

$ns at 0.25 "$ns queue-limit $n3 $n4 0"


$ns at 0.26 "$ns queue-limit $n3 $n4 10"
$ns at 0.305 "$tcp set windowlnit 4"
$ns at 0.305 "$tcp set maxcwnd 4"
$ns at 0.368 "$ns detach-agent $n1 $tcp ; $ns detach-agent $n4 $sink"
$ns at 1.5 "finish"
$ns at 0.0 "$ns trace-annotate \"Goback N end\""
63
$ns at 0.05 "$ns trace-annotate \"FTP starts at 0.01\""
$ns at 0.06 "$ns trace-annotate \"Send 6Packets from SYS1 to SYS4\""
$ns at 0.26 "$ns trace-annotate \"Error Occurs for 4th packet so dont send ack
for the Packet\""
$ns at 0.30 "$ns trace-annotate \"Retransmit Packet_4 to 6\""
$ns at 1.0 "$ns trace-annotate \"FTP stops\""
proc finish {} {
global ns nf
$ns flush-trace
close $nf
puts "filtering..."
exec nam goback.nam &
exit 0
}
$ns run
OUTPUT
GO BACK N protocol

CONCLUSION
Thus tcl programs were executed to simulate the performance of stop wait and Go back N protocol
using ns2.
PRACTICE EXERCISES

1. Write a TCL script to drop down the packets in particular link at specific time.
2. Write a TCL script to drop the packets in router and Endserver link at 1.6sec.
64
3. Write a TCL script to drop down the packets in same link at particular time intervals
4. TCL script to handle trace annotation.
5. Write a TCL script for display the nodes activity in simulation window using trace annotation

VIVA QUESTIONS

1. What command is used to stop RIP routing updates from exiting out an interface but still allow
the interface to receive RIP route updates?
2. If your routing table has a static, a RIP, and an IGRP route to the same network, which route
will be used to route packets by default?
3. Which command displays RIP routing updates?
4. What are the basic components of router
5. Explain routing table
6. What is distance vector routing protocol
7. Explain some basics of internet routing
8. What is static and dynamic routing
9. What are the fields included in routing table?
10. What is split horizon?

TECHNICAL QUESTIONS
1. Which one of the following algorithm is not used for congestion control?
A) traffic aware routing B) admission control
C) load shedding D) none of the above
2. The network layer concerns with
A) bits B) frames
C) packets D) none of the above
3. The 4 byte IP address consists of
A) n/w address B) host address
C) both A and B D) none of the above
4. The subnet gets increasingly loaded with packets causing increase in delay in the delivery of
packets, which can lead to more retransmission, and ultimately increasing more and more traffic. This is a
concept
called as _________

A) Blockage B) Traffic jam C) Congestion D) both A and B

5. ______ is a static algorithm in which every incoming packet is sent out on every outgoing line
except
the one it arrives on. This method usually generates vast number of duplicate packets.

A) Flooding B) Wait and watch C) Congestion D) both A and C


Experiment Score /10
EX.NO.:7 Date of
Completion Additional Credits

STUDY OF TCP/UDP PERFORMANCE USING SIMULATION TOOL.

AIM:
To simulate TCP/UDP Performance Using Simulation Tool

PROGRAM:
set ns [new Simulator]

#Define different colors for data flows (for NAM)


$ns color 1 Blue
$ns color 2 Red

#Open the Trace files


set file1 [open out.tr w]
set winfile [open WinFile w]
$ns trace-all $file1

#Open the NAM trace file


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

#Define a 'finish' procedure


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

#Create six nodes


set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
68
$n1 color red
$n1 shape box
#Create links between the nodes
$ns duplex-link $n0 $n2 2Mb 10ms DropTail
$ns duplex-link $n1 $n2 2Mb 10ms DropTail
$ns simplex-link $n2 $n3 0.3Mb 100ms DropTail
$ns simplex-link $n3 $n2 0.3Mb 100ms DropTail

set lan [$ns newLan "$n3 $n4 $n5" 0.5Mb 40ms LL Queue/DropTail MAC/Csma/Cd
Channel]

# $ns duplex-link $n3 $n4 0.5Mb 40ms DropTail


# $ns duplex-link $n3 $n5 0.5Mb 30ms DropTail

#Give node position (for NAM)


# $ns duplex-link-op $n0 $n2 orient right-down
# $ns duplex-link-op $n1 $n2 orient right-up
# $ns simplex-link-op $n2 $n3 orient right
# $ns simplex-link-op $n3 $n2 orient left
# $ns duplex-link-op $n3 $n4 orient right-up
# $ns duplex-link-op $n3 $n5 orient right-down

#Set Queue Size of link (n2-n3) to 10


# $ns queue-limit $n2 $n3 20

#Setup a TCP connection


set tcp [new Agent/TCP/Newreno]
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink/DelAck]
$ns attach-agent $n4 $sink
$ns connect $tcp $sink
$tcp set fid_ 1
$tcp set window_ 8000
$tcp set packetSize_ 552

#Setup a FTP over TCP connection


set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ftp set type_ FTP

#Setup a UDP connection


set udp [new Agent/UDP]
69
$ns attach-agent $n1 $udp
set null [new Agent/Null]
$ns attach-agent $n5 $null

$ns connect $udp $null


$udp set fid_ 2

#Setup a CBR over UDP connection

set cbr [new Application/Traffic/CBR]

$cbr attach-agent $udp


$cbr set type_ CBR
$cbr set packet_size_ 1000
$cbr set rate_ 0.01mb
$cbr set random_ false

$ns at 0.1 "$cbr start"


$ns at 1.0 "$ftp start"
$ns at 124.0 "$ftp stop"
$ns at 124.5 "$cbr stop"

# next procedure gets two arguments: the name of the


# tcp source node, will be called here "tcp",
# and the name of output file.

proc plotWindow {tcpSource file} {


global ns
set time 0.1
set now [$ns now]
set cwnd [$tcpSource set cwnd_]
set wnd [$tcpSource set window_]
puts $file "$now $cwnd"
$ns at [expr $now+$time] "plotWindow $tcpSource
$file" } $ns at 0.1 "plotWindow $tcp $winfile"
$ns at 5 "$ns trace-annotate \"packet drop\""

# PPP
$ns at 125.0 "finish"
$ns run

70
OUTPUT:

RESULT:
Thus Carrier Sense Multiple Access Protocol - MAC Protocol is simulated in NS2

71
Experiment Score /10
EX.NO.:8(a) Date of
Completion Additional Credits

SIMULATION OF LINK STATE ROUTING PROTOCOL USING NS2

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

OUTCOME
Students become expertise to write tcl script 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

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

74
OUTPUT

CONCLUSION
Thus tcl programs were executed to simulate the performance of link state routing protocol
using
ns2

75
Experiment Score /10
EX. NO.:8(b) Date of
Completion Additional Credits

SIMULATION OF DISTANCE VECTOR ROUTING PROTOCOL USING NS2

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

OUTCOME
Students become expertise to write tcl script 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

76
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

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

77
OUTPUT:

CONCLUSION

Thus tcl programs were executed to simulate the performance of distance vector routing
protocol using ns2.

79

80
Experiment Score /10
EX. NO.:9 Date of
Completion Additional Credits

PERFORMANCE ANALYSIS OF ROUTING PROTOCOL USING NS2

AIM:
To simulate Distance Vector Multicast Routing Protocol in NS2

PROGRAM:
#define options

set val(chan) Channel/WirelessChannel ;


set val(prop) Propogation/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) 3 ;
set val(rp) DSDV ;
set val(x) 500;
set val(y) 400;
set val(stop) 150;

set ns [new Simulator]


set tracefd [open simple.tr w]
set windowVsTime2 [open win.tr w]
set namtrace [open simwrls.nam w]

$ns trace-all $tracefd


$ns namtrace-all-wireless $namtrace $val(x) $val(y)

#set up topography object


set topo [new Topography]

$topo load_flatgrid $val(x) $val(y)

create-god $val(nn)

# create nn mobilenodes $[val(nn)] and them to channel.

82
#configure the nodes
$ns node-config -adhocRouting DSR \
-llType LL \
-macType Mac/802_11 \
-ifqType Queue/DropTail/PriQueue \
-ifqLen 50 \
-antType Antenna/OmniAntenna \
-propType Propagation/TwoRayGround \
-phyType Phy/WirelessPhy \
-channelType Channel/WirelessChannel \
-topoInstance $topo \
-agentTrace ON \
-routerTrace ON \
-macTrace OFF \
-movementTrace ON

for {set i 0} {$i < $val(nn)} {incr i} {


set node_($i) [$ns node]
}

#provide initial location of mobile nodes

$node_(0) set X_ 5.0


$node_(0) set Y_ 5.0
$node_(0) set Z_ 0.0

$node_(1) set X_ 490.0


$node_(1) set Y_ 285.0
$node_(1) set Z_ 0.0

$node_(2) set X_ 150.0


$node_(2) set Y_ 240.0
$node_(2) set Z_ 0.0

#generation of movements

$ns at 10.0 "$node_(0) setdest 250.0 250.0 3.0"


$ns at 15.0 "$node_(1) setdest 45.0 285.0 5.0"
$ns at 110.0 "$node_(0) setdest 480.0 300.0 5.0"

#set up tcp connection between node_(0) and node_(1)


set tcp [new Agent/TCP/Newreno]
$tcp set class_ 2
set sink [new Agent/TCPSink]
83
$ns attach-agent $node_(0) $tcp

$ns attach-agent $node_(1) $sink


$ns connect $tcp $sink
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ns at 10.0 "$ftp start"
#define node initial position in nam
for {set i 0} {$i < $val(nn)} {incr i} {
#30 defines the node size for nam
$ns initial_node_pos $node_($i) 30
}
#telling nodes when the simulation ends
for {set i 0} {$i < $val(nn) } { incr i } {
$ns at $val(stop) "$node_($i) reset" ;
}

#ending nam and the simulation

$ns at $val(stop) "$ns nam-end-wireless $val(stop)"


$ns at $val(stop) "stop"
$ns at 150.0 "puts \"end simulation\" ; $ns halt"
proc stop {} {
global ns tracefd namtrace
$ns flush-trace
close $tracefd
close $namtrace
exec nam simwrls.nam &
}

$ns run

84

OUTPUT:
RESULT:
Thus Distance Vector Multicast Routing Protocol is simulated in NS2
Experiment Score /10
EX. NO.:10 Date of
Completion Additional Credits

SIMULATION OF ERROR CORRECTION CODES (CRC)

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

OUTCOMES
Students gain knowledge in error correction and cyclic redundancy check concepts.

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 : ");


89
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());
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];
}
90
rem=divide(div, divisor, rem);

for(int i=0;i<div.length;i++) //append dividend and ramainder


{
crc[i]=(div[i]^rem[i]);
}

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");
}

91
System.out.println("THANK YOU.... :)");
}

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:

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

You might also like