You are on page 1of 346

THIRUMALAI ENGINEERING

COLLEGE
KILAMBI,
KANCHIPURAM-631551
DEPARTMENT OF COMPUTER SCIENCE AND
ENGINEERING

Networks Laboratory

(CS 6411)

NAME

: _________________________________

REG. NUMBER

: _________________________________

SEMESTER

: _________________________________

YEAR

: ___________________________________

THIRUMALAI
ENGINEERING
COLLEGE
KILAMBI,
KANCHIPURAM631551
DEPARTMENT OF COMPUTER SCIENCE AND
ENGINEERING

BONAFIDE CERTIFICATE
This is to certify that this is a
bonafide work done by
Mr./Miss.______________________________
Reg.No._____________________

For the CS 6411 - Networks Laboratory as a
part

of

B.E.,

Computer

Science

and

Engineering course in Thirumalai Engineering
College, Kanchipuram during the year of 2011-2012.
The Record is found to be completed and satisfactory.

Head of the Department
Staff In-Charge

Submitted for the Practical Examination held on
________________

Internal Examiner
External Examiner

EX.NO:1(a) Implementation of Sliding Window
Protocol
AIM:
To write a java program to perform sliding window protocol
ALGORITHM:
1.Start the program.
2.Get the frame size from the user
3.To create the frame based on the
user request. 4.To send frames to
server from the client side.

5.If your frames reach the server it will send ACK signal to client
otherwise
it
will
send
NACK
signal
to
client.
6.Stop the program
Program :
imp
ort
java.
net.*
;
imp
ort
java.
io.*;
imp
ort
java.
rmi.
*;
p
u
b
l
i

c
c
l
a
s
s
s
l
i
d
s
e
n
d
e
r

{
public
static
void
main(String
a[])throws
Exception
{
ServerSocket ser=new ServerSocket(10); Socket s=ser.accept();
DataInputStream
in=new
DataInputStream(System.in);
DataInputStream
in1=new
DataInputStream(s.getInputStream()); String
sbuff[]=new String[8];
PrintStream p;
int sptr=0,sws=8,nf,ano,i; String ch;
do
{

out. .i+ +) { s b u f f [ s p t r ] = i n . p . for(i=1. p.parseInt(in.print("Enter the no.println("Enter "+nf+" Messages to be send\n").getOutputStream()).readLine()). nf=Integer. if(nf<=sws-1) { System. System. of frames : "). r e a d L i n e ( ) .println(nf).p=new PrintStream(s.out.i<=nf.

p r i n t l n ( s b u f f [ s p t r ] ) . } sws-=nf.print("Acknowledgment received").readLine()). . ano=Integer.parseInt(in1.out. System. sptr=++sptr%8.

readLine(). e q u a l s ( " y e .out.out. of frames exceeds window size").println(" for "+ano+" frames").System. } e l s e { System.println("The no.print("\nDo you wants to send some more frames : ").out. } w h i l e ( c h .println(ch). p. sws+=nf. break. ch=in. } System.

rptr=1.getLocalHost().net.getInputStream()).s " ) ) .getOutputStream()). PrintStream p=new PrintStream(s.rws=8.10). System.println(). String ch.io.*. do { . class slidreceiver { public static void main(String a[])throws Exception { Socket s=new Socket(InetAddress.*. String rbuf[]=new String[8]. s .out. int i=0. c l o s e ( ) . } } RECEIVER PROGRAM import java. DataInputStream in=new DataInputStream(s. import java.nf.

if(nf<=rws1) { .pa rseInt(in.nf=Integer.read Line()).

i + + ) { rptr=++rptr%8. i < = n f . rbuf[rptr]=in. System. out.println("The received Frame " +rptr+" is : "+rbuf[rptr]). } rws-=nf.readLine(). prin tln(" \nA ckn owl edg .out.f o r ( i = 1 . Syst em.

} w h i l . } else break. r e a d L i n e ( ) . rws +=n f.men t sent \n").pr intl n(rp tr+1 ). c h = i n . p.

e q u a l s ( " y e s " ) ) . } } OUTPUT: //SENDER OUTPUT E n t e r t h e n .e ( c h .

o . o f f r a m e s : 4 E n t e r 4 M e s s a g e s t o b e s e .

n d hiii h o w r u i a m f i n e how is evryone Acknowledgment received for 4 frames Do you wants to send some more frames : no //RECEIVER OUTPUT The received Frame 0 is : hiii The received Frame 1 is : how r u The received Frame 2 is : i am fine The received Frame 3 is : how is everyone .

Stop the program PROGRAM /SENDER PROGRAM import java.net. 6.EX. 4.Get the frame size from the user 3. 5.To send frames to server from the client side.NO:1(b) Implementation of Stop and Wait Protocol AIM To write a java program to perform sliding window protocol ALGORITHM: 1.*. 2. import java.Start the program.If your frames reach the server it will send ACK signal to client otherwise it will send NACK signal to client.io.*. p u b l i c c l a s s S e .To create the frame based on the user request.

n d e r { S o c k e t s e n d e r . O b j . O b j e c t O u t p u t S t r e a m o u t .

s t r . S t r i n g p a c k e t .e c t I n p u t S t r e a m i n . a c k . m s g . .

S e n d e r ( ) { } p u b l i c v o i d .i n t n . i = 0 . s e q u e n c e = 0 .

.. ").... System...println("reciver > "+str)... str=(String)in..flush(). System.. ..")... sequ ence =0..out.......getInput Stream())....rea dObject().out.println("Enter the data to send.. out=new ObjectOutputStream(s ender..........r u n ( ) { t r y { BufferedReader br=new BufferedReader(new InputStreamReader(System.. in=new ObjectInputStrea m(sender....out...... .println("Waiting for Connection ...... sen der = new Soc ket(" local host "....in)).........20 04)..getOutputStrea m())...... . System. out.....

n = p a c k e t . .p a c k e t = b r . r e a d L i n e ( ) . l e n g t h ( ) .

wr iteO bject (msg ). s e q u e n c e = .writeObject(msg). } out.i+1)).valueOf(sequence). } else if(i==n){ msg ="en d".o ut.c oncat( packe t. msg= msg.d o { t r y { if(i<n){ msg=String.subs tring(i .bre ak.

.( s e q u e n c e = = 0 ) ? 1 : 0 . f l u s h ( ) .pr int ln( "d ata se nt >" + ms g). o u t . Sy ste m. out .

..println ("waiting for ack ...ac k= (St rin g)i n.value Of(seque nce))){ i++.. System.. \n\n").....out...... } else{ System...o ut.....printl n("Time out resending data ...out... \n\n")... if(ack..r ea dO bje ct( )....... System.println("rec eiver > "+" packet recieved\n\n")...... sequence=(seque nce==0)?1:0.. } } c a t c h ( E x ..eq uals(Stri ng.

c l o s ." ). exiting.c e p t i o n e ) { } } w h i l e ( i < n + 1 ) . out. } catch(E xception e){} finally{ try{ i n . System.print ln("All data sent.

c l o s e ( ) . o u t . s e n d e r . c l o s e ( ) .e ( ) . } c a t c h ( E x c .

} } . s.e p t i o n e ) { } } } pu bli c sta tic vo id m ai n( St rin g ar gs []) { Se nd er s= ne w Se nd er( ).run().

sequence=0.data="".10).*. Reciever(){} p u b l i c v o i d r u n ( ) { t r y { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)).*. import java. Socket connection=null. public class Reciever{ ServerSocket reciever.//RECEIVER PROGRAM import java. int i=0. ObjectOutputStream out.ack. String packet. ObjectInputStream in.io.net. reciever = new ServerSocket(2004. .

connection =reciever.println >"+packet). sequence=0.getOutputStream()).out.out. println("wa iting for connection. .out.writeObject("conn ected .writeOb ject(String."). 1))==sequence) { data+=packet. ("\n\nreceiver } else { >"+packet +" duplicate data"). System.flush().valueOf( packet. in=new ObjectInputStream(co nnection. } else{ . if(Integer.a ccept(). out.readObject().substring(0. out. sequence=(sequence==0)?1:0.getInputStrea m()).out.println("Connection established :"). System. out=new ObjectOutputStream(conn ection.println ("\n\nreceiver } if(i<3){ out. do{ try{ packet=(String)in.su bstring(1). System..").i+ +. valueOf(seq uence)).System.

out. i=0.valueOf ((sequence+1) %2)).writeObject (String. .equals("end")). } } catch(Exception e){} }while(!packet.

out. println ("Data recive d="+d ata).wr iteObj ect("c onnect ion ended ."). } c a t c h ( E x c e p t i o n e ) { } f i n a .Syste m. out.

o u t . r e c i e v e r . c l o s e ( ) .l l y { try{ i n . c l o s e ( ) . c l o s e ( ) .

} c a t c h ( E x c e p t i o n e ) { } } } pu bli c sta tic vo id m ai n( St rin g ar gs []) { Re ..

run(). } } } OUTPUT: //SENDER OUTPUT W a i t i n g f o r C o n n e c t i o n .ci ev er s= ne w Re ci ev er( ). while(true){ s.

r e c i v e r > c o n n e c t e d . E n t e r t h e d a t a t o s e n d .

. T i m e o u t r e s e n d i n g d a t a d a ... receiver > packet recieved data sent>1a waiting for ack... receiver > packet recieved data sent>0n waiting for ack. receiver > packet recieved data sent>1y waiting for ack.m y n a m e data sent>0m waiting for ack........

...t a s e n t > 1 a waiting for ack... receiver > packet recieved data sent>0m waiting for ack. receiver > packet recieved data sent>1e ..

receiver > packet recieved All data sent. . exiting.. C o n n e c t i . //RECEIVER OUTPUT w a i t i n g f o r c o n n e c t i o n ...waiting for ack. .

o n e s t a b l i s h e d : receiver receiver receiver receiver receiver receiver receiver D a t a r e c i v e d = m y n a m e w a >0m >1y >0n >1a >1a duplicate data >0m >1e .

. .i t i n g f o r c o n n e c t i o n . .

