Sie sind auf Seite 1von 56

Om Sakthi

ADHIPARASAKTHI COLLEGE OF ENGINEERING


G.B.Nagar, Kalavai-632506, Vellore District.

DEPARTMENT OF ELECTRONICS &COMMUNCATION ENGINEERING

EC6611 – COMPUTER NETWORKS LABORATORY

NAME:

REG.NO:

YEAR: SEM:
Om Sakthi
ADHIPARASAKTHI COLLEGE OF ENGINEERING
G.B. Nagar, Kalavai – 632 506, Vellore District, Tamil Nadu.

DEPARTMENT OF ELECTRONICS &COMMUNCATION ENGINEERING

CERTIFICATE

Certified that is the bonafide record of work done by

Mr/Ms____________________ with Enrollment Number____________________

Third year/ Vth Semester B.E ELECTRONICS AND COMMUNICATION ENGINEERING in

Anna University during the year 2017 in respect of practical

EC6611 – COMPUTER NETWORKS LABORATORY

Submitted for the Practical Examination held on ________________________

SIGNATURE OF FACULTY-IN-CHARGE SIGNATURE OF HEAD OF THE

DEPARTMENT

Internal Examiner External Examiner


CONTENTS

EX.NO DATE TITLE SIGNATURE


EXP NO: 1 ERROR CORRECTION AND DETECTION TECHNIQUES
DATE:

Aim:
To create a java program for implementing error correction and detection techniques using
Hamming codes.
Algorithm:
Step 1: Start the program.
Step 2: Get the message bits from the user.
Step 3: Calculate the number of parity bits to be added with the message.
Step 4: Generate the parity bits.
Step 5: Generate the Hamming code by adding the parity bits along with message in respective
location.
Step 6: Make a one bit error in transmitting Hamming code.
Step 7: Check the correctness of Hamming code and find the location of error if present in
received hamming code.
Step 8: Stop the program.

Program:

/* IMPLEMENTATION OF ERROR CORRECTION AND DETECTION TECHNIQUES*/


import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.*;
class HammingCode
{
public static void main(String args[])
{
Scanner scr=new Scanner(System.in);
System.out.println("This is Hamming code error detection & correction using even parit");
System.out.println();
System.out.println("Enter 4 data bits D4 D3 D2 D1");
int n=4;
int d[]=new int[4];
for(int i=n-1;i>=0;--i)
{
System.out.println("enter the value of D"+(i+1));
d[i]=scr.nextInt();
}
int k=0;
while(Math.pow(2,k)<(n+k+1))
{
++k;
}
System.out.println();
System.out.println(k+"parity bits are required for the transmission of data bits");
int p[]=new int[k];
int h[]=new int[n+k+1];
for(int i=0;i<7;++i)
h[i]=-1;
int count=0;
int c=2;
while(count<4)
{
++c;
if(c==4)
continue;
h[c]=d[count];
++count;
}
int p1[]={h[1],h[3],h[5],h[7]};
int p2[]={h[2],h[3],h[6],h[7]};
int p3[]={h[4],h[5],h[6],h[7]};
int parity[]=new int[3];
parity[0]=set_parity_bit(p1);
parity[1]=set_parity_bit(p2);
parity[2]=set_parity_bit(p3);
h[1]=parity[0];
h[2]=parity[1];
h[4]=parity[2];
System.out.println("\nsender:");
System.out.print("\nThe data bits entered are:");
for(int i=3;i>=0;--i)
System.out.print(d[i]+"");
System.out.println("The parity bits are:");
for(int i=2;i>=0;--i)
System.out.println("value of p"+(i+1)+"is"+parity[i]+" ");
System.out.print("\nThe Hamming code is as follows:\nD4 D3 D2 P3 D1 P2 P1\n");
for(int i=(n+k);i>0;--i)
System.out.print(h[i]+" ");
System.out.println();
System.out.println();
System.out.println("Enter the hamming code with error at any position of your choice");
for(int i=7;i>0;--i)
h[i]=scr.nextInt();
int p4[]={h[1],h[3],h[5],h[7]};
int p5[]={h[2],h[3],h[6],h[7]};
int p6[]={h[4],h[5],h[6],h[7]};
parity[0]=set_parity_bit(p4);
parity[1]=set_parity_bit(p5);
parity[2]=set_parity_bit(p6);
int position=(int)(parity[2]*Math.pow(2,2)+parity[1]*Math.pow(2,1)+parity[0]*Math.pow(2,0));
System.out.println("Receiver");
System.out.println("Error is detected at position"+position+"at the receiver end");
System.out.println("Correcting the error");
if(h[position]==1)
h[position]=0;
else
h[position]=1;
System.out.print("The correct code is");
for(int i=7;i>0;--i)
System.out.print(h[i]+" ");
}
static int set_parity_bit(int a[])
{
int count=0;
int l=a.length;
for(int i=0;i<l;++i)
if(a[i]==1)
++count;
if((count%2)==0)
return 0;
else
return 1;
}
}

OUTPUT:
E:\ece>java HammingCode
This is hamming code error detection and correction using EVEN parity

Enter 4 data bits.D4 D3 D2 D1


Enter the value of D4
1
Enter the value of D3
0
Enter the value of D2
0
Enter the value of D1
0

