Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 97

CONTENTS

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

1(a) Study of Network Commands 1

Simulation of PING Command 4


1(b)

1(c) Simulation of tracerouter command 9

Create a Socket for HTTP for Web page and


2 14
Upload and Download

3(a) Socket Program For ECHO 21

Client- Server application for


3(b) 24
chat

3(c File Transfer In Client & Server 29


)

4 Implementation of DNS using TCP and 33


UDP sockets

5(a) Implementation of ARP Protocols 40

5(b) Simulation Of Rarp Protocol 46

6(a) Study of Network Simulator (NS) 52

6(b) Simulation Of Congestion Control 59


Algorithm Using Ns2

7 Study of TCP/UDP performance using 68


Simulation tool.

8(a) Simulation Of Link State Routing Protocol 73


Using Ns2

8(b) Simulation Of Distance Vector Routing 76


Protocol Using Ns2

9 Performance evaluation of Routing 82


protocols using Simulation tool.
10 Simulation of error correction code CRC). 89

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
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

OUTPUT

CONCLUSION

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

PRACTICE EXERCISES

1. Write a Java program to implement date server and client in Java using UDPsockets?
2. Write a Java Program to implement sorting N numbers in client server communication using UDP.
3. Write a Java Program to implement broadcasting multiple recipients?
4. Write a Java program to implement a chat server and client in Java using UDP sockets?
5. Write a Java program to implement UDP one way communication?

VIVA QUESTIONS
1. What is the use of Type Of Service field in the IP header?
2. What are the fields in an IP datagram header?
3. Explain Idempotent methods and web applications?
4. What is HTTP session state?
5. What is Secure HTTP?

5
Dhirajlal Gandhi College of Technology

TECHNICAL QUESTIONS

1. server can process multiple requests at a time.


A) An iterative B) A concurrent
C) A concurrent or an iterative D) None of the choices are correct
2. An interface is a set of designed to facilitate interaction between two entities.
A) programs B) instructions
C) rules D) None of the choices are correct
3. Information in a computer is stored in byte order.
A) host B) network
C) server D) None of the choices are correct
4. Network programming needs information to be in byte order.
A) host B) network
C) client D) None of the choices are correct

5. In representation, the least significant byte is stored in the starting address.


A) big-endian B) little-endian
C) middle-endian D) None of the choices are correct
6. In HTTP pipelining
A) multiple HTTP requests can not be sent on a single TCP connection
B) multiple HTTP requests are sent in a queue on a single TCP connection
C) none of the mentione
D) multiple HTTP requests are sent on a single TCP connection without waiting for the
corresponding responses
7. Multiple object can be sent over a TCP connection between client and server in
A) persistent HTTP B) nonpersistent HTTP
C) both (a) and (b) D) none of the mentioned

8. HTTP is protocol.
A) application layer B) transport layer
C) network layer D) none of the mentioned

6
Dhirajlal Gandhi College of Technology

7
Dhirajlal Gandhi College of Technology

8
Dhirajlal Gandhi College of Technology

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());

9
Dhirajlal Gandhi College of Technology

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

PRACTICE EXERCISES

1. Write a Java program to implement string reverse using RPC.


2. Write a Java program to implement Fibonacci series
3. Write a Java program to implement factorial value

10
Dhirajlal Gandhi College of Technology

4. Write a Java program to implement sum of two numbers


5. Write a Java program to check whether the given number is odd or even
6. Write a Java program to check whether the given words are palindromes.

VIVA QUESTIONS

1. Define RPC.
2. Explain client stub
3. Explain server stub.
4. What is marshalling.
5. Why we use marshalling?

TECHNICAL QUESTIONS

1. In representation, the most significant byte is stored in the starting address.


A) big-endian B) little-endian
C) middle-endian D) None of the choices are correct

2. Communication using UDP is usually .


A) connectionless,iterative B) connectionless,concurrent
C) connection-oriented,iterative D) connection-oriented,concurrent

3. Communication using TCP is usually .


A) connectionless, iterative B) connectionless, concurrent
C) connection-oriented, iterative D) connection-oriented, concurrent

4. SOCK_STREAM sockets are used by processes.


A) UDP B) TCP
C) SCTP D) None of the choices are correct