Retrieve its own IP address using built-in function. Listen for new connection and when a connection arrives. Create a client socket and connect it to the server‟s port number. Display the date & time sent by the server. PROGRAM: D a t e C l i e . Stop. 4. 6. Close the input and output streams. 8. Read client‟s IP address sent by the client. 7. 7. 9. accept it. 4. 5.NO:2 Study of Socket Programming and Client Server mode AIM: To implement socket programming date and time display from client to server using TCP Sockets ALGORITHM: Server 1. Close the client socket. Close the server socket. 3. Send server‟s date and time to the client. 5. Close all streams.EX. Create a server socket and bind it to port. 2. 2. 6. 3. Client 1. Send its address to the server. Repeat steps 2-5 until the server is terminated. Stop. Display the client details.

n t . * . * . j a v a : i m p o r t j a v a . n e t . i m p o r t j a v a . i o .

c l a s s d a t e c l i e n t { p u bl ic st at ic v oi d m ai n ( St ri n g ar g s[ ]) { ..

D a t a I n p u t S t r e a m d i s . P r i n t S t r e a m .Socket soc. S t r i n g s d a t e .

g etLocal Host(). .p s . soc=new Socket(i a. t r y { InetAdd ress ia=InetA ddress.8020).

} c a t c h ( I O E x c e p t i o n dis=new DataInputStre am(soc.ge tOutputStream()). System.println("THE EXCEPTION is :"+e). e ) { System.rea dLine().println(ia).println( "THE date in the server is:"+sdate).out. sdate=dis. } . ps.getIn putStream()). ps=new PrintStream(soc.out.

java: i m p o r t j a v a .} } DateServer. n e t . i . * . i o . * . i m p o r t j a v a .

m p o r t j a v a . c l a s s d a t e s e r v e r { p u b li c s t . * . u t i l .

S o c .a ti c v o i d m a i n ( S tr i n g a r g s [ ] ) { S e r v e r S o c k e t s s .

k e t s . S t r i n g i n e t . D a t a I n p u t S t r e a m d i s . try { s s = n . PrintStream ps.

e w S e r v e r S o c k e t ( 8 0 2 0 ) .accept(). Date d=new Date(). w h i l e ( t r u e ) { s=ss. getOut putStre am()). . ps=ne w PrintSt ream(s.

get InputStrea m()).println("THE CLIENT SYSTEM ADDRESS IS :"+inet).close().println("The exception is :"+e). dis=new DataInputS tream(s. .println(d).out.out. } } c a t c h ( I O E x c e p t i o n e ) { System.re adLine().ps. inet=dis. System. ps.

C:\Program Files\Java\jdk1.java Note: dateserver.5.0\bin>javac dateserver.5.0\bin>java dateclient THE date in the server is:Sat Mar 19 13:01:16 GMT+05:30 2008 C:\Program Files\Java\jdk1.} } } OUTPUT: CLIENTSIDE: C:\Program Files\Java\jdk1.5.java uses or overrides a deprecated API.17 .0\bin>java dateserver THE CLIENT SYSTEM ADDRESS IS :com17/192.java Note: dateclient. Note: Recompile with -deprecation for details.5.0\bin> SERVERSIDE: C:\Program Files\Java\jdk1.java uses or overrides a deprecated API. Note: Recompile with -deprecation for details.5.0\bin>javac dateclient.21.168. C:\Program Files\Java\jdk1.

NO:3 Write a code simulating ARP /RARP protocols. .EX.

Start the program Using socket connection is established between client and server. Server maintains the table in which IP and corresponding MAC addresses are stored. i o . 2. Read the IP address which is send by the client. 4. Map the IP address with its MAC address and return the MAC address to client. 3. Send this IP address to server. Program Client: i m p o r t j a v a .Aim: To write a java program for simulating ARP protocols using TCP ALGORITHM: Client 1. Server returns the MAC address to client. 3. Start the program 2. Server 1. 4. Accept the socket which is created by the client. 5. 5. Get the IP address to be converted into MAC address.

* .. u t . i m p o r t j a v a . n e t . i m p o r t j a v a . * .

class Clientarp { p u b li c s t a ti c v o i d m a i n ( S tr i n g a r g s [ ] . * .i l .

in)).0. . Socket clsct=new Socket("127.1".) { t r y { BufferedReader in=new BufferedReader(new InputStreamReader(System.0.139).

println("Enter the Logical address(IP):"). String str1=in.getInputStream()). DataOutputStream dout=new DataOutputStream(clsct. System.readLine(). .DataInputStream din=new DataInputStream(clsct. w r i t e B y t e s ( s t r 1 + ' \ n ' ) .getOutputStr eam()). d o u t .out.

clsct. r e a d L i n e ( ) .S t r i n g s t r = d i n .out. System. } c a t c h .print ln("The Physical Address is: "+str).close().

. o u t .( E x c e p t i o n e ) { S y s t e m . p r i n t l n ( e ) .

i m p o r t j a v a .} } } Server: i m p o r t j a v a . * . i o .

. u t i l . n e t . c l a s s S e r . * . i m p o r t j a v a . * .

v e r a r p { p u b li c s t a ti c v o i d m a i n ( S tr i n g a r g s [ ] .

80."8A :BC:E3:FA"}.80".79. while(true) { DataInputStream din=new DataInputStream(obj1. for(int i=0."165.getInputStream()). String ip[]={"165.) { t r y { Serv erSo cket obj= new Serv erSo cket( 139).165. DataOutputStream dout=new DataOutputStream(obj1.1"}. Sock et obj1 =obj.lengt h. acce pt().i<ip.165. String str=din.getOutputStre am()). String mac[]={"6A:0 8:AA:C2".i++) { .readLine().

i f ( s t r . w r i t e . e q u a l s ( i p [ i ] ) ) { d o u t .

} } o b j .B y t e s ( m a c [ i ] + ' \ n ' ) . b r e a k . c l o s e .

( ) . } } c a t c h ( E x c e p t i o n e ) { S y s t e m . o u .

t . p r i n t l n ( e ) . } } } Output: E : \ n e t w o r k s > j a v a .

S e r v e r a r p E : \ n e t w o r k s > j a v a C l i e n t a r p .

1 .E n t e r t h e L o g i c a l a d d r e s s ( I P ) : 1 6 5 .

6 5 . 8 0 . 8 0 The Physical Address is: 6A:08:AA:C2 .