3 parity bits are required for the transmission of data bits.

SENDER:

The data bits entered are: 1 0 0 0


The Parity bits are:
Value of P3 is 1
Value of P2 is 1
Value of P1 is 1

The Hamming code is as follows :-


D4 D3 D2 P3 D1 P2 P1
1001011

Enter the hamming code with error at any position of your choice.
1
0
0
0
0
1
1

RECEIVER:
Error is detected at position 4 at the receiving end.
Correcting the error....
The correct code is 1 0 0 1 0 1 1

Result:

Thus the implementation of error correction/detection techniques using Hamming codes is


successfully executed.
EXP NO: 2 Implementation of Stop and Wait Protocol and Sliding
DATE: Window Protocol

AIM:

To write a java program to perform sliding window.

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 :
import java.net.*;
import java.io.*;
import java.rmi.*;
public class slidsender
{
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
{
p=new PrintStream(s.getOutputStream());
System.out.print("Enter the no. of frames : ");
nf=Integer.parseInt(in.readLine());
p.println(nf);
if(nf<=sws-1)
{
System.out.println("Enter "+nf+" Messages to be send\n");
for(i=1;i<=nf;i++)
{
sbuff[sptr]=in.readLine();

p.println(sbuff[sptr]);
sptr=++sptr%8;
}
sws-=nf;
System.out.print("Acknowledgment received");
ano=Integer.parseInt(in1.readLine());
System.out.println(" for "+ano+" frames");
sws+=nf;
}
else
{
System.out.println("The no. of frames exceeds window size");
break;
}
System.out.print("\nDo you wants to send some more frames : ");
ch=in.readLine();
p.println(ch);
}
while(ch.equals("yes"));
s.close();
}
}

RECEIVER PROGRAM

import java.net.*; import java.io.*; class slidreceiver


{
public static void main(String a[])throws Exception
{
Socket s=new Socket(InetAddress.getLocalHost(),10);
DataInputStream in=new DataInputStream(s.getInputStream());
PrintStream p=new PrintStream(s.getOutputStream());
int i=0,rptr=-1,nf,rws=8;
String rbuf[]=new String[8];
String ch;
System.out.println();
do
{
nf=Integer.parseInt(in.readLine());
if(nf<=rws-1)
{
for(i=1;i<=nf;i++)
{

rptr=++rptr%8;
rbuf[rptr]=in.readLine();
System.out.println("The received Frame " +rptr+" is : "+rbuf[rptr]);
}
rws-=nf;
System.out.println("\nAcknowledgment sent\n");
p.println(rptr+1);
rws+=nf;
}
else
break;
ch=in.readLine();
}
while(ch.equals("yes"));
}
}

OUTPUT:

//SENDER OUTPUT
Enter the no. of frames : 4
Enter 4 Messages to be send
hiii how r u
i am fine
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

Result:
Thus the implementation of stop and wait protocol is successfully executed.
EX.NO:3
DATE: IMPLEMENTATION OF GO BACK N PROTOCOL

AIM:
To implement the concept for Go Back N protocol using java programming.

ALGORITHM:
STEP 1: Start the program.
STEP 2: Get the number of frames to be sent from the user.
STEP 3: Send a group of 4 frames before waiting for acknowledgment.
STEP 4: Receiver receives the frame as soon as it receives it send the acknowledgement
for that particular frame.
STEP 5: If receiver receives frame in out of order then it discards the frame and sends
the NACK for the expected frame.
STEP 6: Transmitter transmit all the frames starting from lost frame in sequential order.
STEP 7: Stop the program.

