LAB Exercises
LAB Exercises
Applications using
TCP and echo
Expt No:3A server
Date :
and ccho server using TCP Sockets.
Echoclient
AIM: programfor
Towriteajava
client and cchoes it back.
data fromits
CONCEPT: rcceives can rendezvous with on
server simplywelI-known servicethat clients por 7.
Echo connection tothe Echo
1. The
Echo server
is a
thercby getting
a server.
stream. and then forwards
2. The creates a socket standardinput that tex1 to the
Echo Client user on the
3.
input fromthe text to the socket.
4 ltreads
writing the the socket to the client
by through
Echoserver back it from the
scrver echoes the input displaysthe data passed back to server.
$. The programreadsand
6. The client
HARDWARE REQQUIREMENT:
" P- 11400 MHZ speed
20GB Hard disk
64 MB RAM
SOFTWARE REQUIREMENT:
" CCompiler/Java Compiler
ALGORITHM:
side and one for the client side
1. Create two programs one for the server
2. In the server side, create a server socket.
new socket created.
3. The return value of the accept () method is assigned to a
to the clhent.
4. Send the input received from the client at the server side back
5. In the client side, create a socket to connect to the server.
6. Create the object of DatalnputStream to accept input from the serVer
7. Display the input received from the server.
8. Stop the program.
PROGRAM :
EchoServer.java
import java.io. *:
import java.net. *:
public class EchoServer
public EchoServer(int portnum)
try
server = new ServerSocket(portnum):
catch (Exception er)
System.out.println(err):
try
(while (true)
Socket client = server.accept();
BufferedReader r = new BufferedReader(new
InputStreamReader(client.getInputStream)):
PrintWriter w =new PrintWiiter(client. getOutputStream(), true):
w.println("Welcome to the Java EchoServer. Type 'bye' to close."):
String lie:
do line = rreadLine0:
if(line != null )
w.println("Server: "+ line):
while (!ine.trim().equals("bye") ):
client.close():
EchoClient.java :
Import java.io.*:
import java.net.*:
public class EchoClient
public static void main( String[] args)
try
Socket s = new Socket("
BufferedReader r = new BufferedReader(new "127.0.0.1". 9999);
InputStreamReader(s.getInputStream())):
PrintWriter w = new
BufferedReader con = new
InputStreamReader(System. in):
PrintWBufferedReader(ncw
riter(s. getOutputStream). true);
String line:
do
line = r.readLine();
if (line != null )
System.out.println(line):
line = con.rcadLine():
w.printIn(line);
}while ( !line.trim().equals("bye") );
catch (Exception err)
System.err.println( err):
RESULT:
Thus the java program for Echo client and echo server using TCP Sockets was created.
Expt No: 3B
Date : Applications using TCP Sockets (like Chat)
AIM:
To write a java program for chat using TCP Sockets.
CONCEPT:
1. It uses TCP socket communication .We have a server as well as a client.
2. Both can be run in the same machine or different
machines. If both are running in themachine,
the address to be given at the client side is local host
address.
3. If both are running in different machines, then in the
client side we need to specity the
ipaddress of machine in which server application is running.
ALGORITHM:
Server
1. Start the program
2. Create server and client sockets.
3. Use input streams to get the message from user.
4. Use output streams to send message to the client.
5. Wait for client to display this message and writea new one to be
displayed by theserver.
6. Display message given at client using input streams read from socket.
7. Stop the program.
Client
1. Start the
program
2. Create a client socket that connects to the required host and port.
3. Use input streams read message given by server and print it.
4. Use input streams; get the message from user to be given to the server.
5. Useoutput streams to write message to the server.
6. Stop the program.
PROGRAM:
TCP CLIENT
litepclient.java
importjava.io.*:;
importjava.net.*:
public class tepclient
InputStreamReader(clientsoc.getlnputStream
BufferedReader(new InputStreamReader(System.in): ).
try
while (true)
(System.out.println("Sever Says:"+in.readLine()):
userinput = stdin.readLine():
out.println(userinput):}
catch(Exception c)
System.exit(0):}
TCP SERVER
ltepserver.java
importjava.io.*:
importjava.net.*;
public class tcpserver
System.out.printin(TCP SERVER");
System.out.println("Server is ready to connect..."):
ServerSocket serversoc=new ServerSocket(9):
Socket clientsoc = serversoc.accept():
PrintWriter out =new PrintWriter(clientsoc.getOutputStream(), true);
BufferedReader in = new BufferedReader(new
InputStreamReader( clientsoc getInputStrcam);
String inputline:
BufferedReader stdin =new BufferedReader(new InputStreamReader( System.in)):
try!
while (true)!
inputline =stdin.readLine );out.println(inputline);
System.out.println("Client Says:"+in.readLine()):
catch( Exception e)
System.cxit(0):}
Sample Output:
CLIENT-SERVER CHATTING USING TCP
***** *
TCP SERVER
TCP CLIENT
RESULT:
Thus the java program for chat using TCP Sockets was executed.
Expt No: 3C Applications using TCP Sockets (like file
Date : transfer)
AIM:
To write a java program for file transfer using TCP Sockets.
CONCEPT:
Our application has a client and a server. Our aimis to send a file from the
Server machinc.
client machine
ALGORITHM:
Server
1. import java packages and create class file server.
2. Create anew server socket and bind it to the port.
3. Accept the client connection
4. Get the file name and stored into the BufferedReader.
5. Create a new object class file and realine.
6. If fle is exists then FileReader read the content until EOF is reached.
7. Stop the program.
Client
1. Import java packages and crcate class file server.
2. Create a new server socket and bind it to the port.
3. Now connection is established.
4. The object of a BufferReader class is used for storing data content which has been retrievei
from socket object.
5. The content of file is displayed in the client window and the connection is closed.
6. Stop the program.
PROGRAM:
FileTransferServer.java
import java.io.BufferedInputStream:
import java.io.File:
import java. io.FilelnputStrcam;
import java.io.OutputStrean:
import java.net. InetAddress;
import java.net.ServerSocket:
import java.net.Socket;
public class FileTransferServer!
hlc static void main( String|]| args)
Specity the file throws Exeception
File file =new Filc"'e:\datal.bin"):
FilelnputStream tis =new FilelnputStream( file ):
BufferedlnputStream bis =new
BufferedinputStream(fis):
Get socket's output stream
OutputStream os = socket.getOutputStream):
Read File Contents into contents array
bytel] contents:
long fileLength - file.length();
long current = 0:
long start = System.nanoTime():
while(current!-fileLength){
Int size= 10000:
if(fileLength - current >= size)
current += size:
else
size = (int)(fileLength - current):
current = fileLength:
FileTransferClient.java
import java.io. BufferedOutputStream;
import java.io.FileOutputStream:
import java.io.InputStream:
import java.net. InetA ddress;
import java.net.Socket:
FileTransferClient {
public class Exception (
main(String] args) throws
public static void
/Initialize socket
Socket(InetAddress.
s.getByName("localhost"),
Socket socket =new
byte[] contents = new
byte{10000]:
nath
,5000);,
/Initialize the FileOutputStream to the output file's full
FileOutputStream("e:l\data2. bin"):
FileOutputStream fos = new
BufferedOutputStream(fos):
BufferedOutputStream bos = new
getlnputStream();
InputStream is = socket.
read) call
I/No of bytes read in one
int bytesRead =0;
while((bytesRead=is.read(contents)!=-1)
bytesRead);
bos. write(contents, 0,
bos.flush();
socket.close();
System.out.println("File saved successfully!"):
}
OUTPUT:
SERVER
D:Javaljdkl.6\bin>java FileTransferServer
Sending file ...100% complete!File sent succesfully!
CLIENT
D:Javaljdkl.6\bin>java FileTransferClient
File saved successfully!
ADVANTAGES OF TCP
RESULT:
Thus the java program for File transfer using TCP Sockets was executed.
ExptNo:4
SOFTWARE REQUIREMENT:
CCompiler/Java Compiler
ALGORITHM:
Server
Step1: Start the program.
Step2: Create the socket for the server.
Step3: Bind the socket to the port.
Step4: Listen for the incoming client connection.
Step5: Receive the IP address from the client to be resolved.
Step6: Get the domain name for the client.
Step7: Check the existence of the domain in the server.
client.
Step8: If domain matches then send the corresponding address to the
Step9: Stop the program execution
Client
Stepl: Start the Program.
Step2: Create the socket for the client.
Server.
Step3: Connect the socket to the
tobe resolved.
Step4: Send the host name to the server
address and terminate the process
print the
corresponds then
scrver
Step5: Ifthe
PROGRAM:
UDPclient
.jo. *:
import java
import java.nct..
classUDPclient
DatagramSocket ds;
public
public static
static intclicntport-789,serverport-790;
args[])throws Exception
publicstatic void main(String
byte[ 1024]:
byte buffer[]-ncw
ds=new DatagramSocket(serverport); InputStreamReader(System in.
BufferedRcader(new
BufferedRcader dis=new
System.out.printin("serverwaiting");
InetAddressia=InetAddress.getLocalHost);
while(true)
System.out.println("Client:");
String str=dis.readLine():
if(str.equals("end")
break;
ds.send(new DatagramPacket(buffer,str.length(),ia,clientport));
buffer-str.getBytes();:
DatagramPacket(buffer,buffer.length):
DatagramPacket p=new
ds.receive(p);
String psx-new String(p.getData(),0,p.getLength();
System.out.println(Server:" +psx);}}}
UDP server
import java.io.*;
importjava.net.*;
classUDPserver
ds;
public static DatagramSocket
byte[1024);
public static byte buffer[]=new
public static intclientport-789,serverport=790;
Exception
public static void main(String args(|)throws
import java. lang. Object: //0Should be a
mpot java. util.*: capital
class arp
public static void main(String args[])
{try
Process p=Runtime.getRuntime().exec("arp -a");
BufferedReader br=new BufferedRcader(new
String str,strl="",st 1,st2: InputStreamReader(p.getInputStrcam))}:
while((str=br.readLine()!=nul)
strl+-str+"n":
StringTokenizer st=new StringTokenizer(str l, "n");
BufferedR eader brl-new BufferedReader(new InputStrean1
System.out. println("Enter the IP ADDRESS");
Reader(System.in)):
st2=brl.readLine();
while(st.hasMoreTokens())
stl=st.nextToken();
if(stl.indexOf(st2)!=-1)
System.out.println(stl ); } catch(Exception E)
(E.printStack Trace);
OUTPUT:
Enter the IP ADDRESS: 172.15.150,110
00-01-0C-33-1C-5D
Advantages:
RESULT:
is successfilly conmpleted.
Thus the ARP protocols
Expt No:5
Date: Use a too! like Wireshark to capturc
packets and examine the packels
AIM:
Canturing network packetsand cxamine it witlh tools such as Wireshark and tcpdump
CONCEPT:
JARDWARE REQUIREMENT:
iOFTWARE REQUIREMENT:
ALGORITHM:
Open Wireshark.
Set acapture filter, and select the interface on which to capture.
Start the capture.
Generate traffic by connecting to a website. pinging a remote device or attempting any other network connection.
Stop the capture.
ROGRAM:
AIM:
To
SIMULATING ARP PROTOCOL USING JAVA
stimulate ARP protocol using
CONCEPT:
ARP
JAV A
language.
C (Address
The Resolution
in a Protocolis )
logical (IP) address
framerouting table if the obtaisineda from the DNS if the
to be able sender sender is the host or it is
The host or to pass through the router. But the IP datagram found
the router physical must be
P
addresses of the sends an ARP query network. encapsulated in a
Because the sendersender and the IP
address
packet. The packet includes the
does not know the of the receiver. physical and
broadcast
Every
over the
network. nhysical address of the
host or router on the receiver, the query S
only the intended network receives and
packet. recipient recognizes processes
its IP address the ARP query
and sends back an packet, but
C
The response packet ARP response
contains the
HARDWARE REQUIREMENT: recipient's
IP and physical
addresses.
P- 11400 MHZ
speed
20GB Hard disk
64 MB RAM
SOFTWARE REQUIREMENT:
CCompiler/JavaCompiler
ALGORITHM:
PROGRAM:
import java.nct.*;
import java.io.*;
ds new DatagranSocket(clientpot):
SYst
Bautiee
r.
eo utpint
dReaderlh (p ress
dis-new
Buf
ctrle quit the
fere
to
dReader(newprogram")};
leAd res ia=lnetAd res .getLocalHos): InputSiean1keader(System.in) .
while(true){
DatagranPackct p-new DatagramP'acket(buffer,buffer.length):
ds.receive(p):
String psx rew
Stringp.ge
System.out.printl1(Cicnt:"
tData(0,0,
+psx):
p.g e
lnetA ddressib-lnetAddress.getByName(psx);
System.0ut.println("Server output:"+ib):;
String str-dis.readLine():
tLength);
if(str.cquals(end")
break:
buffer-str.getBytes():
ds.send(new DatagramP'acket(buffer,str.length).ia,serverport):}}}
OUTPUT
UDPelient
D:ProgramFiles\Javaljdkl.6.0\bin>javac UDPclient.java
D:\ProgramFilesWava\jdkl.6.0binjava UDPclient
Server waiting
Client:www.yaho0.com
UDPserver
D:\Program FilesJavaljdk1.6.0\bin>javac UDPserver.java
D:\Program Files\Wavaljdkl.6.0\bin>java UDPserver
Press ctrl te to quit the program
Client:Www.yahoo.com
Server output:www.yaho0.com 106.10.170.|15
AIM:
To stinulate RARP protocol using JAVA language.
CONCEPT
RARP (Reverse Address Resolution Protocol
RARP finds the logical address for a machine that knows only its physical address.
Each host or router is assigned one or more logical (IP) addresses. which are unique and
independent of the physical (hardware) address of the machine.
To create an IP datagram, a host or a router needs to know its own IP 2idress or
addresses.
HARDWARE REQUIREMENT:
P- 11400 MHZ speed
20GB Hard disk
64 MB RAM
SOFTWARE REQUIREMENT:
CCompiler/Java Compiler
ALGCRITHM:
utility packages
Step 1: Import the net, input output, language,
command arp -a " as parameter.
Step 2: Use the method exec with the
command in input stream.
Step 3: Store the result of the ping
and display the result.
Step 4: Process the input stream
Step 5: End the process
PROGRAM:
import java.net. *:
Import java.io.*:
O Should be a capital
import java.lang.Object; //
Import java.util.*:
class rarp
args[])
public static void main( String
try
Process p-Runtime.
BufferedReader
.getR
br=newunt im e().exec("arp -a"):
while((str=br.readLine())!=null)BufferedReader(new InputStreamR
String str,strl="",st1.st2:
Reader(p.getInputStream():
str1+=str+"n":
SringTokenizer
BufferedReader stFnew
brl=new
StringTokenizer(str1, "n"):
ADDRESS "):
Bufphysical
feredReader48-bit(newADDR
System.out.println("Enter the
InputStreamReader(System.
ENTER THE PHYSICAL in); 48BIT
st2=brl.readLine0:
while(st.hasMoreTokens()
stl=st.nextToken():
if('stl.index Of(st2)!=-l)
System.out.println(st 1);
catch(Exception E)
E.printStackTrace():
OUTPUT:
172.15.150.110
RESULT:
Thus the RARP protocols are successfully completed.
Simulation of Congestion
simulator(NS) and Control
Network Algorithms using NS.
Expt No: 6 Study of
Date :
composing of three routers and
network
a simple
OBJECTIVES:
segment is to create soffware.
practice Tracer
The goal of this using the Cisco Packet
devices RouterC
wohost end
.1
2
172.20.10.0
172.31.20.0
192.168.40.0
172.16.23.0 e
1
ef
Router B Host 2
2
Router A
we will try create
this scenario and individ:
topology for
Host 1
exhibit n.4 shall be our addresses to better reflect the
The network
from altered IP
ourselves, onlv with slightly
similar network learn about:
will
this task we
devices. During topology
1. Constructing the
2. Static routing
3. Dynamic routing
basic principa
the topology going to have to learn the
1.Constructing constructing our network, we are tracer, observe the panelin the low
Before we can begin vou have loaded
up the Packet
IOS. Once
of our router's
screen.
left section of the
2621XM 2311
1941 2620X4
1341
Routers
1841
routers. -
In this task. we shall only use
to the network.
panel is used to add devices
This anywhere ou
of connections. Place the router
devices and two types 1841 router model.
icon, then select the
Select the router
network.
nuer we ust adtt to the
nctvwork is labeled Roule) Double click on i
Physical Device View
HWICESW Zoom in Zoom Out
Onginal Size
NIWCAAG
WICAN
WIC-1ENET
WIC-1T
WICAM
WIC2T
NIC-COver
Customize Customize
Icon in Icon in
Physical View Logical View
Adding Mocules: Drag the module to an available slot on the device.
Semoving Modules: Drag the module from the device to thhe module list..
This opens up the contiguration panel for this router. It is divided into three scctions:
Phvsical: here you can add and remove physical interfaces on the router
Config: this is an overview of the router's active configurations. We will not be using this
pnelin this task
router's lOS.
CLI: this is the router's command line interface. Used to give commands to the
interfaces this router has at its
In the physical panel of the router you can see all the physical
console interface and an auxiliary
disposal. It will most likely have tvo FastEthernet intefaces, a
FastEthernet interfacces, but to connect one
interface. Individual LANs can be connected to the
intertaces. So we have to add them to the router.
router to another, we are going to need Serial
the router to power it off. The green
Click on the POWER switch in the physical panel of
light will disappear.
into Slot 1 of the router. Then use the power
Next, drag and drop the HWIC-2T module
Switch again to power up the router.
Physical Device Viow
leseOriginal Size
HWIGa1 Zoem In
WICAM
WIC 1ENET
WIC 1T
WIC-2AM
WIC-2T
WIC Cover
Custornize
Customize lcon in
Icon in Logical View
Physical View
eWIC-2T is a Cisco 2-Port Gerial Hiob-Speed WAN Interface Caro,
providing 2 serial ports.
shall need to
The HWIC-2T module contains two serial interfaces which we
to others in our network. Now that our router is sufficiently equipped to handle connect
the thisat Tote
We can start configuring it using the Command Line Interface (CLI). task hara
Chck on the CLIbutton in the top of the router's configuration panel.
This is the Command Line Interface of our router. Here you can type commands
willthen execute, very similar to a command prompt of other operating systems. The the IOs which
divided into three primary modes. If you enter the CLI for the first time, you will find
1OS is
in the User Executive mode. yourself
C1SCo 1841 (revision S.0) with 114688K/16384K bytes oi nemory.
Processor board ID FTXO947z18E
MS60 processoI: part nunber 0,. mask 49
2 FaStEthernet/IEEg e02.3 interface (s)
2 LoN-Speed serial{syncfasync) netWOrk interEace s)
191K bytes of NVRAM.
63488R bytes of ATA CompactFlash (Read/NEite)
Cisco IOS Software. 1841 software (c1841-ADVIPsERVIC3ESKS-M) . Version l2.4(1514
RELEASE SOFTHARE (tc2)
Iechnical Support: http:f/www.cisco.co/techsupport
Copyright (e) 1986-2007 by Cisco Systems, Ine.
Copiled Wed 18-Jul-07 04:52 by pt team
Router
The User Executive mode is the first mode of the IOS. It is identified by the " " symbol which
shows up at the end of the CLI
Router>
prompt:
The User Executive mode has very limited can be entered in
capabilities. Onlya few commands
configuration. In
this mode and none of them have the power to invoke a inthe router's
change the User
this task. we won't be using the User Executive mode at all. Once you are in
Executive Mode, type *enable" (no quotes) to moveetothe Privileged Executive mode.
Cisco 1841 revision 5.0) with 114688K/16384K bytes of menory
PrOcessor boazd ID F
Me 60 processor part
TXO947Z18E
nurber 0, nask 49
2 FastEthernet/IERE 802.3 interface (a)
bytes o£ VRAM
191K
6348BK bytes of ATA CompactElagh (Read/WEite)
Version 12.4415)I1,
Cisco IOs Software, 1841 So£tware C1B41-ADVIPSERVICESK9-M),
PELEASE SOFTARE tei
hnical SupPOKt: htt:/ww.cisco.com/techsupport
CopyEight (c) 1986-2007 by Cisco Systems, Inc.
Compiled Wed 18-Jul-07 04:52 by pt te am
enabi
symbol at
Executive mnode. This mode is identified by the # various
Privileged view the
You are now in the
The Privileged Executive is primarily used to the User
prompt.
the end of the command "disable" or exit" will move you back to the
configurations of the router.
Typing
commands of the Privileged Executive mode is
Executive mode. One of the
most useful
almost any configuration of the router.
command allows you to view router's physical
"show command. This brief'will display a short list of the
interface
For example, typing "show ip
interfaces. Prctocol
Router>enable
intertace brief OK? Method Status
Routertshcw ip IÆ-Address
Interface administratively down down
YES unset
unassigned administrativel down down
FastEthernet0/O
IES unset
nassigned administratively doWn doWn
FastEthernet0/1
YES unset
unassigned adminigtratively doWn doWn
Serial0/1/0 YES unset
nassiqned administratively down down
Serial0/1/1 YES unset
unassigned useful.
will not tell us anything help
Vlani interfaces, the list symbol "?* is used
as a
ROuterf
configured any of the parameters. The
yet using other
Since we haven't command
enter the show
Youcan also
command in the CLI. Typing "show ?" will display all possible paraneters for he s
command. Similarly, typing only the "9" command in the Privileged execut
display all commands supported in this mode. Do not worry though, we will iVonlye bemode yi
La
very limited number of thcm.
Now, use the configure terminal" command to enter the Global Configuration
ar
Routertconfigure termínal
One pe 1ine Znd with CNTL/Z
mode.
Enter COnEiguration commands,
Router (config) #
You are now inthe Global Configuration mode, as shown by the "Router(config#
The Global Configuration mode is used to change the configuration of the router.
the Global Configuration mode with the "exit" command. Let's start however by You canlpromrp
name of the router to Router-A, For this, use the hostname command followed hv
you wish to apply to the router. the changngnae
te
Type in hostname Router-A" to change the router's name to Router-A As you can
see, te
command prompt also changed to reflect the router's new name. This router is going to
the Router Ain our topology. As you can see in the exhibit at the start of this servez
serves as the gateway for the LAN 172.16.23.0 on which Host 1 is located. We
task, Route:
will use te
FastEthernet0/0interface to connect the router to this LAN.
Type in interface FastEthernet0/0" to access the FastEthernet0/0 interface.
You are now in the Interface Configuration mode for this interface. Every interface has is
independent configuration mode which can be accesses by using the "interface" COmma
followed bythe name of the interface you wish to access.
Now that we are in this interface, we need to change its IP address so that it becomes anar
the172.16.23.0 network.
Change the IP address of the interface using the following command:
IP address 172.16.23.1 255.255.255.0
Use the "no shutdown" command to activate the interface.
Router-A{canfig) #interface FastEthernet0/O
Router-A{config-if) #ip address 172.16.23.1 255.255.255.0
Router-A(config-if)$no shutdown
Router-A(config-if)
3LINK-5-CHANGED: Interface FastEthernet0/0, changed state to up
Router-A{config-if) $no shutdown
Router-A(config-if) *
The "IP address" is an Interface Configuration mode
that interface. This command has two
command used to assign an lP adares
parameters. The first one is the actual IP address e
to use. Here we used the 172.16.23.1 address, which is the first address on the 172.16.23
network. Gateways of a network are usually assigned the first
The second parameter is the subnet mask.. The
address of that network.
of an IP address are used to identifythe network255.255.255,0 masknetwork
portion. So this means can
that usethetheisaddres
172.16.23.1 to 172.16.23.254. Remember that the last address of a network is always usedasth
broadcast address and cannot be used as a host
address.
used the
Lastly, we 'no
are off by
default If shutdoWn command to tun the
you want to use
you needinterface
Notethat the following line an
LINK-5-CHANGED: was interface,
displayed: to
on. On router, interfaces a
activate it by using this command.
all
result of the no
return to
Int erface
shutthedown" command.FasThetEthIOSernet0/0, changed state up This also to
If you
command, you can Privileged
see that the Executive mode and informed us that the
use interface now actíve. is
is a
1841
Router