Server returns the IP address to client.Get the MAC address to be converted into IP address. Map the IP address with its MAC address and return the IP address to client. Client: i m p o r t j a v a .Send this MAC address to server. 4.EX.NO (3(b) Program for Reverse Address Resolution Protocol (RARP) using UDP Aim: To write a java program for simulating RARP protocols using UDP ALGORITHM: Client 1. using datagram sockets UDP function is established. Read the MAC address which is send by the client. 2. Server 1. 3. i . 4. 2.Start the program 2. 3. Server maintains the table in which IP and corresponding MAC addresses are stored. Start the program.

u t . i m p o r t j a v a . i m p o r t j a v a . n e t . * . * .o .

i l . c l a s s C l i e n t r a r p 1 2 { p u b li c s t a ti c v o i . * .

BufferedReader in=new BufferedReader(new InputStreamReader(System.d m a i n ( S tr i n g a r g s [ ] ) { t r y { DatagramSocket client=new DatagramSocket(). byte[] sendbyte=new byte[1024].0 . System.println("Enter the Physical address (MAC):") .0.g etByName("127.in)).out. InetAddress addr=InetAddress. byte[] receivebyte=new byte[1024].1").

client.send(sender).String str=in.1309). sendbyte=str. DatagramPacket sender=newDatagramPacket(sendbyte.getBytes().length).readLine(). .sendbyte .addr.receivebyte.length. DatagramPacket receiver=new DatagramPacket(receivebyte.

System.getData()).out. String s=new String(receiver.println("The Logical Address is(IP): "+s. } c a t c h ( E x c e p t i o n e ) { S y s t e m .receive(receiver).close().trim()). client.client.

. } } } Server: i m p o r t j a v a . i . p r i n t l n ( e ) . o u t .

i m p o r t j a v a . u . n e t . * . * . i m p o r t j a v a .o .

t i l . * . c l a s s S e r v e r r a r p 1 2 { p u b li c s t a ti c .

while(true) { byte[] sendbyte=new byte[1024]. byte[] receivebyte=new byte[1024].len .v o i d m a i n ( S tr i n g a r g s [ ] ) { t r y { DatagramSocket server=new DatagramSocket( 1309). DatagramPacket receiver=new DatagramPacket(receivebyte.receivebyte.

ge tPo rt() . server. Ine tA ddr ess add r=r ece ive r.gth).8 . 80.t rim().receive(receiver). int por t=r ece ive r. String s=str. String ip[] ={" 165. String str=ne w String (recei ver.ge tA ddr ess (). 165.ge tData( )).

length. 165. i++) .0". for(int i=0.1 "}. Stri ng mac[]= {"6A:0 8:AA:C 2".i<ip ."8A: BC:E3: FA"}. 79." 165.

DatagramPacket sender=newDatagramPacket(sendbyte.length. server.send(sender).sendbyt e. } } .getBytes().port). break.{ i f ( s . e q u a l s ( m a c [ i ] ) ) { sendbyte=ip[i].addr.

} } c a t c h ( E x c e p t i o n e ) { S y s t e m . o .b r e a k .

u t . } } } Output: I : \ e x > j a v a S e . p r i n t l n ( e ) .

r v e r r a r p 1 2 I : \ e x > j a v a C l i e n t r a r p 1 2 E n t .

80 .80.165.e r t h e P h y s i c a l a d d r e s s ( M A C ) : 6 A : 0 8 : A A : C 2 The Logical Address is(IP): 165.

maximum and average times.1: length of the IP address. Step 7:Stop the program.2: time required to get the details. Step 4: declare one BufferedReader stream class object. Step 3: To create a process object p to implement the ping command. Step 2: Include necessary package in java.4: minimum . 5.3: send packets . 4(a). Write a code simulating PING command Aim: To Write the java program for simulating ping command Algorithm Step 1: start the program. 5. 5. Step 5: Get thedetails of the server 5.EX-NO. Program: i m p o r t j a v . Step 6: print the results. receive packets and lost packets.

n e t . * . * .a . c l a s s p i n g s e r v e r . i o . i m p o r t j a v a .

System.out.print(" Enter the IP Address to be Ping : ").{ p u b li c s t a ti c v o i d m a i n ( S tr i n g a r g s [ ] ) { t r y { String str. BufferedReader buf1=new BufferedReader(ne .

String ip=buf1.in)).readLine(). P r o c e s s p = . g e t R u n t i m e ( ) .w InputStreamReader (System. R u n t i m e H = R u n t i m e .

e x e c ( " p i n g " + i p ) .H . g e t I n p u t . I n p u t S t r e a m i n = p .

BufferedRea der buf2=new BufferedRea der(new InputStream Reader(in)). r e a d L i n e ( ) ) ! = n .S t r e a m ( ) . w h i l e ( ( s t r = b u f 2 .

} } c a t c h . o u t . p r i n t l n ( " " + s t r ) .u l l ) { S y s t e m .

( E x c e p t i o n e ) { .

g e t M e s s a g e ( ) ) . p r i n t l n ( e .S y s t e m . o u t . } } .

11:bytes= 32 time<1ms TTL =128 Reply from 192.0.11:bytes= 32 time<1ms TTL =128 Ping statistics for 192.0.received=4.0.} Output: Enter the IP address to the ping:192.average=2ms .0.168.168.approximate round trip time in milli seconds: Minimum=1 ms.168.0.1 Packets: sent=4.168.11:bytes= 32 time<1ms TTL =128 Reply from 192.0.maximum=4ms.168.1: with bytes of data =32 Reply from 192.1 Pinging 192.0.lost=0(0% loss).11:bytes= 32 time<1ms TTL =128 Reply from 192.168.168.

i o .IOException. I n p u t S t r e a m R e a d .io.EX-NO.io. i m p o r t j a v a . Write a code simulating TRACEROUTE command Aim: To Write the java program for simulating Traceroute command Algorithm Program import java. import java.BufferedReader. 4(b).

e r . i m p o r t j a v a . A r r a y L i s t . u t i l . i m p o r t t r a c e .

r o u t e . p u b l i c a b s t r a c t c l a s s T r a c . T r a c e r o u t e I t e m .

p u b l i c T r a c e r o u t e ( ) { r u n = R u n t i m e .e r o u t e { private Runtime run. .

} public ArrayList<TracerouteItem> traceroute(String destination) { ArrayList<TracerouteItem> result = new ArrayList<TracerouteItem>(). String cmd = getTracerouteCommand(destination). e x e c . try { p r = r u n .g e t R u n t i m e ( ) . Process pr = null.

} c a t c h ( I O E x c e p t i o n e ) { } e. BufferedReader buf = new BufferedReader(new InputStreamReader( pr.printStackTrace().( c m d ) . String line = "". .getInputStream())).

t r y { w h il e (( li n e = b u f. r e a d L i n e () ) ! = n u ll ) { T r a c e r .

a d d ( i t e m ) .o u t e I t e m i t e m = p a r s e ( l i n e ) . } } catch(IOException e) . r e s u l t .

public abstract String getTracerouteCommand(String destination). r e t u r n r e s u l t .{ } return null. } public abstract TracerouteItem parse(String line). } Output .

2. Algorithm 1. .Start the program.NO 5. 5.To send frames to server from the client side. 4. s w i n g . * . Create a socket for HTTP for web page upload and download.Get the frame size from the user 3.Stop the program Program : Client i m p o r t j a v a x .If your frames reach the server it will send ACK signal to client otherwise it will send NACK signal to client.To create the frame based on the user request. 6. Aim: To write a java program for socket for HTTP for web page upload and download .EX.

a w t .i m p o r t j a v a . * . n e t . i m a g e . i m p o r t j a v a . i m p . * .

. i m a g e i o .o r t j a v a x . * . * . i m p o r t j a v a .ima ge.awt . Buf fere dIm age. imp ort java . i o .

I O E x c e p t i o n . Byt eAr ray Out put Stre am.io. i m p o r t . imp ort java . i m p o r t j a v a .imp ort java . File .io. i o .

").jpg")). baos. ").out. soc=new Socket("localhost".write(img. "jpg". I m a g e I O . ByteArrayOutputStream baos = new ByteArrayOutputStream(). .println("Reading image from disk.j a v a x . baos).flush(). i m a g e i o . try { System.ou t. ImageIO.prin tln(" Clien t is runni ng. img = ImageIO. BufferedImage img = null.read(new File("digital_image_proces sing. public class Client{ public static void main(String args[]) throws Exception{ Socket soc. Syste m.4000).

c l o s e ( ) . b a o s . .b y t e [ ] b y t e s = b a o s . t o B y t e A r r a y ( ) .

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.print
ln("Ima
ge sent
to
server.
");
dos.clos
e();
out.close();
}catch
(Exception
e)
{ System.out.println("Exception: " +
e.getMessage()); soc.close();
}
s
o
c
.
c
l
o
s
e
(
)
;
}
}
Server

i
m
p
o
r
t
j
a
v
a
.
n
e
t
.
*
;
i
m
p
o
r
t
j
a
v
a
.
i
o
.
*
;
i
m
p
o
r
t

j
a
v
a
.
a
w
t

.
i
m
a
g
e
.
*
;
i
m
p
o
r
t
j
a
v
a
x
.
i
m
a
g
e
i
o
.
*
;
i
m
p
o
r
t
j
a
v
a
x
.

s
w
i
n
g
.
*
;
class Server {
public static void
main(String args[])
throws
Exception{ ServerS
ocket server=null;
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
ByteArrayInpu
tStream(data);
BufferedImage
bImage
=
ImageIO.read(i
an);
JFrame f = new JFrame("Server");
ImageI
con
icon =
new
ImageI
con(bI
mage);
JLabel l
= new

JLabel(
);
l.setIcon(icon);
f.add(l);
f.pack();
f
.
s
e
t
V
i
s
i
b
l
e
(
t
r
u
e
)
;

}

}

Output
When you run the client code, following output screen would appear on
client side.

Step 5: declare the class rpc and extends the predefined class.b). Program: Client: i m p o r t j a . Step 7: declare the class server &create an object ob for the class rpc. Step 11:Stop the program. Step 2: include the necessary packages in java. Step 4: declare the remote methods inside the interface used.power( a. Step 3: create an interface as ucet and extends the predefined interface remote into it.b)and log(a). Step 10: the remote method contains the methods such as functions(a. Write a program to implement RPC(Remote Procedure Call) Aim: To write a java program to implement RPC (remote procedure call) Algorithm : Step 1: start the program. Step 6: unicast remote object an implement the interface ucet into it. Step 8: declare the class client Step 9: call the remote methods using the object ob which is the object of the interface ucet.EX-NO 6.

* . r m i . i o .v a . r m i . s e r v . i m p o r t j a v a . * . i m p o r t j a v a .

p u b l i c c l a s s c l i e n t r p c { p u b l i c s t a t i c v . * .e r .

lookup(s erverurl) .o i d m a i n ( S t r i n g a r g [ ] ) { t r y { String serverur l="rmi:// localhos t/serverr pc". ucet ob=(uce t) Naming.fun ction(10 .out.pr intln("the . int r=ob. System.5).

out. println("the answer of(a)^(b) is:"+t). System.power(1 0. int t =ob.o ut..println("the log value of the given number "+10+" is :"+d).answer of(a+b)^2 is:"+r).println( "error. } c a t c h ( E x c e p t i o n e ) { System.getMess age()).log(10 ). double d=ob."+ e.5). } } . System.out.

} .

Server: import java. p u b l i c c l a s s s .*. r m i . * . i m p o r t j a v a . s e r v e r .rmi.

e r v e r r p c { p u b l i c s t a t i c v o i d m a i n ( S t r i n g a r g [ ] ) .

} c a t c h . o b ) . r e b i n d ( " s e r v e r r p c " . N a m i n g .{ t r y { rpc ob=new rpc().

M a t h . . * . i m p o r t j a v a . l a n g .*.( E x c e p t i o n e ) { } }} RPC: import java.rmi.

* .i m p o r t j a v a . public class rpc extends UnicastRemoteObject implements ucet { p u b l i c r p c ( ) t h r o w . r m i . s e r v e r .

r .s E x c e p t i o n { } public int function(int a.int b)throws RemoteException { int m. m = ( a * a ) + ( b * b ) + ( 2 * a * b ) .

} public int power(int a.int b)throws RemoteExceptio n { i n t m = ( i n t ) M a t h . r e t u .e t u r n m . b ) . p o w ( a .

l o g ( a ) ) . p u b li c i . } public double log(int a)throws RemoteExce ption { r e t u r n ( M a t h . } } Ucet: import java.r n m .*.rmi.

public int power(int a.int b)throws RemoteException.n t e r f a c e u c e t e x t e n d s R e m o t e { public int function(int a. .int b)throws RemoteException.

} Output: J a v a c u c e t .public double log(int a)throws RemoteExcep tion. j a v a S t a r t r m i r e g i s t r y .

J a v a c r p c . j a v a r m i r p c j a v a c c l i e n t r p c . j a v a j a .

j a v a javac ucet.java j a v a c s e r v e . j a v a j a v a c r p c .v a c s e r v e r r p c .

r r p c . j a v a j a v a s e r v e r r p c j a v a c c l i e n t r p c . j a v a .

30258 .j a v a c l i e n t r p c the ans of (a+b)^2 is:225 the ans of (a)^(b) is :100000 the log value of the given number 10 is 2.

u t i l .Stop the program Program i m p o r t j a v a .To send frames to server from the client side. S c a n n e r .To create the frame based on the user request. 5. Implementation of Subnetting Aim: Write a program to implement subnetting and find the subnet masks. 6.EX-NO 7.Start the program. .Get the frame size from the user 3. 2.If your frames reach the server it will send ACK signal to client otherwise it will send NACK signal to client. 4. Algorithm : 1.

”). Strin g ip = sc.split(“\\.in) . //SPlit the string after every .ne xtLin e().prin t(“En ter the ip addr ess”) . Syste m. String split_bip[] = new String[4].c l a s s S u b n e t { public static void main(String args[]) { Scan ner sc = new Scan ner(S yste m. . String split_ip[]=ip.ou t.

for(int i=0.nextInt().println(“IP in binary is “+bip).print (“Enter the number of addresses: “). .i++){ split_bip[i] = appendZeros(Integer. } System. System.out.parseInt(split_ip[i]))). // “18” => 18 => 10010=>00010010 bip += split_bip[i].i<4.toBinaryString(Integer.out.//split binary ip String bip = “”. int n = sc.

out.i-) //Get first address by ANDing last n bits with 0 fbip[i] &= 0. i<32. S t r i n g f i p [ ] = { “ ” .log(2)). log 120/log 2 gives log to the base 2 => 6. ” .i++) fbip[i] = (int)bip. int mask = 32-bits. ceil gives us upper integer */ System.i>31-bits. System.println(“Number of bits required for address = “+bits).out. //convert cahracter 0.charAt(i)-48.1 to integer 0.1 for(int i=31. for(int i=0.log(n)/Math. //Calculation of first address and last address int fbip[] = new int[32]. /*eg if address = 120. ” ” .//Calculation of mask int bits = (int)Math.println(“The subnet mask is = “ +mask).9068.ceil(Math.

pr . Sy ste m. ” ” } . i < 3 2 . f o r ( i n t i = 0 .” . i + + ) fip [i/ 8] = ne w Str ing (fi p[i /8] +f bip [i]) . out .

i>31-bits. } System.out.charAt(i)48. i<32. S t r i n g l i .println().”).i+ +) { System .par seInt(fi p[i].out. if(i! =3) System .out.2)) . for(int i=0.1 to integer 0.i <4 . for (in t i= 0.pri nt(“. //convert cahracter 0. int lbip[] = new int[32].i++) lbip[i] = (int)bip.i-) //Get last address by ORing last n bits with 1 lbip[i] |= 1.pri nt(Inte ger.1 for(int i=31.int (“ Fir st ad dre ss is = “).

” ” } . ” ” .p [ ] = { “ ” . i + + ) l i p [ i / 8 ] = . ” ” . i < 3 2 . f o r ( i n t i = 0 .

S y s t e m . p r i n t ( “ L . o u t .n e w S t r i n g ( l i p [ i / 8 ] + l b i p [ i ] ) .

par seInt( lip[i]. i + + ) { Syste m.out . if(i! =3) . f o r ( i n t i = 0 . 2)). i < 4 .a s t a d d r e s s i s = ” ) .print (Integ er.

} static String appendZeros(String s){ St ri ng te m p = ne w St ri ng (“ 00 00 00 00 ″).print (“. o u t .”).out . p r i n t l n ( ) . } S y s t e m . .Syste m.

su bs tri ng (s. le ng th ()) + s.ret ur n te m p. } } .

110.Output Enter the ip address: 100.10 IP in binary is 011001000110111 010010110000010 10 Enter the number of addresses: 7 Nu mb er of bits req uire d for add ress = 3 The sub net mas k is = 29 F i r s t a d d r e s s .150.

1 5 0 .i s = 1 0 0 . 1 1 0 . 1 1 0 . 8 L a s t a d d r e s s i s = 1 0 0 .

1 5 . 1 5 0 ..

4.java import java.If your frames reach the server it will send ACK signal to client otherwise it will send NACK signal to client. import java.io.Get the frame size from the user 3.*. 6.Start the program.EX-NO 8. Applications usingTCP Sockets A.net.To create the framebased on the user request. 5.*. p u b l i c c l a s s E S e .To send frames to server from the client side. 2. Echo client and Echo server Aim To write a java program for application using TCPSockets Links Algorithm 1.Stop the program EchoServer.

r v e r { p u b li c s t a ti c v o i d m a i n ( S tr i n g a r g s [ ] ) { S e r v e r S .

S t r i n g l i n e . P .o c k e t s = n u l l . D a t a I n p u t S t r e a m i s .

S o c k e t c = n u l l .r i n t S t r e a m p s . t r y { s = n e w S e r v .

} c a t c h ( I O E x c e p t i o n e ) { S y s t e .e r S o c k e t ( 9 0 0 0 ) .

readLine(). is=new DataInput Stream(c. getInputSt ream()). while(true ) { line=is. ps=new PrintStrea m(c.accept(). o u t . p r i n t l n ( e ) . . } t r y { c=s.getOu tputStrea m()).m .

p s . } } c a t c h ( I O E x c e p t i o n e ) . p r i n t l n ( l i n e ) .

o u t . } } } EClient.{ S y s t e m .java i m p o r t j a v . p r i n t l n ( e ) .

i o .a . * . n e t . p u b l i c c l a s s E C l i e . i m p o r t j a v a . * .

n t { p u b l i c s t a t i c v o i d m a i n ( S t r i n g a r g [ ] ) { .

D a t a I n p u t S t r e a m i s .S o c k e t c = n u l l . i . S t r i n g l i n e .

P r i n t S t r e a m o s . c=new Socket(ia. 9000). try { } c a t c h ( I O E x c e p t i o InetAddre ss ia = InetAddre ss.s 1 .getLoc alHost(). .

o u t . } t r y { os=new PrintStream(c.n e ) { S y s t e m . p r i n t l n ( e ) . while(true) .getOutputStream()). is1=new DataInputS tream(c.in). is=new DataInputStream(System.get InputStrea m()).

r e a d L i n .{ S y s t e m . p r i n t l n ( " C l i e n t : " ) . l i n e = i s . o u t .

out. . }} c a t c h ( I O E x c e p t i o n e ) { System.println("Socket Closed!").readLine()). System.e ( ) . os.println(line).out .println("Server:" + is1.

5.0\ bin> Client . Note: Recompile with -deprecation for details.0\ bin>javac EServer.0\ bin>java EServer C:\Program Files\Java\jdk1.java Note: EServer.} } } O u t p u t S e r v e r C:\Program Files\Java\jdk1.5. C:\Program Files\Java\jdk1.java uses or overrides a deprecated API.5.

C:\Program Files\Java\jdk1.java uses or overrides a deprecated API.5. Note: Recompile with -deprecation for details. C:\Program Files\Java\jdk1.0 \bin>java EClient Client: Hai Server S e r v e r : H a i S e r v e r C l i e n t : Hello S e r v .5.0 \bin>javac EClient.java Note: EClient.

e r : H e l l o C l i e n t : end S e r v e r : e n d C l i e n t : ds Socket Closed! .

Chat .B.

i m p o r t j a v a .Aim Write a Program client -server application for chat using UDP Sockets Program UDPserver.java i m p o r t j a v a . * . n e . i o .

println("press ctrl+c to quit the program"). c l a s s U D P s e r v e r { public static DatagramSocket ds.t .getData . String psx=new String(p. public static void main(String args[])throws Exception { ds=new DatagramSocket(clientport). BufferedReader dis=new BufferedReader(new InputStreamReader(System. public static int clientport=789.receive(p). * . ds. InetAddress ia=InetAddress.buf fer. System. while(true) { DatagramPacket p=new DatagramPacket(buffer.length).in)).geyLocalHost(). public static byte buffer[]=new byte[1024].out.serverport=790.

out. o u t .getLength ()). p r i n t l n ( " S e r v e r : " ) .().0. System.print ln("Client:" + psx). S y s t e m .p. S t r i n g s t r .

r e a d L i n e ( ) . i f ( s t r . e q u a l s ( " e n d " ) ) b r e a .= d i s .

d s . g e t B y t e s ( ) .k . b u f f e r = s t r .str. s e n d ( n e w DatagramPack et(buffer.le ngth().serve rport)).ia. } } } .

. n e t . * . * .java i m p o r t j a v a . i m p o r t j a v a .UDPclient. i o .

public static int clientport=789.c l a s s U D P c l i e n t { public static DatagramSocket ds.serverport=790. .

in)). InetAdd ress ia=InetA ddress.out. while(tr ue) { S y s t e m . o u t . System. ds=new DatagramSocket(serverport).println("server waiting"). BufferedReader dis=new BufferedReader(new InputStreamReader(System.public static void main(String args[])throws Exception { byte buffer[]=new byte[1024]. p r i n t l n ( " C l .g etLocal Host().

e q . i f ( s t r . r e a d L i n e ( ) .i e n t : " ) . S t r i n g s t r = d i s .

} } } .0. ds.clientport)).u a l s ( " e n d " ) ) b r e a k .print ln("Server:" + psx).getBytes(). buffer=str.l ength().p.str. ds.send(new DatagramPacket(buffer.out.getData ().buf fer. DatagramPacket p=new DatagramPacket(buffer.length). System.getLength ()). String psx=new String(p.ia.receive(p).

5.O U T P U T : S e r v e r C:\Program Files\Java\jdk1. 5.0\bin>java UDPserver press .java C:\Program Files\Java\jdk1.0\bin>javac UDPserver.

ctrl+c to quit the program Client:Hai Server .

0\bin>java UDPclient server waiting .Server: Hello Client C l i e n t : H o w a r e Y o u S e r v e r : I am Fine Client C:\Program Files\Java\jdk1. 5.5.0\bin>javac UDPclient.java C:\Program Files\Java\jdk1.

Client: Hai Server S e r v e r : H e l l o C l i e C l i e n t : How are You S e r v e r : I a m F i n e .

C l i e n t : end C. File Transfer Program File Client i m p o r t j a v a . .

n e t . i m p o r t j a v a . . * .i o . i m p o r t j a v a . * .

.u t i l . * .

class Clientfile { { T r y public static void main(String args[]) { BufferedReader in=new BufferedReader(new InputStreamReader(System.rea dLine(). Socket clsct=new Socket("127. DataOutputStream dout=new DataOutputStream(clsct. dout. println("En ter the new file name:").println("Enter the file name:").readLine().writeBytes(str+'\n').getOutputStr eam()). String str=in.getInputStream()). FileWriter f=new F i l e W .out. String str2=in.1". System.in)).ss.out. DataInputStream din=new DataInputStream(clsct.0.0. String str1. System.139).

r i t e r ( s t r 2 ) . w h i l e ( t r u . c h a r b u f f e r [ ] .

e
)
{ str1=din.readLine();
if(str1.equals("-1")) break;
System.out.println(str1);
buffer=new char[str1.length()];
str
1.
ge
tC
ha
rs(
0,s
tr1
.le
ng
th(
),b
uff
er,
0);
f.
wr
ite
(b
uff
er)
;
}
f.close();
c
l
s
c
t
.
c
l

o
s
e
(
)
;

}
c
a
t
c
h
(
E
x
c
e
p
t
i
o
n
e
)

{
S
y
s
t
e
m
.
o

u
t
.
p
r
i
n
t
l
n
(
e
)
;
}
}
}

Server
i
m
p
o
r
t
j
a
v
a
.
i
o
.
*
;

i
m
p
o
r
t
j
a
v
a
.
n
e
t
.
*

;

i
m
p
o
r
t
j
a
v
a
.
u
t
i
l
.
*
;

c
l
a
s
s
S
e
r
v
e
r
f
i

l
e
{p
ubl
ic
sta
tic
voi
d
ma
in(
Str
ing
arg
s[]
)
{
T
r
y

{
Server
Socket
obj=ne
w
Server
Socket
(139);
while(t
rue)
{
Socket obj1=obj.accept();
DataInputStream din=new DataInputStream(obj1.getInputStream());
DataOutputStream
dout=new
DataOutputStream(obj1.getOutputStre
am()); String str=din.readLine();
FileReader f=new FileReader(str);

String s. w h i l e ( ( s = b .Buffere dReade r b=new Buffere dReade r(f). r e a d L i n e ( ) ) ! = n u l l ) { S y s .

w r i t e B y t e s ( s + ' \ n ' . o u t . d o u t . p r i n t l n ( s ) .t e m .

} f.close(). } } catch(Exception e) { System.println(e).} } } .out.writeBytes("-1\n").) . dout.

Output File content C o m p u t e r n e t w o r k s j h f c g s a u f jbsdava j b v u e s .

t x t server .a g v c l i e n t E n t e r t h e f i l e n a m e : s a m p l e .

C o m p u t e r n e t w o r k s j h f c g s a u f jbsdava jbvuesagv client E n t e r t h e n e w .

t x t C o m p u t e r n e t w o r k s j h f c g s a .f i l e n a m e : n e t .

u
f
jbsdava
jbvuesagv
Destination file

C
o
m
p
u
t
e
r
n
e
t
w
o
r
k
s
j
h
f
c
g
s
a
u
f
jbsdava
jbvuesagv

EX-NO 9. Applications using TCP and UDP
Sockets like DNS, SNMP and File
Transfer
Aim

To write a java program for DNS application
Algorithm
1.Start the program.
2.Get the frame size from the user
3.To create the frame based on the user request.
4.To send frames to server from the client side.
5.If your frames reach the server it will send
ACK signal to client otherwise it will send
NACK signal to client.
6.Stop the program
Program
/
U
D
P
D
N
S
S
e
r
v
e
r

U
d
p
d
n
s
s
e
r
v
e
r

.
j
a
v
a
i
m
p
o
r
t
j
a
v
a
.
i
o
.
*
;
i
m
p
o
r
t

j
a
v
a
.
n
e
t
.
*
;
p
u
b
l
i
c
c
l
a
s
s
u
d
p
d
n
s
s
e
r
v
e
r

{

private static
int
indexOf(Strin
g[]
array,
String str)
{
str = str.trim();
f
o
r
(
i
n
t
i
=
0
;
i
<
a
r
r
a
y
.
l
e
n
g
t
h
;

i
+
+
)

{
i
f
(
a
r
r
a
y
[
i
]
.
e
q
u
a
l
s
(
s
t
r
)
)
r
e
t
u

out.140".19".com". } r e t u r n 1 .184".85.189.com"}. System."80. String[] ip = {"68.println("Press Ctrl + C to Quit").r n i ."cricinfo.92. "facebook. } public static void main(String arg[])throws IOException { String[] hosts = {"yahoo.63.148.206. "209.16"}. "69. "gmail.com".168.180. while (true) .com".

if(indexOf (hosts. serversocket. receivedata. String capsent. System. byte[] senddata = new byte[1021]. int port = recvpack.getData()).{ DatagramSocket serversocket=new DatagramSocket(1362).receive(recvpack).g etAddress( ).println( "Request for host " + sen). sen) != -1) c a p s e n t new . String sen = new String(recvpack. byte[] receivedata = new byte[1021].o ut.length). DatagramPacket recvpack = DatagramPacket(receivedata. InetAddre ss ipaddress = recvpack.g etPort().

= i p [ i n d e x O f ( h o s t s . e l s e c a p s e . s e n ) ] .

s e n d d a t a = c a p s e .n t = " H o s t N o t F o u n d " .

length. senddata.ipaddress.send(pack).n t . DatagramPacket pack = new DatagramPacket (senddata. serversocket. . c l o s e ( ) . g e t B y t e s ( ) . s e r v e r s o c k e t .port).

} } } / / U D P D N S C l i e n t U d p d n s c l i e .

i o . . i m p o r t j a v a .n t . * . * . n e t . j a v a i m p o r t j a v a .

in)). new new .p u b l i c c l a s s u d p d n s c l i e n t { public static void main(String args[])throws IOException { BufferedReader br = BufferedReader(new InputStreamReader(System. DatagramSocket clientsocket = DatagramSocket().

i f ( a r g s .InetAddress ipaddress. l e n g t h = = 0 ) i p a d d r e s s .

byte[] senddata = new byte[1024 ]. else ipaddress = InetAddre ss.getByN ame(args[ 0]). .getLocalHost().= InetAddress.

b y t e [ ] r e c e i v e d a t a = n e w b y t e [ 1 0 2 4 ]. i n t p o rt a d d r = .

Senddata = sentence.receive(recvpack). Syste m. ipaddress.lengt h).portaddr). DatagramPacket recvpack =new DatagramPacket(receivedata.send(pack). clientsocket.length.cl ose(). DatagramPacket pack = DatagramPacket(senddata.getBytes(). System.senddata. String senten ce = br.out.pri ntln("IP Address: " + modified). clientsocket.receivedata.1 3 6 2 . } } O U new . String modified = new String(recvpac k. print(" Enter the hostna me : ").rea dLine( ).out.getData()). clientsocket.

j a v a j a v a u d p d .T P U T S e r v e r j a v a c u d p d n s s e r v e r .

com Client j a v a c u d p d n s c l i e n t . j a v a .n s s e r v e r Press Ctrl + C to Quit Request for host yahoo.com Request for host cricinfo.com Request for host youtube.

j a v a u d p d n s c l i e n t E n t e r t h e h o s t n a m e : y a h .

c o m I P A d d r e s s : 6 8 . 2 0 6 . 1 8 4 j a v a u . 1 8 0 .o o .

d p d n s c l i e n t E n t e r t h e h o s t n a m e : c r i c i n f o .

. 1 6 8 . c o m I P A d d r e s s : 8 0 . 1 4 0 j a v a u d p . 9 2 .

c o .d n s c l i e n t E n t e r t h e h o s t n a m e : y o u t u b e .

m I P A d d r e s s : H o s t N o t F o u n d .

To send frames to server from the client side. 2. im po rt or g.s n m p4 j.IOException.To create the frame based on the user request.Stop the program Program import java.SNMP Aim To write a java program for SNMP application program Algorithm 1.io. im po rt or g.Get the frame size from the user 3.Start the program. 4.B. 5.s .If your frames reach the server it will send ACK signal to client otherwise it will send NACK signal to client. 6. C o m m un ity Ta rg et.

i m p o r t o r g . s .P D U.n m p4 j. s n m p 4 j . S n m p . i m p o r t o r g .

Re spons eEve nt.s nmp4 j.TransportMapping. Addr ess. impo rt org.eve nt.smi.s nmp4 j. impo rt org. import org. impo rt org.n m p 4 j . im po rt or .snmp4j.mp. Snmp Const ants. T a r g e t .s nmp4 j.

G en eri cA dd res s.OctetString.s n m p4 j.s n m p4 j.g. * Constructor * @param add */ .smi. String address = null.VariableBinding.DefaultUdpTransportMapping.snmp4j. import org. import org.smi. public class SNMPManager { Snmp snmp = null. import org. im po rt or g.s mi .s mi .transport.snmp4j.snmp4j.O ID .

.p u b l i c S N M P M a n a g e r ( S t r i n g a d d ) { address = add.

1.1. as discussed in previous article */ String sysDescr = client.1.0 => SysName * => MIB explorer will be usefull here. System..getAsString(new OID(".5.2. * @throws IOException */ private void start() throws IOException { .6. /** * OID .1.0.1.3.public static void main(String[] args) throws IOException { /** * Port 161 is used for Read and Other operations * Port 162 is used for the trap gene ratio n */ SNMPManager client = new SNMPManager("udp:127.1. } /** * get any answers because the communication is asynchronous * and the listen() method listens for answers.1.out.1/16 1").6.0")).start()..0 => SysDec * OID .1.1.3.2.1.1. client.3.println(sysDescr).1.0.1.6.1.2.

snmp = new Snmp(transport). / / D o n o t f o r g e t t h i s l i n e ! t r a n s p o r .TransportMapping transport = new DefaultUdpTransportMapping().

t . l i s t e n ( ) . } /** * Method which takes a single OID and returns the response from the agent as a String. * @param oid * @return * @throws IOException */ .

return event.toS tring(). } /** * This method is capable of handling multiple OIDs * @param oids * @return * @throws IOException */ public ResponseEvent get(OID oids[]) throws IOException { PDU pdu = new PDU(). for (OID oid : oids) { p d u .g et(0).public String getAsString(OID oid) throws IOException { ResponseEvent event = get(new OID[] { oid }).getResponse(). a d d ( n e w V a r i .getVariable().

GET). which contains information about * where the data should be fetched and how. ResponseEvent event = snmp. } throw new RuntimeExce ption("GET timed out"). } /** * This method returns a Target. null). } pdu.setType(PDU. if(event != null) { return event. getTarget(). * @return .a b l e B i n d i n g ( o i d ) ) .send(pdu.

target.set Version(S nmpCons tants. target. CommunityTarget target = new CommunityTarget(). }} . target. return target. target.setTimeout(1500).setRetries(2).pars e(address). target.vers ion2c).setAddr ess(targetAdd ress).*/ private Target getTarget() { Address targetAddress = GenericAddress.setCom munity(new OctetString(" public")).

1 (Build 2600 Multiprocessor Free) .Software: Windows 2000 Version 5.OUT PUT Hardware: x86 Family 6 Model 23 Stepping 10 AT/AT COMPATIBLE .

.

C. * . i o . . File Transfer AIM To write a java program for applaction using TCP and UDP Sockets Links Program F i l e C l i e n t i m p o r t j a v a .

* . * .i m p o r t j a v a . i m p o r t j a v a . n e t . u t i l .

writeBytes(str+'\n').println("Enter the file name:").in))..out. println("En . dout. System. Socket clsct=new Socket("127.getOutputStr eam()).1".139).0. c l a s s C l i e n t f i l e { { T r y public static void main(String args[]) { BufferedReader in=new BufferedReader(new InputStreamReader(System.0. System.out.getInputStream()).readLine(). DataInputStream din=new DataInputStream(clsct. String str=in. DataOutputStream dout=new DataOutputStream(clsct.

FileWriter f=new F i l e W r i t e r ( s t r 2 ) .ss.rea dLine().ter the new file name:"). String str2=in. String str1. c h a r b u f f e r [ .

w h i l e ( t r u e ) { str1=din. str 1. buffer=new char[str1.println(str1). 0).length()]. System.readLine(). f.equals("-1")) break.out.s tr1 .le ng th( ).b uff er. ge tC ha rs( 0. wr ite (b uff . if(str1.] .

er) . } c a t c h ( E x c e p t i o n . } f. c l s c t .close(). c l o s e ( ) .

p r i n t l n ( e ) .e ) { S y s t e m . o u t . } } } .

i o . * .Server i m p o r t j a v a . i m p o r t j a v a . n e t . * .

u t i l . c l a s s S e r v e r f i . i m p o r t j a v a .. * .

getInputStream()).l e {p ubl ic sta tic voi d ma in( Str ing arg s[] ) { T r y { ServerSocket obj=new ServerSocket(139). String str=din. DataOutputStream dout=new DataOutputStream(obj1.getOutputStre am()). while(true) { Socket obj1=obj. F i l e R . DataInputStream din=new DataInputStream(obj1.readLine().accept().

e a d e r f = n e w F i l e R e a d e r ( s t r ) . B u f f e r e d R e a d e r .

b = n e w BufferedReader(f). r e a d L i n e ( ) ) ! = n u l l ) { S y s t e m . String s. w h i l e ( ( s = b .

. o u t . p r i n t l n ( s ) . w r i t e B y t e s ( s + ' \ n ' ) . . d o u t .

out.} } } . dout.writeBytes("-1\n").close().} f.println(e). } } catch(Exception e) { System.

Output File conten t Comp uter netwo rks jhfcgs auf jbsdav a jbvues agv client E n t e r t h e f i l e n a m .

e : s a m p l e . t x t s e r v e r C o m p u t e r n e t w o .

r k s j h f c g s a u f j b s d a v a j b v u e s a g v .

c l i e n t E n t e r t h e n e w f i l e n a m e .

: n e t . t x t C o m p u t e r n e t w o r k s j h f .

c g s a u f jbsdava jbvuesagv Destination file C o m p u t e r n e t w o r k s j h f c g s a .

u f j b s d a v a j b v u e s a g v .

and Simulation of Congestion Control Algorithms using NS N E T W O R K S I M U L A T O R ( N S 2 ) N s o v e r v .and Simulation of Congestion Control Algorithms using NS Aim: To Study of Network simulator (NS). Study of Network simulator (NS).EX-NO 10.

Queu ing disciplines. Windows and Mac        Ns unctionalities Routing.26. Transportatio n. QoS Wireless Ad hoc routi ng.i e w  Ns programming: A Quick start   Case study I: A simple Wireless network   Case study II: Create a new agent in Ns  Ns overview   Ns Status   Periodical release (ns2. mobi le IP. Feb 2003)   Platform support   FreeBSD. Traffic sources. Linux. senso rMA C Traci ng. visua lizati on . Solaris.

links) and the events (data transmissions. and those events are processed in order. Network simulators can also provide other tools to facilitate visual analysis of trends and potential trouble spots. Trace files log every packet. the time required for an accurate answer can be extremely large. if congestion is high. with some events triggering future events— such as the event of the arrival of a packet at one node triggering the event of the arrival of that packet at a downstream node. packet error etc. To estimate the likelihood of a buffer overflow in a network. An important output of simulations are the trace files. in which a list of pending "events" is stored. every event that occurred in the simulation and are used for analysis. The network model / configuration describes the state of the network (nodes.and vario us utiliti e NS( Netw ork Simu lators ) Most of the commercial simulators are GUI driven. then estimation of the average occupancy is challenging because of high variance. Most network simulators use discrete event simulation. . while some network simulators are CLI driven. switches. Simulation of networks is a very complex task.).routers. Specialized techniques such as "control variates" and "importance sampling" have been developed to speed simulation. For example.

can all be simulated with a typical simulator and the user can test.. With the help of simulators. Various types of Wide Area Network (WAN) technologies like TCP. mobile units etc. links. routers. simulating a scenario with several nodes or experimenting with a new protocol in the network. network simulators are relatively fast and inexpensive. bridges. OPNET (proprietary software) 3. and Local Area Network (LAN) technologies like Ethernet. ordered after how often they are mentioned in research papers: 1.Examples of network simulators There are many both free/open-source and proprietary network simulators. analyze various standard results apart from devising some novel protocol or strategy for routing etc. Examples of notable network simulation software are. ns (open source) 2. Compared to the cost and time involved in setting up an entire test bed containing multiple networked computers. one can design hierarchical networks using various types of nodes like computers. switches. Network simulators are particularly useful in allowing researchers to test new networking protocols or changes to existing protocols in a controlled and reproducible environment. token rings etc. IP etc. Network simulators are also widely used to simulate battlefield networks in Network-centric warfare . They allow engineers. NetSim (proprietary software) Uses of network simulators Network simulators serve a variety of needs. ATM. hubs. routers and data links. A typical network simulator encompasses a wide range of networking technologies and can help the users to build complex networks from basic building blocks such as a variety of nodes and links. researchers to test scenarios that might be particularly difficult or expensive to emulate using real hardware for instance.

Minimally. Packet loss occurs when one or morepacketsof data travelling across a computer networkfail to reachtheir destination. ranging from the very simple to the very complex. the more difficult it is for transportlayer protocols to maintain high bandwidths. .There are a wide variety of network simulators. The larger the value of packet loss. Graphical applications allow users to easily visualize the workings of their simulated environment. as well as to frequency and patterns of loss among longer packet sequences is strongly dependent on the application itself. The amount of packet loss during the steady state is another important property of a congestion control scheme. the links between those nodes and the traffic between the nodes. the other two being bit errorand spurious packets caused due to noise. Packets can be lost in a network because they may be dropped when a queue in the network node overflows. a network simulator must enable a user to represent a network topology. Packet loss is distinguished as one of the three main error types encountered in digital communications. specifying the nodes on the network. but may permit more advanced forms of customization. Textbased applications may provide a less intuitive interface. More complicated systems may allow the user to specify everything about the protocols used to handle traffic in a network. the sensitivity to loss of individual packets.

and if having waited for service. The larger the valueof delay.g. . the more difficult it is for transport layer protocols to maintain highbandwidths.Throughput This is the main performance measure characteristic. Thus queue length is very important characteristic to determine that how well the active queue management of the congestion control algorithm has been working. and most widely used. It is determined as the ratio of the total data received to the end to end delay. The throughput is usually measured inbitsper second (bit/s orbps). Throughput is an important factor which directly impacts the network performance Delay Delay is the time elapsed while a packet travels from one point e. leaving thesystem after being served.. source premise or network ingress to destination premise or network degrees. andsometimes indata packetsper second or data packets pertime slotThis measure how soon the receiver is able to get a certain amount of data send by the sender. We will calculate end to end delay Queue Length A queuing system in networks can be described as packets arriving for service. throughputor network throughputis the average rate of successfulmessage delivery over a communication channel. Incommunicationnetworks. waiting for service if it is not immediate. such asEthernetorpacket radio.

Perform a case study about the different routing algorithms to select the .11.

Link State routing Aim: To study the link state routing Link State routing Routing is the process of selecting best paths in a network. . This article is concerned primarily with routing in electronic data networks using packet switching technology. routing directs packet forwarding (the transit of logically addressed network packets from their source toward their ultimate destination) through intermediate nodes. constructing routing tables. In the past. However this latter function is much better described as simply forwarding. though they are not specialized hardware and may suffer from limited performance. Thus. firewalls. and transportation networks. including the telephone network (circuit switching). electronic data networks (such as the Internet). The routing process usually directs forwarding on the basis of routing tables which maintain a record of the routes to various network destinations. gateways. Intermediate nodes are typically network hardware devices such as routers. In packet switching networks. Multipath routing techniques enable the use of multiple alternative paths.network path with its optimum and economical during data transfer. bridges. or switches. Most routing algorithms use only one network path at a time. i. the term routing was also used to mean forwarding network traffic among networks. is very important for efficient routing. which are held in the router's memory. General-purpose computers can also forward packets and perform routing. Routing is performed for many kinds of networks.

structured addressing (routing. Administrative distance: where a lower distance is preferred (only valid between different routing protocols) Routing.In case of overlapping/equal routes. Prefix-Length: where longer subnet masks are preferred (independent of whether it is within a routing protocol or over different routing protocol) 2. in a more narrow sense of the term. Structured addresses allow a single routing table entry to represent the route to a group of devices. Routing has become the dominant form of addressing on the Internet. the following elements are considered in order to decide which routes get installed into the routing table (sorted by priority): 1. Metric: where a lower metric/cost is preferred (only valid within one and the same routing protocol) 3. In large networks. Bridging is still widely used within localized environments. . in the narrow sense) outperforms unstructured addressing (bridging). is often contrasted with bridging in its assumption that network addresses are structured and that similar addresses imply proximity within the network.

Controlled Flooding has its own two algorithms to make it reliable. If it is received from the next node. DVMRP. 2.Uncontrolled Flooding is the fatal law of flooding. In SNCF. the node attaches its own address and sequence number to the packet. since every node has a memory of addresses and sequence numbers. and those used in ad-hoc wireless networks. .There are generally two types of flooding available. Uncontrolled Flooding and Controlled Flooding. Each node tries to forward every message to every one of its neighbours except the source node. Each node acts as both a transmitter and a receiver. it drops it immediately while in RPF. If it receives a packet in memory. Flooding Flooding s a simple routing algorithm in which every incoming packet is sent through every outgoing link except the one it arrived on. the node will only send the packet forward. SNCF (Sequence Number Controlled Flooding) and RPF (Reverse Path Flooding). it sends it back to the sender. More than two neighbours creates a broadcast storm. All nodes have neighbours and route packets indefinitely. including OSPF.Flooding is used in bridging and in systems such as Usenet and peer-to-peer file sharing and as part of some routing protocols.ii. This results in every message eventually being delivered to all reachable parts of the network. Algorithm There are several variants of flooding algorithm. Most work roughly as follows: 1.

in some case. and to allow messages to eventually expire from the system. A variant of flooding called selective flooding partially addresses these issues by only sending packets to routers in the same direction. it will also use the  This algorithm is very simple to implement.  Advantages  f a packet can be delivered.Algorithms may need to be more complex than this. aturally utilizes every path through the network. it will (probably multiple times). since.   shortest path.  . In selective flooding the routers don't send every incoming packet on every line but only on those lines which are going approximately in the right direction. precautions have to be taken to avoid wasted duplicate deliveries and infinite loops.

distance-vector routing protocols have less computational complexity and message overhead. Distance vector In computer communication theory relating to packet-switched networks.Disadvantages  Flooding can be costly in terms of wasted bandwidth. This value should take into account  number of nodes that a packet may have to pass through on the way to its destination. which require a router to inform all the nodes in a network of topology changes. or DUAL FSM (in the case of Cisco Systems's protocols) to calculate paths.   Messages can become duplicated in the network further increasing the load on the networks bandwidth as well s  requiring an increase in  processing complexity to disregard duplicate messages. it can be harmful to the reliability of a computer network. Distance-vector routing protocols use the Bellman-Ford algorithm. unless certain precautions are taken:   Use a hop count or a time to live count and include it with each packet. Compared to link-state protocols. a distancevector routing protocol is one of the two major classes of routing protocols. A distance-vector routing protocol requires that a router informs its neighbors of topology changes periodically. While a message may only have one destination it has to be sent to every host. In the case of a ping floor a denial of service attack. the other major class being the link-state protocol.     Duplicate packets may circulate forever. Ford-Fulkerson algorithm.   Have each node keep track of every packet seen and only forward each packet once  Enforce a network topology without loops  iii . .

Method Routers using distance-vector protocol do not have knowledge of the entire path to a destination. Direction in which router or exit interface a packet should be forwarded. "Distance" is a . 2. The vector distance algorithm was the original ARPANET routing algorithm and was also used in the internet under the name of RIP (Routing Information Protocol). "Direction" usually means the next hop address and the exit interface. Distance from its destination Distance-vector protocols are based on calculating the direction and distance to any link in a network. Instead they use two methods: 1. Examples of distance-vector routing protocols include RIPv1 and RIPv2 and IGRP.The term distance vector refers to the fact that the protocol manipulates vectors (arrays) of distances to other nodes in the network.

EGP and BGP are not pure distance-vector routing protocols because a distance-vector protocol calculates routes based only on link costs whereas in BGP. The core of the count-to-infinity problem is that if A tells B that it has a path somewhere. This process has been described as ‗routing by rumor‘ because routers are relying on the information they receive from other routers and cannot determine if the information is actually valid and true. Now suppose that A is taken offline. . The least cost route between any two nodes is the route with minimum distance. imagine a subnet connected like A-B-C-D-E-F. To see the problem clearly. there is no way for B to know if the path has B as a part of it. The cost of reaching a destination is calculated using various route metrics. There are a number of features which can be used to help with instability and inaccurate routing information. Once a router has this information it is able to amend its own routing table to reflect the changes and then inform its neighbors of the changes. and let the metric between the routers be "number of jumps". the local route preference value takes priority over the link cost. Count-to-infinity problem The Bellman-Ford algorithm does not prevent routing loops from happening and suffers from the countto-infinity problem. In the vector-updateprocess B notices that the route to A. Each node maintains a vector (table) of minimum distance to every node.measure of the cost to reach a certain node. for example. RIP supports cross-platform distance vector routing whereas IGRP is a Cisco Systems proprietary distance vector routing protocol. Updates are performed periodically in a distance-vector protocol where all or part of a router's routing table is sent to all its neighbors that are configured to use the same distance-vector routing protocol. RIP uses the hop count of the destination whereas IGRP takes into account other information such as node delay and available bandwidth.

and C is still not aware of the fact that A is down so it tells B that A is only two jumps from C (C to B to A). which is false. The problem is. due to the relaxation property of Bellman-Ford). is down .no. This slowly propagates through the network until it reaches infinity (in which case the algorithm corrects itself. .B does not receive the vector update from A. Ex.11 UNICAST ROUTING PROTOCOL Aim: To write a ns2 program for implementing unicast routing protocol.which was distance 1. B also gets an update from C.

Step 15: define the finish procedure.file1. Step 6: set the unicast routing protocol to transfer the packets in network. Step 3: set the color for packets. Step 11: set the destination node using tcp sink. Step 13: down the connection between any nodes at a particular time. Step 10: set a tcp reno connection for source node.Algorithm: Step 1: start the program. Step 2: declare the global variables ns for creating a new simulator. Step 14: reconnect the downed connection at a particular time. Step 4: open the network animator file in the name of file2 in the write mode. Step 5: open the trace file in the name of file 1 in the write mode. Step 17: close the trace file and namefile and execute the network animation file. Step 12: setup a ftp connection over the tcp connection. Step 16: in the definition of the finish procedure declare the global variables ns. Step 18: at the particular time call the finish procedure.file2. Step 7: create the required no of nodes. Step 9: give the position for the links between the nodes. Step 8: create the duplex-link between the nodes including the delay time.bandwidth and dropping queue mechanism. . Step 19: stop the program.

Program:
set ns [new Simulator]
#Define
different
colors for data
flows
(for
NAM)
$ns
color 1 Blue
$ns color 2 Red
#Open the Trace file
s
e
t
f
i
l
e
1
[
o
p
e
n
o
u
t
.
t
r

w
]
$
n
s
t
r
a
c
e
a
l
l
$
f
i
l
e
1

#
O
p
e
n
t
h
e
N
A
M
t
r
a
c
e
f
i
l
e
s
e
t
f
i
l
e
2
[
o
p
e
n

o
u
t
.
n
a
m
w
]
$
n
s
n
a
m
t
r
a
c
e
a
l
l
$
f
i
l
e
2
#
D
e
f
i
n
e
a
'

f
i
n
i
s
h
'
p
r
o
c
e
d
u
r
e
p
r
o
c
f
i
n
i
s
h
{
}
{
g
l
o
b
a
l
n
s
f
i

l
e
1
f
i
l
e
2
$
n
s
f
l
u
s
h
t
r
a
c
e
c
l
o
s
e
$
f
i
l
e
1
c
l
o
s

n a m & e x i t 3 } # Next line should be commented out to have the static routing $ns rtproto DV #Create six nodes set n0 [$ns node] set n1 [$ns node] set n2 [$ns node] set n4 [$ns node] set n4 [$ns node] set n5 [$ns node] .e $ f i l e 2 e x e c n a m o u t .

3Mb 10ms DropTail $ns duplex-link $n1 $n4 0.3Mb 10ms DropTail $ns duplex-link $n3 $n5 0.3Mb 10ms DropTail $ns duplex-link $n1 $n2 0.3Mb 10ms DropTail $ns duplex-link $n2 $n3 0.5Mb 10ms DropTail $ns duplex-link $n4 $n5 0.#Create links between the nodes $ns duplex-link $n0 $n1 0.5Mb 10ms DropTail #Give node position (for NAM) $ns duplex-link-op $n0 $n1 orient right $ns duplex-link-op $n1 $n2 orient right $ns duplex-link-op $n2 $n3 orient up $ns duplex-link-op $n1 $n4 orient up-left $ns duplex-link-op $n3 $n5 orient left-up $ns duplex-link-op $n4 $n5 orient right-up #Setup a TCP connection s e t t c p [ n e w A g e n t / T C P / N e w r .

e n o ] $ n s a t t a c h a g e n t $ n 0 $ t c p set sin k [ne w Ag ent /T CP Sin k/ Del Ac k] $ns atta ch- .

age nt $n 5 $si nk $ n s c o n n e c t $ t c p $ s i n k $ t c p s e t f i d _ 1 .

# S e t u p a F T P o v e r T C P c o n n e c t i o n s e t f t p [ .

n e w A p p l i c a t i o n / F T P ] $ f t p a t t a c h a g e n t $ t c p $ftp set type_ FTP .

0 d o w n $ n 1 $ n 4 $ n s r t m o d e l a t .$ n s r t m o d e l a t 1 .

0 " f i n i .4 .1 "$ftp start" $ n s a t 6 . 5 u p $ n 1 $ n 4 $ns at 0.

s h " $ n s r u n .

no. Algorithm: Step 1: start the program.11(b) MULTICASTING ROUTING PROTOCOL Aim: To write a ns2 program for implementing multicasting routing protocol.Ex. .

. Step 4: open the network animator file in the name of file2 in the write mode. Step 5: open the trace file in the name of file 1 in the write mode. Step 3: set the color for packets. Step 6: set the multicast routing protocol to transfer the packets in network.Step 2: declare the global variables ns for creating a new simulator. Step 9: give the position for the links between the nodes.bandwidth and dropping queue mechanism. Step 8: create the duplex-link between the nodes including the delay time. Step 7: create the multicast capable no of nodes.

Step 14: create the receive agent for joining and leaving if the nodes in the group. Step 16: in the definition of the finish procedure declare the global variables. Program: # Create scheduler #Create an event scheduler wit multicast turned on set ns [new Simulator -multicast on] #$ns multicast #Turn on Tracing . Step 11: set the destination node . Step 13: down the connection between any nodes at a particular time. Step 18: at the particular time call the finish procedure.Step 10: set a udp connection for source node. Step 15: define the finish procedure.port and random false for the source and destination files. Step 17: close the trace file and namefile and execute the network animation file. Step 19: stop the program. Step 12: setup a traffic generator CBR for the source and destination files.

s e t t f [ o p e n o u t p u t . t r w ] $ n s t r a c e a l l $ t f # Turn on nam Tracing s e t .

f d [ o p e n m c a s t . n a m w ] $ n s n a m t r a c e a l l $ f d # Create nodes set n0 [$ns node] set n1 [$ns node] .

5Mb 10ms DropTail .set n2 [$ns node] set n3 [$ns node] set n4 [$ns node] set n5 [$ns node] set n6 [$ns node] set n7 [$ns node] # Create links $ns duplex-link $n0 $n2 1.

5Mb 10ms DropTail # Ro uti ng pro toc ol: say dist anc e vec tor #Pr oto col s: Ctr Mc ast.5Mb 10ms DropTail $ns duplex-link $n3 $n7 1.$ns duplex-link $n1 $n2 1.5Mb 10ms DropTail $ns duplex-link $n4 $n6 1. BS T set mp rot o D M set mrthandle [$ns mrtproto $mproto {}] # Allocate group addresses .5Mb 10ms DropTail $ns duplex-link $n4 $n5 1.5Mb 10ms DropTail $ns duplex-link $n3 $n4 1. ST.5Mb 10ms DropTail $ns duplex-link $n2 $n3 1. D M.

s e t g r o u p 1 [ N o d e a l l o c a d d r ] s e t g r o u p 2 [ N o d e .

a l l o c a d d r ] # UDP Transpo rt agent for the traffic source set udp0 [new Agent/U DP] $ n s a t t a c h a g e n t $ n 0 $ u d p .

0 $ u d p 0 s e t d s t _ a d d r _ $ g r o u p 1 $ u d p 0 s e t d s t _ .

p o r t _ 0 set cbr1 [ne w App licat ion/ Traf fic/ CB R] $cbr 1 atta chage nt $ud p0 # Tr an sp ort ag ent for the tra ffi c so urc e set ud p1 [ne w .

Ag ent /U DP ] $ n s a t t a c h a g e n t $ n 1 $ u d p 1 $ u d p 1 s e t d s t .