CLIENT PROGRAM:
import java.util.*;
import java.net.*;
import java.io.*;
public class gobackclient
{
public static void main(String args[])throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the value of m :");
int m=Integer.parseInt(br.readLine());
int x=(int)((Math.pow(2,m))-1);
System.out.println("Enter the no of frames to be sent: ");
int count=Integer.parseInt(br.readLine());
int data[]=new int[count];
int h=0;
for(int i=0;i<count;i++)
{
System.out.print("Enter data for no "+h+" =>");
data[i]=Integer.parseInt(br.readLine());
h=(h+1)%x;
}
Socket client=new Socket("localhost",6262);
ObjectInputStream ois=new ObjectInputStream(client.getInputStream());
ObjectOutputStream oos=new ObjectOutputStream(client.getOutputStream());
System.out.println("Connected with server");
boolean flag=false;
GoBackNListener listener=new GoBackNListener(ois,x);
listener=new GoBackNListener(ois,x);
listener.t.start();
int strt=0;
h=0;
oos.writeObject(x);
do
{
int c=h;
for(int i=h;i<count;i++)
{
System.out.print("| "+c+" |");
c=(c+1)%x;
}
System.out.println();
System.out.println();
h=strt;
for(int i=strt;i<x;i++)
{
System.out.println("Sending frame : "+h);
h=(h+1)%x;
System.out.println();
oos.writeObject(i);
oos.writeObject(data[i]);
Thread.sleep(100);
}
listener.t.join(3500);
if(listener.reply!=x-1)
{
System.out.println("No reply from server in 3.5 seconds. Resending data from frame no "+
(listener.reply+1));
System.out.println();
strt=listener.reply+1;
flag=false;
}
else
{
System.out.println("All elements sent successfully. Exiting");
flag=true;
}
}while(flag);
oos.writeObject(-1);
}
}
class GoBackNListener implements Runnable
{
Thread t;
ObjectInputStream ois;
int reply,x;
GoBackNListener(ObjectInputStream o,int i)
{
t=new Thread(this);
ois=o;
reply=-2;
x=i;
}
@Override
public void run()
{
try
{
int temp=0;
while(reply!=-1)
{
reply=(Integer)ois.readObject();
if(reply!=-1&&reply!=temp+1)
reply=temp;
if(reply!=-1)
{
temp=reply;
System.out.println("acknowledgement of frame no "+(reply%x)+" received");
System.out.println();
}
}
reply=temp;
}
catch(Exception e)
{
System.out.println("Exception => "+e);
}}}
SERVER PROGRAM:
import java.util.*;
import java.io.*;
import java.net.*;
public class gobacknserver
{
public static void main(String args[])throws Exception
{
ServerSocket server=new ServerSocket(6262);
System.out.println("Server established");
Socket client=server.accept();
ObjectOutputStream oos=new ObjectOutputStream(client.getOutputStream());
ObjectInputStream ois=new ObjectInputStream(client.getInputStream());
System.out.println("Client is now connected");
int x=(Integer)ois.readObject();
int k=(Integer)ois.readObject();
int j=0;
int i=(Integer)ois.readObject();
boolean flag=true;
Random r=new Random(6);
int mod=r.nextInt(6);
while(mod==1||mod==0)
mod=r.nextInt(6);
while(true)
{
int c=k;
for(int h=0;h<=x;h++)
{
System.out.print(" | "+c+" | ");
c=(c+1)%x;
}
System.out.println();
System.out.println();
if(k==j)
{
System.out.println("Frames received not in correct order "+" \n"+" Expected frame: "+j+"
\n"+"Received frame no: "+k);
j++;
System.out.println();
}
if(j%mod==0&&flag)
{
System.out.println("Error found. Acknowledgement not sent");
flag=!flag;
j--;
}
else if(k==j-1)
{
oos.writeObject(k);
System.out.println("Acknowledgement sent");
}
System.out.println();
if(j%mod==0)
flag=!flag;
k=(Integer)ois.readObject();
if(k==-1)
break;
i=(Integer)ois.readObject();
}
System.out.println("Client finished sending data.Exiting");
oos.writeObject(-1);
}
}
OUTPUT:
CLIENT SIDE:
D:\3 ece>java gobackclient
Enter the value of m :
2
Enter the no of frames to be sent:
4
Enter data for no 0 =>1
Enter data for no 1 =>2
Enter data for no 2 =>3
Enter data for no 0 =>4
Connected with server
| 0 || 1 || 2 || 0 |

Sending frame : 0

acknowledgement of frame no 0 received

Sending frame : 1

Sending frame : 2

No reply from server in 3.5 seconds. Resending data from frame no 1

SERVER SIDE:
D:\3 ece>java gobacknserver
Server established
Client is now connected
|0| |1| |2| |0|

Frames received not in correct order


Expected frame: 0
Received frame no: 0

Acknowledgement sent

|1| |2| |0| |1|

Frames received not in correct order


Expected frame: 1
Received frame no: 1

Error found. Acknowledgement not sent

|2| |0| |1| |2|


Client finished sending data.Exiting….

RESULT:
Thus the concept of Go Back N protocol using java programming was implemented and
output was verified.
EX:NO:4
DATE: IMPLEMENTATION OF HIGH LEVEL DATA LINK CONTROL PROTOCOL

AIM:
To write a java program to implement the concept of high level data link control(bit
stuffing).
ALGORITHM:
STEP 1:Start the program.
STEP 2:Get the binary message from the user.
STEP3:If the entered message is not in binary form display that ” Enter only binary
values”.
STEP 4:Perform bit stuffing insert zero after 5 consecutive ones Inorder to avoid data
considered as a flag sequence.
STEP 5: Insert the flag(01111110) before and after data to Indicates start and end of
frame.
STEP 6:Transmit to the receiver
STEP 7:Receiver extract data from the frame by removing flags.
STEP 8:Perform bit unstuffing (remove zero after 5 consecutive 1’s) and get the original
data

Program:
import java.util.*;
public class SEFBS
{
public static void main(String[] args)
{
System.out.print("Enter the binary message");
Scanner sn=new Scanner(System.in);
String data=sn.nextLine();
String res=new String();
String out=new String();
int counter=0;
for(int i=0;i<data.length();i++)
{
if(data.charAt(i)!='1' && data.charAt(i)!='0')
{
System.out.println("Enter only binary values!!!");
return;
}
if(data.charAt(i)!='1')
{
counter++;
res=res+data.charAt(i);
}
else
{
res=res+data.charAt(i);
counter=0;
}
if(counter==5)
{
res=res+'0';
counter=0;
}
}
String Inc="01111110"+res+"01111110";
System.out.println("The message to be transfered: "+Inc);
System.out.println("Sending the Message.....");
counter=0;
for(int i=0;i<res.length();i++)
{
if(res.charAt(i)=='1')
{
counter++;
out=out+res.charAt(i);
}
else
{
out=out+res.charAt(i);
counter=0;
}
if(counter==5)
{
if((i+2)!=res.length())
out=out+res.charAt(i+2);
else
out=out+' ';
i=i+2;
counter=1;
}
}
System.out.println("Message Received........Successfully!!!");
System.out.println(" The Destuffed Message is: "+out);
}
}
OUTPUT:
D:\3 ece>java SEFBS
Enter the binary message
01110001
The message to be transfered: 011111100111000101111110
Sending the Message.....
Message Received........Successfully!!!
The Destuffed Message is: 01110001
RESULT:
Thus the java program to implement the concept of high level data link control(bit
stuffing) was written and output was verified
EX:NO:5
DATE: IMPLEMENTATION OF SOCKET PROGRAMMING

AIM:
To write java program to implement socket programming.
ALGORITHM:
Step1: Start the program.
Step2: Create client and server socket.
Step3: Bind the address to client and server socket.
Step4: Send and receive message through socket system call.
Step5: Stop the program.

CLIENT PROGRAM:
import java.io.*;
import java.net.*;
public class myclient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}