5.SOCK_DGRAM sockets are used by processes.


A) UDP B) TCP
C) SCTP D) None of the choices are correct

6.SOCK_SEQPACKET sockets are used by processes.


A) UDP B) TCP C) SCTP D)none of the choices are correct
11
Dhirajlal Gandhi College of Technology

12
Dhirajlal Gandhi College of Technology

13
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

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.p ack();
f.setVisible(true);
}
}

OUTPUT

16
Dhirajlal Gandhi College of Technology

CONCLUSION

Thus HTTP socket for web page upload and download using java was written and executed
successfully.

17
Dhirajlal Gandhi College of Technology

PRACTICE EXERCISES

1. Write a Java program to implement HTTP web page upload using socket.
2. Write a Java program to implement HTTP web page download using socket.
3. Write a Java program to implement HTTP request methods
4. Write a Java program to implement get and post methods of HTTP
5. Write a Java program to implement HTTP client.

VIVA QUESTIONS:

1. What is Hypertext Transfer Protocol (HTTP)?


2. What HTTP response headers do?
3. What is IP?
4. What do you mean by IP is an unreliable protocol?
5. What do you mean by IP is a best-effort protocol?
TECHNICAL QUESTIONS

1. A DNS client is called


A) DNS updater B) DNS resolver C) DNS handler D) none of the
mentioned

2. Servers handle requests for other domains


A) directly B) by contacting remote DNS server
C) it is not possible D) none of the mentioned

3. DNS database contains


A) name server records B) hostname-to-address records
C) hostname aliases D) all of the mentioned

4. If a server has no clue about where to find the address for a hostname then
A) server asks to the root server B) server asks to its adjcent server
C) request is not processed D) none of the mentioned

5. Which one of the following allows client to update their DNS entry as their IP address change?
A) dynamic DNS B) mail transfer agent
C) authoritative name server D) none of the mentioned

6. SNMP defines the to be sent from a manager to an agent and vice versa.
A) format of the packets B) encoding of the packets
C) number of packets D) none of the above

7. A manager is a host that runs the SNMP process.


A) client B) server C) both a and b D) none of the above

18
Dhirajlal Gandhi College of Technology

19
Dhirajlal Gandhi College of Technology

20
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

{
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
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

}
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
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

OUTPUT

CONCLUSION

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

36
Dhirajlal Gandhi College of Technology

PRACTICE EXERCISES

1. Write a Java Program to implement sorting N numbers in client server communication using TCP.
2. Write a Java program to implement date server and client in C using TCP sockets.
3. Write a Java program to implement a chat server and client in C using TCP sockets.
4. Write a Java program to implement FTP using TCP.
5. Write a Java program to implement TCP two way communication
VIVA QUESTIONS
1. Explain UDP.
2. Name two fields which are available in TCP header but not in UDP header.
3. Does UDP based applications have port numbers.
4. Name one criterion where an application developer would choose UDP over TCP.
5. Name one application which uses UDP on the internet.

TECHNICAL QUESTIONS

1. Information can be represented as a sequence of


A. byte patterns C. characters
B. bit patterns D. images
2. Parameter that refers to recording and broadcasting of picture is
A. Text C. Audio
B. Image D. Video
3. Both station can transmit and receive data simultaneously in
A. simplex mode C. Half duplex mode
B. Full duplex mode D. None of Above
4. Data communications are transfer of data through some
A. transmission medium C. linear medium
B. Network LAN D. Protocols
5. In representation of text symbols, each set of bit pattern is called
A. Code C. Unicode
Coding D.sequence

37
Dhirajlal Gandhi College of Technology

38
Dhirajlal Gandhi College of Technology

39
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

{
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
Dhirajlal Gandhi College of Technology

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

1. Write a Java program to reverse the string in client server communication using UDP?
2. Write a Java program to change case of a given string in client server communication using UDP?
3. Write a Java program to check whether the given word is palindrome in client server
communication using UDP.
4. Write a Java program to print the socket address of the client in UDP.
5. Write a Java Program to implement a DNS server and client in Java using UDP sockets.

VIVA QUESTIONS
1. Explain the services used in UDP?
2. Which of the protocols uses both TCP and UDP?
3. What is meant by port?
4. What is the header size of UDP?
5. Differentiate TCP and UDP
TECHNICAL QUESTIONS

1. is a dynamic mapping protocol in which a physical address is found for a given logical
address.
A) ARP B) RARP C) both a and b D) none of the above