_ a d d r _ $ g r o u p 2 $ u d p 1 s e t d s t _ p o r t _ 0 set cbr2 [ne w App licat ion/ Traf fic/ CB .

R] $cbr 2 atta chage nt $ud p1 # Create receiver s e t r c v r 1 [ n e w A g e n t / N u l l ] $ n s a t t .

a c h a g e n t $ n 5 $ r c v r 1 $ns at 1.5 "$n6 joingroup $rcvr2 $group 1" set rcvr3 [new .0 "$n5 joingroup $rcvr1 $group 1" set rcvr2 [new Agent/ Null] $ns attach-agent $n6 $rcvr2 $ns at 1.

5 "$n5 joingroup $rcvr4 $group 2" set rcvr5 [new Agent/ Null] $ns attach-agent $n6 $rcvr2 $ns at 3.Agent/ Null] $ns attach-agent $n7 $rcvr3 $ns at 2.0 "$n7 joingroup $rcvr3 $group 1" set rcvr4 [new Agent/ Null] $ns attach-agent $n5 $rcvr1 $ns at 2.0 "$n6 joingroup $rcvr5 $group 2" set rcvr6 [new Agent/ Null] $ns attach-agent $n7 $rcvr3 .

5 "$n7 join-group $rcvr6 $group2" $ns at 4.0 "$n7 leave-group $rcvr3 $group1" $ns at 5.5 "$n5 leave-group $rcvr4 $group2" $ns at 6.0 "$n6 leave-group $rcvr5 $group2" $ns at 6.$ns at 3.5 "$n6 leave-group $rcvr2 $group1" $ns at 5.5 "$n7 leave-group $rcvr6 $group2" # Schedule events $ n s a t 0 . 5 " $ c b r 1 s t a r t " $ n s a t 9 .0 "$n5 leave-group $rcvr1 $group1" $ns at 4.