SERVER PROGRAM:
import java.io.*;
import java.net.*;
public class MyServer{
public static void main(String[]args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();
DataInputStream din=new DataInputStream(s.getInputStream());
String str=(String)din.readUTF();
System.out.println("Message="+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}

OUTPUT:
E:\3 ece>java Myserver
Message=Hello Server

CLIENT PROGRAM:
import java.net.*;
import java.io.*;
class MyClient1
{
public static void main(String args[])throws Exception
{
Socket s=new Socket("localhost",3333);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop"))
{
str=br.readLine();
dout.writeUTF(str);
dout.flush();
str2=din.readUTF();
System.out.println("serversays:"+str2);
}
dout.close();
s.close();
}
}

SERVER PROGRAM:
import java.net.*;
import java.io.*;
class MyServer1
{
public static void main(String args[])throws Exception
{
ServerSocket ss=new ServerSocket(3333);
Socket s=ss.accept();
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop"))
{
str=din.readUTF();
System.out.println("Client says:"+str);
str2=br.readLine();
dout.writeUTF(str2);
dout.flush();
}
din.close();
s.close();
ss.close();
}
}
OUTPUT:
Client side:
E:\3 ece>java MyClient1
hi
serversays:hello

Server side:
E:\3 ece >java MyServer1
Client says:hi
hello

Result:
Thus the program to implement socket programming was written and executed successfully.
EX.NO:6 IMPLEMENTATION OF SOCKET PROGRAMMING
ECHO , PING ,AND TALK
DATE:

AIM:
To create a java program for implementing socket program of ECHO , PING and TALK.
ALGORITHM:
ECHO:
Step 1:Start the program.
Step 2:Create the client and server socket.
Step 3:Bind the server address in the client socket.
Step 4:Send message from client socket to server socket.
Step 5:Server socket reads the message from client socket display it and rewrite back to client
socket.
Step 6:Client socket display the echoed message from server socket.
Step 7:Stop the program.
PING:
Step 1:Start the program.
Step 2:Create a process to run the ping command.
Step 3:Get the IP address of remote system.
Step 4:Run the ping process by giving remote system IP address.
Step 5:Check the response from the remote system for its reachability.
Step 6:Stop the program.
TALK:
Step 1:Start the program.
Step 2:Create the client and server socket.
Step 3:Bind the server address in the client socket.
Step 4:Send message from client socket to server socket.
Step 5:Server socket reads the message from client socket , display it and give response message
back to client socket.
Step 6:Client socket in term reads message from server socket and write reply message back to
server socket.
Step 7:Repeat this above procedure until user enters exit message.
Step 8:Stop the program.
PROGRAM:

Echo client program:


import java.io.*;
import java.net.*;
import java.util.*;
public class echoclient
{
public static void main(String args[])throws Exception
{
Socket c=null;
DataInputStream usr_inp=null;
DataInputStream din=new DataInputStream(System.in);
DataOutputStream dout=null;
try
{
c=new Socket("127.0.0.1",5678);
usr_inp=new DataInputStream(c.getInputStream());
dout=new DataOutputStream(c.getOutputStream());
}
catch(IOException e)
{
}
if(c!=null || usr_inp!=null || dout!=null)
{
String unip;
while((unip=din.readLine())!=null)
{
dout.writeBytes(""+unip);
dout.writeBytes("\n");
System.out.println("\n the echoed message");
System.out.println(usr_inp.readLine());
System.out.println("\n enter your message");
}
System.exit(0);
}
din.close();
usr_inp.close();
c.close();
}
}

Echo server program:


import java.io.*;
import java.net.*;
public class echoserver
{
public static void main(String args[])throws Exception
{
ServerSocket m=null;
Socket c=null;
DataInputStream usr_inp=null;
DataInputStream din=new DataInputStream(System.in);
DataOutputStream dout=null;
try
{
m=new ServerSocket(5678);
c=m.accept();
usr_inp=new DataInputStream(c.getInputStream());
dout=new DataOutputStream(c.getOutputStream());
}
catch(IOException e)
{}
if(c!=null || usr_inp!=null)
{
String unip;
while(true)
{
System.out.println("\nMessage from Client...");
String m1=(usr_inp.readLine());
System.out.println(m1);
dout.writeBytes(""+m1);
dout.writeBytes("\n");
}
}
dout.close();
usr_inp.close();
c.close();
}
}
OUTPUT
Client:
C:\Program Files\Java\jdk1.6.0\bin>java echoclient
hello
The echoed message
hello
Enter your message
Server:
C:\Program Files\Java\jdk1.6.0\bin>java echoserver
Message from Client...
hello
PING Program:
import java.io.*;
import java.net.*;
class pingserver
{
public static void main(String args[])
{
try
{
String str;
System.out.print(" Enter the IP Address to be Ping : ");
BufferedReader buf1=new BufferedReader(new
InputStreamReader(System.in));
String ip=buf1.readLine();
Runtime H=Runtime.getRuntime();
Process p=H.exec("ping " + ip);
InputStream in=p.getInputStream();
BufferedReader buf2=new BufferedReader(new
InputStreamReader(in));
while((str=buf2.readLine())!=null)
{
System.out.println(" " + str);
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}

Output:
Enter the IP address to the ping:192.168.0.1
Pinging 192.168.0.1: with bytes of data =32

Reply from 192.168.0.11:bytes=32 time<1ms TTL =128


Reply from 192.168.0.11:bytes=32 time<1ms TTL =128
Reply from 192.168.0.11:bytes=32 time<1ms TTL =128
Reply from 192.168.0.11:bytes=32 time<1ms TTL =128

Ping statistics for 192.168.0.1


Packets: sent=4,received=4,lost=0(0% loss),approximate round trip time in milli seconds:
Minimum=1
ms,maximum=4ms,average=2ms
Talk client:
import java.io.*;
import java.net.*;
public class talkclient
{
public static void main(String args[])throws Exception
{
Socket c=null;
DataInputStream usr_inp=null;
DataInputStream din=new DataInputStream(System.in);
DataOutputStream dout=null;
try
{
c=new Socket("127.0.0.1",1234);
usr_inp=new DataInputStream(c.getInputStream());
dout=new DataOutputStream(c.getOutputStream());
}
catch(IOException e)
{}
if(c!=null || usr_inp!=null || dout!=null)
{
String unip;
System.out.println("\nEnter the message for server:");
while((unip=din.readLine())!=null)
{
dout.writeBytes(""+unip);
dout.writeBytes("\n");
System.out.println("reply");
System.out.println(usr_inp.readLine());
System.out.println("\n enter your message:");
}
System.exit(0);
}
din.close();
usr_inp.close();
c.close();
}
}
Talk server:
import java.io.*;
import java.net.*;
public class talkserver
{
public static void main(String args[])throws Exception
{
ServerSocket m=null;
Socket c=null;
DataInputStream usr_inp=null;
DataInputStream din=new DataInputStream(System.in);
DataOutputStream dout=null;
try
{
m=new ServerSocket(1234);
c=m.accept();
usr_inp=new DataInputStream(c.getInputStream());
dout=new DataOutputStream(c.getOutputStream());
}
catch(IOException e)
{}
if(c!=null||usr_inp!=null)
{
String unip;
while(true)
{
System.out.println("\nmessage from client:");
String m1=usr_inp.readLine();
System.out.println(m1);
System.out.println("enter your message:");
unip=din.readLine();
dout.writeBytes(""+unip);
dout.writeBytes("\n");
}
}
dout.close();
usr_inp.close();
c.close();
}
}
OUTPUT
Client:
C:\Program Files\Java\jdk1.6.0\bin>java talkclient
Enter your message:
hai
reply
hello
enter your message:
Server:
C:\Program Files\Java\jdk1.6.0\bin>java talkserver
message from client:
hai
enter your message:
hello
message from client:
RESULT:
Thus the program for echo ,ping and talk is successfully executed using java program
EX.NO:7
DATE: IMPLEMENTATION OF CSMA/CA

AIM:
To implement concept of Carrier Sense Multiple Access with Collision Avoidance(CSMA/CA) using
netsim.

ALGORITHM:

To begin with the experiment, open NetSim

Click on Simulation, select LAN network and Wireless Lan from the sub
menu. The simulation environment is now open.

i. Drag and drop the BSS and the Hub on the environment. Connect
the BSS and the hub.
ii. Drag and drop the node near to the BSS only. Two is the minimum
number of nodes required for transmission to take place.

CSMA/CA

fig 1, right click on the 1st node and select Point to Point from the
transmission option.
Click Configure and Simulate - you will see the performance metrics screen.
(Details on how to model broadcast traffic is available in the “?” file panel

Here click Close and save the


experiment.

Save
On being prompted whether you want to save the experiment click Yes.

Enter any file name as shown above and

click OK.

Retrieve
Rather then creating new scenarios each time, this can be done as follows.

After saving the experiment, click or File and Open from the sub menu
on the file panel.

Fig a
Fig b
Select LAN from fig a.
Select Wireless Lan- Protocol, Star-Hub Topology and the experiment
which you have saved for the Sample from fig b.
Click on the accept button

Now, you will obtain the initial scenario.


Set the traffic to Point to Point on one additional node (total of 2 nodes)
Click Configure and Simulate. …. Follow the same procedure increasing the
number of nodes by 1 every time, till all 6 nodes transmit Point to Point

INFERENCE:

The collision avoidance concept in wireless LAN protocol, avoids the


possibility of collision of data frames. The working of wireless LAN is such that
when a node transmits to the destination the data reaches the access point
(coordination point) and from there it is transmitted to the destination node.
Due to its nature of double transmission and protocol overheads, the
throughput is reduced by 50% when compared to Ethernet.

OUTPUT:

THROUGHPUT(%)

NO.OF.NODE
RESULT:
Thus the concept of Carrier Sense Multiple Access with Collision Avoidance(CSMA/CA) using
netsim was implemented and the output was verified.
EX.NO:8
DATE: IMPLEMENTATION OF NETWORK TOPOLOGY
STAR, BUS, RING

AIM:
To write a ns2 program for implementing network topology.

ALGORITHM:

Step 1: start the program.


Step 2: declare the global variables ns for creating a new simulator.
Step 3: set the color for packets.
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 6: set the unicast routing protocol to transfer the packets in network.
Step 7: create the required no of nodes.
Step 8: create the duplex-link between the nodes based on topology.
Step 9: give the position for the links between the nodes.
Step 10: set a tcp reno connection for source node.
Step 11: set the destination node using tcp sink.
Step 12: setup a ftp connection over the tcp connection.
Step 13: down the connection between any nodes at a particular time.
Step 14: reconnect the downed connection at a particular time.
Step 15: define the finish procedure.
Step 16: in the definition of the finish procedure declare the global variables ns,file1,file2.
Step 17: close the trace file and namefile and execute the network animation file.
Step 18: at the particular time call the finish procedure.
Step 19: stop the program.

PROGRAM:
BUS topology:
#Create a simulator object
set ns [new Simulator]

#Open the nam trace file


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

#Define a 'finish' procedure


proc finish {} {
global ns nf
$ns flush-trace
#Close the trace file
close $nf
#Executenam on the trace file
exec nam out.nam &
exit 0
}

#Create four nodes


set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]

#CreateLanbetween the nodes


set lan0 [$ns newLan "$n0 $n1 $n2 $n3 $n4" 0.5Mb 40ms LL Queue/DropTail MAC/Csma/Cd Cha
nnel]

#Create a TCP agent and attach it to node n0


set tcp0 [new Agent/TCP]
$tcp0 set class_ 1
$ns attach-agent $n1 $tcp0
#Create a TCP Sink agent (a traffic sink) for TCP and attach it to node n3
set sink0 [new Agent/TCPSink]
$ns attach-agent $n3 $sink0
#Connect the traffic sources with the traffic sink
$ns connect $tcp0 $sink0

# Create a CBR traffic source and attach it to tcp0


set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.01
$cbr0 attach-agent $tcp0

#Schedule events for the CBR agents


$ns at 0.5 "$cbr0 start"
$ns at 4.5 "$cbr0 stop"

#Call the finish procedure after 5 seconds of simulation time


$ns at 5.0 "finish"

#Run the simulation


$ns run

RING TOPOLOGY
#***********************************************************************#
#Aim : To monitor traffic for Ring topology using NS2
#***********************************************************************#

#Create a simulator object


set ns [new Simulator]

#Open the nam trace file


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

#Define a 'finish' procedure


proc finish {} {
global ns nf
$ns flush-trace
#Close the trace file
close $nf
#Executenam on the trace file
exec nam out.nam &
exit0
}

#Create four nodes


set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]

#Create links between the nodes


$ns duplex-link $n0 $n1 1Mb 10ms DropTail
$ns duplex-link $n1 $n2 1Mb 10ms DropTail
$ns duplex-link $n2 $n3 1Mb 10ms DropTail
$ns duplex-link $n3 $n4 1Mb 10ms DropTail
$ns duplex-link $n4 $n5 1Mb 10ms DropTail
$ns duplex-link $n5 $n0 1Mb 10ms DropTail

#Create a TCP agent and attach it to node n0


set tcp0 [new Agent/TCP]
$tcp0 set class_ 1
$ns attach-agent $n1 $tcp0
#Create a TCP Sink agent (a traffic sink) for TCP and attach it to node n3
set sink0 [new Agent/TCPSink]
$ns attach-agent $n3 $sink0
#Connect the traffic sources with the traffic sink
$ns connect $tcp0 $sink0

# Create a CBR traffic source and attach it to tcp0


set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.01
$cbr0 attach-agent $tcp0

#Schedule events for the CBR agents


$ns at 0.5 "$cbr0 start"
$ns at 4.5 "$cbr0 stop"

#Call the finish procedure after 5 seconds of simulation time


$ns at 5.0 "finish"

#Run the simulation


$ns run

Ring topology:

OUTPUT:

RESULT:
Thus the ns2 program to implement the network topology was written and the output was
verified.

EX.NO:9
DATE: IMPLEMENTATION OF DISTANCE VECTOR ROUTING

AIM:
To implement the concept of distance vector routing using NetSim.

DISTANCE VECTOR ROUTING:

Distance Vector Routing is one of the routing algorithms used in a Wide Area
Network for computing shortest path between source and destination.
The router is one of the main devices used in a wide area network. The main task
of the
router is routing. It forms the routing table and delivers the packets depending
upon the routes in the table – either directly or via an intermediate device
(perhaps another router).
Each router initially has information about its all neighbors (i.e., it is directly
connected). After a period of time, each router exchanges its routing table among
its neighbors. After certain number of exchanges, all routers will have the full
routing information about the area of the network.
After each table exchange, router re computes the shortest path between the
routers.
The algorithm used for this routing is called Distance Vector Routing.

ALGORITHM:

• Repeat the following steps until there is no change in the routing


table for all routers.
1. Take the Next Router routing table and its neighbor routing table.
2. Add the router entry that is not in your own routing table, but
exists in any one of the other routing tables. If the new router
entry exists in more than one neighbor, then find the minimum
cost among them. The minimum cost value details are taken as a
new entry: such as source router, intermediate router, destination
router and cost value, etc.
3. Update the source router routing table cost value if both the
destination router and the intermediate router field value have
the same value as any one of the neighbors’ routing entry.
4. Update the source router’s routing table entry with the new
advertised one if the intermediate router value in the source
table is not same, but the cost value is greater than the its
neighbor’s entry.
5. Write the next stage of routing table into the file. Repeat steps 1 to

5 for all routers.

Check whether any changes are made in any of the routers. If yes,
then repeat the above steps, otherwise, quit the process
DESCRIPTION:
To begin with the experiment, open NetSim

Click on Programming from the file panel and select Distance Vector
Routing.

The scenario will be obtained as shown below. Follow the steps.

When you select the User mode, you have to write your own
program in C/C++, compile and link to NetSim software for
validation.
Click on the button to view the file path.

Continue with the steps as given for sample

mode.

OUTPUT:
RESULT:
Thus the concept of Distance Vector Routing was implemented successfully and the output was
verified.
EX.NO:10
DATE: IMPLEMENTATION OF LINK STATE ROUTING
ALGORITHM

AIM:
To implement the concept Link state routing Algorithm using a netsim.

INTRODUCTION:

The router is one of the main devices used in a wide area network. The main task of
the router is routing. It forms the routing table and delivers the packets depending
upon the routes in the table – either directly or via an intermediate device
(perhaps another router).
Link state algorithm is a method used to find the shortest path between a source
router
and a destination router based on the distance and route the packets through that

route.

ALGORITHM:

1.
Start with the router: the root of the tree
2.
Assign a cost of 0 to this router and make it the first permanent router.
3.
Examine each neighbor router of the router that was the last permanent router.
4.
Assign a cumulative cost to each router and make it temporary.
5.
Among the list of temporary routers
5. a. Find the router with the smallest cumulative cost and make it permanent.
5. b. If a router can be reached from more than one direction
5. b.1. Select the direction with the shortest cumulative
cost.
6. Repeat steps 3 to 5 until every router becomes permanent. Description
To begin with the experiment, open NetSim

Click on Programming from the file panel and select Link State Routing

The scenario will be obtained as shown below. Follow the steps.


When you select the User mode, you have to write your own program in C/C++,
compile and link to NetSim software for validation.

Click on the button for details on how to proceed with your own code.

Click on the button to view the file path.

Continue with the steps as given for sample mode.


Inference (to be filled up by the
students)
Here, Router 1 is taken as the source and Router 3 as the destination. The paths are
connected with input as the distance. The figure indicated in red line shows the shortest
path.

RESULT:
Thus the concept of Link State Routing was implemented using netsim and output was verified
EX.NO :11 STUDY OF NETWORK SIMULATOR (NS) AND
OF CONGESTION CONTROL ALGORITHMS USING NS2
DATE:

Aim:

To Study of Network simulator (NS).and Simulation of Congestion Control Algorithms using


NS2.

NET WORK SIMULATOR (NS2)


Ns overview

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 (ns-2.26, Feb 2003)

Platform support

FreeBSD, Linux, Solaris, Windows and Mac

Ns unctionalities

Routing, Transportation, Traffic sources,Queuing


disciplines, QoS

Wireless

Ad hoc routing, mobile IP, sensor-MAC


Tracing, visualization and various utilitie
NS(Network Simulators)

Most of the commercial simulators are GUI driven, while some network simulators are CLI driven.
The network model / configuration describes the state of the network (nodes,routers, switches, links)
and the events (data transmissions, packet error etc.). An important output of simulations are the trace
files. Trace files log every packet, every event that occurred in the simulation and are used for
analysis. Network simulators can also provide other tools to facilitate visual analysis of trends and
potential trouble spots.

Most network simulators use discrete event simulation, in which a list of pending "events" is stored,
and those events are processed in order, 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.

Simulation of networks is a very complex task. For example, if congestion is high, then estimation of
the average occupancy is challenging because of high variance. To estimate the likelihood of a buffer
overflow in a network, the time required for an accurate answer can be extremely large. Specialized
techniques such as "control variates" and "importance sampling" have been developed to speed
simulation.

Examples of network simulators

There are many both free/open-source and proprietary network simulators. Examples of notable
network simulation software are, ordered after how often they are mentioned in research papers:

1. ns (open source)
2. OPNET (proprietary software)
3. NetSim (proprietary software)

Uses of network simulators

Network simulators serve a variety of needs. Compared to the cost and time involved in setting up an
entire test bed containing multiple networked computers, routers and data links, network simulators
are relatively fast and inexpensive. They allow engineers, researchers to test scenarios that might be
particularly difficult or expensive to emulate using real hardware - for instance, simulating a scenario
with several nodes or experimenting with a new protocol in the network. Network simulators are
particularly useful in allowing researchers to test new networking protocols or changes to existing
protocols in a controlled and reproducible environment. 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. With the help of simulators, one can design
hierarchical networks using various types of nodes like computers, hubs, bridges, routers, switches,
links, mobile units etc.

Various types of Wide Area Network (WAN) technologies like TCP, ATM, IP etc. and Local Area
Network (LAN) technologies like Ethernet, token rings etc., can all be simulated with a typical
simulator and the user can test, analyze various standard results apart from devising some novel
protocol or strategy for routing etc. Network simulators are also widely used to simulate battlefield
networks in Network-centric warfare

Packet loss

occurs when one or morepacketsof data travelling across a computer networkfail to reachtheir
destination. Packet loss is distinguished as one of the three main error types encountered in digital
communications; 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. The amount of packet loss during the steady state is another important property of a
congestion control scheme. The larger the value of packet loss, the more difficult it is for
transportlayer protocols to maintain high bandwidths, the sensitivity to loss of individual packets, as
well as to frequency and patterns of loss among longer packet sequences is strongly dependent on the
application itself.

Throughput

This is the main performance measure characteristic, and most widely used.
Incommunicationnetworks, such asEthernetorpacket radio, throughputor network throughputis the
average rate of successfulmessage delivery over a communication channel. The throughput is usually
measured inbitsper second (bit/s orbps), 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. It is determined as the ratio of the total data received to the end to end delay. 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.g., source premise or network
ingress to destination premise or network degrees. The larger the valueof delay, the more difficult it
is for transport layer protocols to maintain highbandwidths. We will calculate end to end delay

Queue Length

A queuing system in networks can be described as packets arriving for service, waiting for service if
it is not immediate, and if having waited for service, leaving thesystem after being served. Thus
queue length is very important characteristic to determine that how well the active queue
management of the congestion control algorithm has been working.

RESULT:
Thus Network simulator (NS).and Simulation of Congestion Control Algorithms using NS2 was
studied.
EX.NO:11a
DATE: IMPLEMENTATION OF UNICAST ROUTING PROTOCOL

AIM:
To write a ns2 program for implementing unicast routing protocol.

ALGORITHM:

Step 1: start the program.


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


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

#Open the NAM trace file


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

#Define a 'finish' procedure


proc finish {} {
global ns file1 file2
$ns flush-trace
close $file1
close $file2
exec nam out.nam &
exit 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]

#Create links between the nodes


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


set tcp [new Agent/TCP/Newreno]
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink/DelAck]
$ns attach-agent $n5 $sink
$ns connect $tcp $sink
$tcp set fid_ 1

#Setup a FTP over TCP connection


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

$ns rtmodel-at 1.0 down $n1 $n4


$ns rtmodel-at 4.5 up $n1 $n4

$ns at 0.1 "$ftp start"

$ns at 6.0 "finish"

$ns run

OUTPUT:
RESULT:
Thus the ns2 program to implement the concept of unicast routing protocol was written and the
output was verified.
EX.NO:12
DATE: IMPLEMENTATION OF DATA ENCRYPTION AND DECRYPTION

AIM:

To implement the concept of Data encryption and decryption using netsim.

DATA ENCRYPTION AND DECRYPTION:

In encryption, each letter position in the file text which is given in encrypt mode is
changed according to the ascending order of the key text.

In decryption each letter position in the encrypted file text is changed according to the
ascending order of the key text.

ALGORITHM:

ENCRYPTION:

1. Get the text to be encrypted (plain text) and key text.


2. Find the length of the plain text.
3. For i=1 to length of plain text
Find the binary equivalent of ith character of plain text.
Find the binary equivalent of ith character of key text
Find the XOR of above two values.
4. The resulting value will be the encrypted format (cipher text) of the plain text.

DECRYPTION:

1. Get the text to be decrypted (cipher text) and key text.


2. Fnd the length of the cipher text.
3. For i=1 to length of cipher text
Find the binary equivalent of ith character of cipher text.
Find the binary equivalent of ith character of key text
Find the XOR of above two values.
4. The resulting value will be the decrypted format (original plain text) of the cipher
plain text.
DESCRIPTION:
To begin with the experiment, open NetSim

Click on Programming from the file panel and select Cryptography,this opens a sub-menu
.In that select XOR.

The scenario will be obtained as shown below. Follow the steps.

FOR ENCRYPTION,

Select sample mode

Select encryption
Enter the plain text
Enter the key text

Click link to
execute the
program
FOR DECRYPTION,

Select sample mode

Select decryption

Enter the cipher


text
Enter the key
text
click link to execute the
program
RESULT:
Thus the concept of Data encryption and decryption using netsim was implemented and
output was verified.

Das könnte Ihnen auch gefallen