2. The target hardware address on an Ethernet is in an ARP request.


A) 0x000000000000 B) 0.0.0.0 C) variable D) class dependent

3. A technique called is used to create a subnetting effect.


A) ARP B) RARP C) proxy ARP D) none of the above

4. . An RPC (remote procedure call) is initiated by the


A) server B) client C) both (a) and (b) D) none of the mentioned

5. Remote procedure calls is


A) inter-process communication
B) a single process
C) a single thread
D) none of the mentioned

43
Dhirajlal Gandhi College of Technology

44
Dhirajlal Gandhi College of Technology

45
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

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

PRACTICE EXERCISES
1. Write a Java program to implement SYN flooding
2. Write a Java program to implement Packet capturing
3. Write a Java program to build raw sockets with tcp
4. Write a Java program to build raw sockets with udp.
5. Write a Java program to implement ping command.
6. Write a Java program to implement trace route command.

VIVA QUESTIONS
1. Define a raw socket.
2. What are the parameters of raw socket.
3. Explain Packet injection?
4. Explain packet sniffing?
5. What is the use of Raw sockets?

TECHNICAL QUESTIONS
1. RPC allows a computer program to cause a subroutine to execute in
A) its own address space B) another address space C) both (a) and (b) D) none of the
mentioned
2. A remote procedure is uniquely identified by
A) program number B) version number C) procedure number D) all of the mentioned
3. is a program providing services to the _ program.
A) server; client B) client; server C) server; server D) None of the choices are correct
4.A is a program requesting services from a .
A) server; client B) client; server C) client; client D) None of the choices are correct
5. server can process only one request at a time.
A) An iterative B) A concurrent C) A concurrent or an iterative D) None of the
choices are correct
6. SOCK_SEQPACKET sockets are used by processes.
A) UDP B) TCP C) SCTP D) None of the choices are correct

49
Dhirajlal Gandhi College of Technology

50
Dhirajlal Gandhi College of Technology

51
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

% ./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
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

$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
Dhirajlal Gandhi College of Technology

}
$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
Dhirajlal Gandhi College of Technology

$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
Dhirajlal Gandhi College of Technology

$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
Dhirajlal Gandhi College of Technology

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

65
Dhirajlal Gandhi College of Technology

66
Dhirajlal Gandhi College of Technology

67
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

$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
Dhirajlal Gandhi College of Technology

$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
Dhirajlal Gandhi College of Technology

OUTPUT:

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

71
Dhirajlal Gandhi College of Technology

VIVA QUESTIONS

1) Difference between tcp/udp


2) What are the layers in TCP/IP model.
3) Is TCP/IP protocol is Stateless , if yes explain
4) Name the PDU of TCP and UDP
5) Name the three steps in TCP to establish connection.

TECHNICAL QUESTIONS

1. Which of the following is false with respect to UDP


a) Connection-oriented b) Unreliable c) Transport layer protocol d) All of the mentioned
2. what is the header size of UDP packet?
a) 8 bytes b) 8 bits c) 16 bytes d) 124 bytes
3. The field used to detect errors over the entire user datagram is
a) UDP header b) Checksum c) Source port d) Destination port
4. In TCP, sending and receiving data is done as
a) Stream of bytes b) Sequence of characters c) Lines of data d) Packets
5. The value of acknowledgement field in a segment defines
a) Number of previous bytes to receive b) Total number of bytes to receive
c) Number of next bytes to receive d) Sequence of zero‟s and one‟s

72
Dhirajlal Gandhi College of Technology

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

73
Dhirajlal Gandhi College of Technology

$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
Dhirajlal Gandhi College of Technology

OUTPUT

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

75
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

OUTPUT:

CONCLUSION

Thus tcl programs were executed to simulate the performance of distance vector routing 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.
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

78
Dhirajlal Gandhi College of Technology

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

TECHNICAL QUESTIONS