5 " $ c b r 1 s t o p " $ n s a t 0 .. 5 " $ c b r 2 s t a r t " $ n s .

5 " $ c b r 2 s t o p " #post-processing $ n s a t 1 0 . 0 " f i n i s h " p r o .a t 9 .

c f i n i s h { } { global ns tf $ n s f l u s h t r a c e c l o s e $ t f e x e c .

n a m m c a s t . n a m & e x i t 0 } # For nam #Color s for packets from two mcast groups $ns color 10 red $ n s c o l o r .

1 1 g r e e n $ n s c o l o r 3 0 p u r p l e $ n s c o l o r 3 1 g r .

e e n # Manual layout: order of the link is significant! #$ns duplex-link-op $n0 $n1 orient right #$ns duplex-link-op $n0 $n2 orient right-up #$ns duplex-link-op $n0 $n3 orient right-down # Show queue on simplex link n0->n1 #$ns duplex-link-op $n2 $n3 queuePos 0.5 # Group 0 source $ u d p 0 s e t f i d _ 1 0 $ n 0 c o l o r r e d $n0 label "Source 1" # .

G r o u p 1 s o u r c e $ u d p 1 s e t f i d _ 1 1 $ n 1 c o l o r g r .

e e n $ n 1 l a b e l " S o u r c e 2 " $ n 5 l a b e l " R e c e i v e r .

