Professional Documents
Culture Documents
Network Lab III Year-12-108
Network Lab III Year-12-108
Pag Marks
Ex. e Date of Awarde Staff Rem
Date Name of the Experiment
No. No. Completion d Sign arks
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,
3
Dhirajlal Gandhi College of Technology
ALGORITHM
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
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
OBJECTIVE
To simulate traceroute command using java language.
OUTCOME
Students gain knowledge of traceroute command using java
ALGORITHM
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
10
Dhirajlal Gandhi College of Technology
VIVA QUESTIONS
1. Define RPC.
2. Explain client stub
3. Explain server stub.
4. What is marshalling.
5. Why we use marshalling?
TECHNICAL QUESTIONS
12
Dhirajlal Gandhi College of Technology
13
Dhirajlal Gandhi College of Technology
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
PROGRAM
//File Upload and Download Code Example
import javax.swing.*;
import java.net.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
14
Dhirajlal Gandhi College of Technology
dos.write(bytes, 0, bytes.length);
System.out.println("Image sent to server. ");
dos.close();
out.close();
soc.close();
}
}
Server
import java.net.*;
import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.*;
class Server {
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();
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:
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
18
Dhirajlal Gandhi College of Technology
19
Dhirajlal Gandhi College of Technology
20
Dhirajlal Gandhi College of Technology
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
ECHO CLIENT
import java.io.*;
import java.net.*;
public class eclient
{
{
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
AIM
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
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
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
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
32
Dhirajlal Gandhi College of Technology
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
}
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)
{
34
Dhirajlal Gandhi College of Technology
senddata = capsent.getBytes();
DatagramPacket pack = new DatagramPacket(senddata,
senddata.length,ipaddress,port);
serversocket.send(pack);
serversocket.close();
}}}
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
37
Dhirajlal Gandhi College of Technology
38
Dhirajlal Gandhi College of Technology
39
Dhirajlal Gandhi College of Technology
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
{
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
43
Dhirajlal Gandhi College of Technology
44
Dhirajlal Gandhi College of Technology
45
Dhirajlal Gandhi College of Technology
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
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:
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.
• An address or id_, monotonically increasing by 1 (from initial value 0) across the simulation
namespace as nodes are created,
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 connections between agents (ex. make connection between a "tcp" and "sink")
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,
$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.
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:
57
Dhirajlal Gandhi College of Technology
% ./install
Once following message comes:
(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).
58
Dhirajlal Gandhi College of Technology
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
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
proc finish {} {
global ns nf
$ns flush-trace
close $nf
}
$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]
62
Dhirajlal Gandhi College of Technology
$ns trace-all $f
set nf [open goback.nam w]
$ns namtrace-all $nf
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
AIM:
To simulate TCP/UDP Performance Using Simulation Tool
PROGRAM:
set ns [new Simulator]
set lan [$ns newLan "$n3 $n4 $n5" 0.5Mb 40ms LL Queue/DropTail MAC/Csma/Cd Channel]
# 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
TECHNICAL QUESTIONS
72
Dhirajlal Gandhi College of Technology
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
73
Dhirajlal Gandhi College of Technology
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
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
}
76
Dhirajlal Gandhi College of Technology
$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
AIM:
To simulate Distance Vector Multicast Routing Protocol in NS2
PROGRAM:
#define options
create-god $val(nn)
82
Dhirajlal Gandhi College of Technology
#generation of movements
$ns run
84
Dhirajlal Gandhi College of Technology
OUTPUT:
RESULT:
Thus Distance Vector Multicast Routing Protocol is simulated in NS2
PRACTICE EXERCISES
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
86
Dhirajlal Gandhi College of Technology
87
Dhirajlal Gandhi College of Technology
88
Dhirajlal Gandhi College of Technology
OBJECTIVE
To implement error correction Using CRC( Cyclic redundancy check)
OUTCOMES
Students gain knowledge in error correction and cyclic redundancy check concepts.
ALGORITHM
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;
data_bits=Integer.parseInt(br.readLine());
data=new int[data_bits];
*/ 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.println();
System.out.println("CRC code : ");
for(int i=0;i<crc.length;i++)
System.out.print(crc[i]);
91
Dhirajlal Gandhi College of Technology
{
int cur=0;
while(true)
{
for(int i=0;i<divisor.length;i++)
rem[cur+i]=(rem[cur+i]^divisor[i]);
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
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.-----
94