1. Distance Vector Routing is a……... routing algorithm, it consists of a data structure called a ………
A) Static, routing table B) Dynamic, look-up table
C) Static, look-up table D) Dynamic, routing table

2. A station in a network forwards incoming packets by placing them on its shortest output queue. What
routing algorithm is being used?
A) hot potato routing B) flooding
C) Static routing D) delta routing

3. State weather the following statement is true or false for Hierarchical Routing 1). In hierarchical
routing, the routers are divided into regions. 2) Each router is having the idea about internal structure of
other regions 3). Two level hierarchies may be insufficient hence it may be necessary to group the regions
into clusters.
A) 1. True, 2. True, 3. True
B) 1. True, 2. False, 3. False
C) 1. False, 2. False, 3. False
D) 1. True, 2. False, 3. True

79
Dhirajlal Gandhi College of Technology

80
Dhirajlal Gandhi College of Technology

81
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

#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
Dhirajlal Gandhi College of Technology

$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
Dhirajlal Gandhi College of Technology

OUTPUT:

RESULT:
Thus Distance Vector Multicast Routing Protocol is simulated in NS2

PRACTICE EXERCISES

1. Write a C program to implement routing protocol using OSPF


2. Write a C Program to inplement routing protocol using dijkstra‟s routing alorithm
3. Write a C program to implement routing protocol using interior gateway routing protocol

VIVA QUESTION
1. What is Routing ?
2. Name the types of routing algorithm.
3.What is adaptive routing algorithm?
4. what is non adaptive routing algorithm
5. Difference between BGP and OSPF protocol

85
Dhirajlal Gandhi College of Technology

TECHNICAL QUESTIONS

1. When there is heavy traffic on network, queuing time is

A. Remains same B. increases C.decreases D.none of the above

2. Time required for a bit to travel from source to destination is

A. Latency B.Propagation Time C.Delay D.Transmission time

3. To create a neighborhood relationship, a router running BGP sends an .............. message.


A. open B update C. keep alive D. close

4. The technique which requires no network information required is ….


A. flooding B. variable routing C. fixed routing D. random routing

5. Which of the following produces high traffic network?


A. Variable routing B. Flooding C. Fixed routing D. Random routing

86
Dhirajlal Gandhi College of Technology

87
Dhirajlal Gandhi College of Technology

88
Dhirajlal Gandhi College of Technology

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

A. Start the program


B. Create an object for the class process.
C. Get the number of bits to be send.
D. Get the divisor value.
E. Generate the dividend value with appending the value of (n-1) number of bits of divisor.
F. Make a change in the message (bits) in sender side.
G. Generate a result whether there is error or not in the message
H. 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
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

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
Dhirajlal Gandhi College of Technology

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

93
Dhirajlal Gandhi College of Technology

PRACTICE EXERCISES

1. Write a Java program to implement flow control using sliding window protocol.
2. Write a Java Program to implement error correction using hamming code.
3. Write a Java Program to implement flow control using stop and wait protocol.
4. Write a Java program to implement error detection using check sum.
5. Write a Java program to implement flow control using go back arq

VIVA QUESTIONS

1. What is flow control?


2. what is the use of hamming code protocol.
3. Difference between stop and wait protocol and sliding window protocol.
4. what is burst error?
5. What is parity checker?

TECHNICAL QUESTIONS

1. Term that refers to a set of procedures used to restrict amount of data that sender can send before
waiting for acknowledgment is-----
A) Flow control. B) Error Control.
C) Delay D) Byte stuffing
2. Error control is combination of---
A. Error Detection and Error correction. B.Flow and Error control
C. Bit stuffing and un stuffing. D. Byte stuffing and in byte stuffing.
3.Error Control and Flow Control are responsibilities of
A) Data link and Network Layers B) Data link and Physical layer
C) Application and Presentation layer. D) Data Link and Transport Layer.

4. When does the station B send a positive acknowledgement (ACK) to station A in Stop and Wait
protocol?
A) Only when no error occurs at the transmission level.
B)When retransmission of old packet in a novel frame is necessary
C) Only when station B receives frame with error
D) All the above
5. If the value of check sum is 0 the message is.-----

A)Accepted B) Rejected C) Resend D) Error

94

You might also like