1 " .

$n5 color blue $ n 6 l a b e l " R e c e i v e r 2 " $ n 6 c o l o r b l u e $ n 7 l a .

b e l " R e c e i v e r 3 " $ n 7 c o l o r b l u e # $ n 2 a d d m a r k m .

0 r e d # $ n 2 d e l e t e m a r k m 0 " # Animation rate $ n s s e t a n i m a t i o n r .

a t e 3 . 0 m s $ n s r u n .

.

11(c) CARRIER SENSE MULTIPLE ACCESS Aim: To write a ns2 program for implementing carrier sense multiple access.no. Step 4: open the network animator file in the write mode. Step 3: set the color for packets. . Step 7: create the capable no of nodes. Step 2: declare the global variables ns for creating a new simulator.Ex. Step 6: transfer the packets in network. Step 5: open the trace file and the win file in the write mode. Algorithm: Step 1: start the program.

Step 19: stop the program.Step 8: create the duplex-link between the nodes including the delay time.bandwidth and dropping queue mechanism. Step 10: set a tcp connection for source node. Step 12: set the window size and the packet size for the tcp. Step 14:. Step 16: in the definition of the finish procedure declare the global variables. Step 11: set the destination node using tcp sink. Step 13: set up the ftp over the tcp connection. . Step 15: create the traffic generator CBR for the source and destination files. Step 15: define the plot window and finish procedure. Step 18: at the particular time call the finish procedure.set the udp and tcp connection for the source and destination. Step 9: give the position for the links between the nodes. Step 17: close the trace file and namefile and execute the network animation file.

Program: s e t n s [ n e w S i m u l a t o r ] $ n s c o l o r 1 b l u e .

$ns color 2 red set fi1 [open out.tr w] s e t w i n f i l e [ o p e n W i n F i l e w ] $ n s t r a c e a l l $ .

n a m w ] $ n s n a m t r a c e a l l $ .f i 1 s e t f i 2 [ o p e n o u t .

f i 2 p r o c f i n i s h { } { g l o b a l n s f i 1 f i 2 $ n s f l u .

n a m & e x i t 0 } .s h t r a c e c l o s e $ f i 1 close $fi2 e x e c n a m o u t .

3Mb 100ms DropTail $ns simplexlink $n3 $n2 0.5Mb 40ms LL Queue/DropTail MAC/Csma/Cd Channel] set tcp [new Agent/TCP/Newreno] $ns attach-agent $n0 $tcp set sin k [ne w Ag ent /T CP Sin k/ Del Ac k] $ns atta chage nt $n 4 .3Mb 100ms DropTail set lan [$ns newLan "$n3 $n4 $n5" 0.set n0 [$ns node] set n1 [$ns node] set n2 [$ns node] set n3 [$ns node] set n4 [$ns node] set n5 [$ns node] $n1 color red $n1 shape box $ns duplex-link $n0 $n2 2Mb 10ms DropTail $ns duplex-link $n1 $n2 2Mb 10ms DropTail $ns simplexlink $n2 $n3 0.

$si nk $ n s c o n n e c t $ t c p $ s i n k $ t c p s e t f i d _ 1 $tcp set window_ 8000 $tcp set packetsize_ 552 s e t f t .

p [ n e w A p p l i c a t i o n / F T P ] $ f t p a t t a c h a g e n t $ t c p .

$ftp set type_ FTP set udp [new Agent/UDP] $ns attach-agent $n1 $udp set null [new Agent/Null] $ns attach-agent $n5 $null $ns connect $udp $null $udp set fid_ 2 set cbr [new Application/Traffic/CBR] .

$ c b r a t t a c h a g e n t $ u d p $ c b r s e t t y p e _ C B R .

$cbr set packet_size_ 1000 $cbr set rate_ 0.01mb $cbr set random_ false $ns at 0.0 "$ftp start" $ns at 24.0 "$ftp stop" $ns at 24.1 "$cbr start" $ns at 1.5 "$cbr stop" p r o c p l o t w i n d o w { t c p S o u r c e fi l e } { g l o b a l n s .

set time 0.1 set now [$ns now] s e t c w n d [ $ t c p S o u r c e s e t c w n d _ ] s e t w n d [ $ t c .

p S o u r c e s e t w i n d o w _ ] p u t s $ f i l e " $ n o w $ c w n d " $ns at [expr $now+ $time] "plotwindow .

0 "finish" $ns run Output: .$tcpSource $file" } $ns at 1.0 "plotwindow $tcp $winfile" $ns at 5 "$ns traceannotate \"packet drop\"" $ns at 125.