Вы находитесь на странице: 1из 75

DMI COLLEGE OF ENGINEERING

PALANCHUR CHENNAI – 600 123

DEPARTMENT OF ELECTRONICS AND COMMUNICATION


ENGINEERING

LABORATORY MANUAL

SUB CODE : EC6611


SUBJECT TITLE: COMPUTER NETWORKS LABORATORY
SEMESTER : VI
YEAR : III
DEPARTMENT : ELECTRONICS AND COMMUNICATION ENGINEERING
EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

Vision of the Department

To develop committed and competent technologists in electronics and communication


engineering to be on par with global standards coupled with cultivating the innovations and ethical
values.

Mission of the Department:

DM 1: To be a centre of excellence in teaching learning process promoting active learning with


critical thinking.

DM 2: To strengthen the student’s core domain and to sustain collaborative industry interaction with
internship and incorporating entrepreneur skills.

DM 3: To prepare the students for higher education and research oriented activities imbibed with
ethical values for addressing the social need.

PROGRAM EDUCATIONAL OBJECTIVES (PEOs):

PEO1. CORE COMPETENCY WITH EMPLOYABILITY SKILLS: Building on fundamental


knowledge, to analyze, design and implement electronic circuits and systems in Electronics and
Communication Engineering by applying knowledge of mathematics and science or in closely related
fields with employability skills.

PEO2. PROMOTE HIGHER EDUCATION AND RESEARCH AND DEVELOPMENT: To


develop the ability to demonstrate technical competence and innovation that initiates interest for
higher studies and research.

PEO3. INCULCATING ENTREPRENEUR SKILLS: To motivate the students to become


Entrepreneurs in multidisciplinary domain by adapting to the latest trends in technology catering the
social needs.

PEO4. ETHICAL PROFESSIONALISM: To develop the graduates to attain professional


excellence with ethical attitude, communication skills, team work and develop solutions to the
problems and exercise their capabilities.

DMI College Of Engineering 1


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

PROGRAM OUTCOMES (POs)

The Program Outcomes (POs) are described as.

1. Engineering Knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals and an engineering specialization to the solution of complex engineering problems.
2. Problem Analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.
3. Design / Development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate consideration
for the public health and safety, and the cultural, societal, and environmental considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with
an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need for
sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms
of the engineering practice.
9. Individual and team work: Function effectively as an individual and as a member or leader in
diverse teams, and in multidisciplinary settings.

10. Communication: Communicate effectively on complex engineering activities with the


engineering community and with society at large, such as, being able to comprehend and write

DMI College Of Engineering 2


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

effective reports and design documentation, make effective presentations, and give and receive clear
instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering management principles and apply these to one’s own work, as a member and leader in a
team, to manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for and have the preparation and ability to engage in
independent and lifelong learning in the broadest context of technological change.

PROGRAM SPECIFIC OUTCOMES (PSOs):

PSO1. Analyze and design the analog and digital circuits or systems for a given specification and
function.

PSO2. Implement functional blocks of hardware-software co-designs for signal processing and
communication applications.

PSO3. Design, develop and test electronic and embedded systems for applications with real time
constraint and to develop managerial skills with ethical behavior to work in a sustainable environment.

DMI College Of Engineering 3


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

INSTRUCTIONS TO STUDENTS FOR WRITING THE RECORD

In the record, the index page should be filled properly by writing the corresponding
experiment number, experiment name , date on which it was done and the page number.

On the right side page of the record following has to be written:

1. Title: The title of the experiment should be written in the page in capital letters.

2. In the left top margin, experiment number and date should be written.

3. Aim: The purpose of the experiment should be written clearly.

4. Apparatus/Tools/Equipments/Components used: A list of the Apparatus/Tools/ Equipments/


Components used for doing the experiment should be entered.

5. Theory: Simple working of the circuit/experimental set up/algorithm should be written.

6. Procedure: Steps for doing the experiment and recording the readings should be briefly
described(flow chart/ Circuit Diagrams / programs in the case of computer/processor related
experiments)
7. Results: The results of the experiment must be summarized in writing and should be
fulfilling the aim.

On the Left side page of the record following has to be recorded:

a) Circuit/Program: Neatly drawn circuit diagrams for the experimental set up.

b) Design: The design of the circuit components for the experimental set up for
selecting the components should be clearly shown if necessary.
3. Observations:

i) Data should be clearly recorded using Tabular Columns.

ii) Unit of the observed data should be clearly mentioned

iii) Relevant calculations should be shown. If repetitive calculations are needed, only show a
sample calculation and summarize the others in a table.

DMI College Of Engineering 4


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

EC6611 COMPUTER NETWORKS LABORATORY LTP C


0 0 3 2

LIST OF EXPERIMENTS:
1. Implementation of Error Detection / Error Correction Techniques
2. Implementation of Stop and Wait Protocol and sliding window
3. Implementation and study of Go-back-N and selective repeat protocols
4. Implementation of High Level Data Link Control
5. Study of Socket Programming and Client – Server model
6. Write a socket Program for Echo/Ping/Talk commands.
7. To create scenario and study the performance of network with CSMA / CA protocol and
compare with CSMA/CD protocols.
8. Network Topology – Star, Bus, Ring
9. Implementation of distance vector routing algorithm
10. Implementation of Link state routing algorithm
11. Study of Network simulator (NS) and simulation of Congestion Control Algorithms using NS
12. Encryption and decryption.

TOTAL: 45 PERIODS

DMI College Of Engineering 5


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

Course outcomes

Students able to understand the concepts of PC to PC Communication, Parallel


CO1
and serial communications

Students will demonstrate skills to understand the given scenario and analyze the
CO2
performance of various protocols.

Students able to implement various routing algorithms so that all available links
CO 3
will be utilized effectively

Students will show the ability to derive various encryption and decryption
CO 4
algorithms.
Students shows skills to implement Stop and Wait, Go back N and Selective
CO 5
Repeat protocols..

CO PO, PSO Mappings:

Course Program Outcomes PSO


Code and
CO
Course 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3
name
CO 1 2 - - - - 2 3 2 3 2 2 2 2 - -
EC6611 CO 2 2 - - - - 1 2 3 2 3 2 2 2 - -
Computer
CO 3 3 - - - - 2 3 2 3 2 3 3 3 - -
Networks
Laboratory CO4 3 - - - - 3 2 2 3 2 3 2 3 - -
CO 5 3 - - - - 2 3 2 3 3 3 2 3 - -
Average 3 - - - - 2 2.6 2.2 3 2 3 2.2 3 - -

DMI College Of Engineering 6


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

S.NO LIST OF EXPERIMENTS PAGE NO.

1.a TCP Socket Program In Java For Chat Server And Client 8

1.b TCP Socket Program In Java For Chat Server And Client 12

2 UDP Socket Program In ‘C’ For File Transfer 16

3 Ping Command Program Using Java 20

4 Implementation of sliding window protocol using Java 23

5 Implementation of Stop & Wait Protocol 29

6 Implementation of Encryption And Decryption Of A Data 37

7 Implementation of High Level Data Link Control 40

8 Implementation of Error Detection And Correction Technique 43

9 Study of Network Simulator (NS2) 48

10 Simulation of Congestion Control Algorithm 59

11 Implementation of Distance Vector Routing Algorithm 64

12 Implementation of Link State Routing Algorithm 69

Content beyond syllabus

S.NO LIST OF EXPERIMENTS PAGE NO.


1 Implementation of Subnetting. 73

DMI College Of Engineering 7


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

EX.NO.1.a TCP SOCKET PROGRAM IN JAVA FOR CHAT SERVER AND CLIENT

AIM:
To develop a chat server and client program in Java using TCP socket.
ALGORITHM:
SERVER:
1. Create a server socket.
2. Wait for client to be connected.
3. Read client’s message and display it.
4. Get a message from user and send it.
5. Repeat step 3-4 until the client end.
6. Close the stream.
7. Close the server and client socket.
8. Stop.
CLIENT:
1. Create the client socket and establish connection with server.
2. Get a message from user and send it to server.
3. Read all inputs / outputs stream.
4. Close the client socket.
5. Stop.

Client Program
import java.io.*;
import java.net.*;
public class chatclient
{
public static void main (String args[]) throws Exception
{

DMI College Of Engineering 8


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

Socket sock = new Socket("172.16.15.19",3000);


BufferedReader KeyRead = new BufferedReader(new InputStreamReader(System.in));
OutputStream ofstream = sock.getOutputStream();
PrintWriter pwrite = new PrintWriter(ofstream,true);
InputStream istream=sock.getInputStream();
BufferedReader receivedread=new BufferedReader(new InputStreamReader(istream));
System.out.println("client ready for chatting");
String receivemessage,sendmessage;
while(true)
{
sendmessage=KeyRead.readLine();
pwrite.println(sendmessage);
System.out.flush();
if((receivemessage=receivedread.readLine())!=null)
{
System.out.println(receivemessage);
}
}
}
}
Server Program
import java.io.*;
import java.net.*;
public class chatserver
{
public static void main(String args[])throws Exception
{
ServerSocket sersock=new ServerSocket(3000);
System.out.println("Server ready for chatting");
Socket sock=sersock.accept();
BufferedReader KeyRead = new BufferedReader(new InputStreamReader(System.in));

DMI College Of Engineering 9


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

OutputStream ofstream=sock.getOutputStream();
PrintWriter pwrite=new PrintWriter(ofstream,true);
InputStream istream=sock.getInputStream();
BufferedReader receivedread = new BufferedReader(new InputStreamReader(istream));
String receivemessage,sendmessage;
while(true)
{
if((receivemessage = receivedread.readLine())!=null)
{
System.out.println(receivemessage);
}
sendmessage=KeyRead.readLine();
pwrite.println(sendmessage);
System.out.flush();
}
}
}

DMI College Of Engineering 10


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

Output:

Result:
Thus the TCP chat server and client is performed using Java.

DMI College Of Engineering 11


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

TCP SOCKET PROGRAM IN JAVA TO DISPLAY SYSTEM


EX.NO.1.b
SYSTEM CONFIGURATION

AIM:

To develop client server model in Java using TCP socket to display current systems date, time
and IP address.

ALGORITHM:

SERVER:

1. Create a socket.
2. Bind the socket to an address.
3. Listen for connection
4. Accept a connection.
5. Send and receive data.

CLIENT:

1. Create a server socket


2. Connect the socket to the address of the server
3. Send and receive the data

TCPDATECLIENT.JAVA

import java.net.*;
import java.io.*;
class tcpdateclient
{
public static void main(String args[])
{
Socket soc;
BufferedReader dis;
String sdate;
PrintStream ps;
try
{
InetAddress ia=InetAddress.getLocalHost();
if(args.length==0)

DMI College Of Engineering 12


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

soc=new Socket(InetAddress.getLocalHost(),4444);
else soc=new Socket(InetAddress.getByName(args[0]),4444);
dis=new BufferedReader(new InputStreamReader(soc.getInputStream()));
sdate=dis.readLine();
System.out.println("the date and time on server is :"+sdate);
ps=new PrintStream(soc.getOutputStream());
ps.println(ia);
ps.close();
}
catch(IOException e)
{
System.out.println("the exception is"+e);
}
}
}

TCPDATESERVER.JAVA

import java.net.*;
import java.io.*;
import java.util.*;
class tcpdateserver
{
public static void main(String args[])
{
ServerSocket ss=null;
Socket cs;
PrintStream ps;
BufferedReader dis;
String inet;
try
{
ss=new ServerSocket(4444);
System.out.println("press ctrl+c to quit");
while(true)
{
cs=ss.accept();
ps=new PrintStream(cs.getOutputStream());
Date d=new Date();
ps.println(d);
dis=new BufferedReader(new InputStreamReader(cs.getInputStream()));

DMI College Of Engineering 13


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

inet=dis.readLine();
System.out.println("client system IP address is:"+inet);
ps.close();
dis.close();
}}
catch(IOException e)
{
System.out.println("the ecxeption is"+e);
}}}

DMI College Of Engineering 14


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

OUTPUT:

RESULT:

Thus the socket program for displaying current date, time and IP address is

implemented successfully.

DMI College Of Engineering 15


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

EX NO:2 UDP SOCKET PROGRAM IN ‘C’ FOR FILE TRANSFER

AIM:

To develop UDP client and server model in ‘c’ to transfer a text file.

ALGORITHM:

SERVER:

1. Declare the variable and structure for a server datagram socket using socket using socket
function.
2. Bind the local IP address to the port number using bind function.
3. Specify the number of client that the server can connect using listen function.
4. After accepting,receive the message sent by the client using recv function.
5. The characters are fetched from file using ‘fopen’ and ‘fgetc’ function.
6. Then send the characters to the client using ‘send’ function.
7. Close the server socket and connection socket.

CLIENT:

1. Create a datagram socket for client using socket function.


2. Send the message to the server using send function.
3. Close the client socket.
4. The file name that is to be transferred is specified in the client.
5. The contents of the file are verified from the server side.

Client

#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
main()
{
struct sockaddr_in cli,serv;

DMI College Of Engineering 16


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

int sockfd,len;
char msg[50],rec[100];
sockfd=socket(AF_INET,SOCK_DGRAM,0);
cli.sin_family=AF_INET;
cli.sin_port=3261;
cli.sin_addr.s_addr=INADDR_ANY;
printf("enter the file name");
scanf("%s",msg);
sendto(sockfd,msg,sizeof(msg),0,(struct sockaddr *)&cli,sizeof(struct sockaddr));
printf("the received file content is");
len=sizeof(struct sockaddr);
recvfrom(sockfd,rec,sizeof(rec),0,(struct sockaddr*)&cli,&len);
printf("%s",rec);
close(sockfd);
}
Server
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
main()
{
struct sockaddr_in serv,cli;
int sockfd,len,i=0;
char rec[50],ch[50];
FILE *fp;
sockfd=socket(AF_INET,SOCK_DGRAM,0);
serv.sin_family=AF_INET;
serv.sin_port=3261;

DMI College Of Engineering 17


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

serv.sin_addr.s_addr=INADDR_ANY;
bind(sockfd,(struct sockaddr*)&serv,sizeof(struct sockaddr));
listen(sockfd,5);
len=sizeof(struct sockaddr);
recvfrom(sockfd,rec,sizeof(rec),0,(structsockaddr*)&cli,&len);
printf("the file name is\n");printf("%s\n",rec);
fp=fopen(rec,"r");
if(fp==NULL)
{
printf("error");
exit(0);
}
while(fgets(ch,50,fp)!=NULL)
{
printf("%s",ch);
}
fcloseall();
sendto(sockfd,ch,sizeof(ch),0,(struct sockaddr*)&cli,sizeof(struct sockaddr));
close(sockfd);
}

DMI College Of Engineering 18


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

Out put:
server:

[root@Localhost~]# cc su.c

[root@Localhost~]#./a.out

The file name is

Test.txt

Hi,welcome.

Client:

[root@Localhost~]# cc cu.c

[root@Localhost~]#./a.out

Enter the file name

Test.txt

The received file content is

Hi,welcome.

RESULT:

Thus the client server model using UDP socket has been developed successfully for File
Transfer.

DMI College Of Engineering 19


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

EX. No. 3 PING COMMAND PROGRAM USING JAVA

AIM:

To write a Java program to execute the PING command.

ALGORITHM:

1. Start the process.


2. Establish the connection between two systems
3. Get the address of the system to be pinged
4. Print the number of packets sent and received
5. Stop the process.

PROGRAM:

import java.io.*;

import java.net.*;

class pingTest {

public static void main(String[] args) {

String ip = "127.0.0.1";

String pingResult = "";

String pingCmd = "ping " + ip;

try {

Runtime r = Runtime.getRuntime();

Process p = r.exec(pingCmd);

BufferedReader in = new BufferedReader(new

InputStreamReader(p.getInputStream()));

String inputLine;

while ((inputLine = in.readLine()) != null) {

System.out.println(inputLine);

DMI College Of Engineering 20


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

pingResult += inputLine;

in.close();

} catch (IOException e) {

System.out.println(e);

DMI College Of Engineering 21


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

Output:

Result:

Thus the PING command program was executed successfully.

DMI College Of Engineering 22


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

IMPLEMENTATION OF SLIDING WINDOW PROTOCOL USING


EX. NO. 4
JAVA

AIM:

To write a JAVA program to simulate a sliding window protocol that uses Selective Repeat
ARQ.

ALGORITHM:

SERVER:

1. Create a server socket.


2. Assume the sending window size
3. If the receiver is ready initialize sender’s frame sequence to 0
4. Get data from user
5. Send it to the receiver along with sequence number
6. Increment sequence number by 1
7. Repeat step 4-6 until all frames have been sent
8. Wait for acknowledgement
9. If all ACK have arrived then go to step 11.
10. Set sequence number to earliest outstanding frame for which there is no ACK. Go to step 4
11. Stop

CLIENT:

1. Create a socket for client


2. Indicate to sender, the readiness to accept frames
3. Initialize receiver’s expected frame sequence to 0
4. Accept the incoming frame
5. If frame’s sequence == receiver’s sequence and go to step 6.
6. Send an ACK.
7. Repeat step 3-6 until all frames are received in sequence and go to step 8.
8. Discard frame, thereby force the sender to retransmit. Go to step 3.
9. Stop.

SENDER:

import java.net.*;
import java.io.*;
import java.rmi.*;
public class slidsender

DMI College Of Engineering 23


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

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;

DMI College Of Engineering 24


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

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:

import java.net.*;

import java.io.*;

class slidreceiver

public static void main(String a[])throws Exception

DMI College Of Engineering 25


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

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

DMI College Of Engineering 26


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

while(ch.equals("yes"));

DMI College Of Engineering 27


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

OUTPUT:

RESULT:

Thus the program for sliding window protocol was implemented successfully.

DMI College Of Engineering 28


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

EX. NO : 5 IMPLEMENTATION OF STOP & WAIT PROTOCOL

AIM
To implement the stop and wait protocol using Java .

PROCEDURE
Sender
Step1: sequence  0
Step2: Accept new packet and assign sequence to it.
Step3: Send packet sequence with sequence number sequence.
Step4: Set timer for recently sent packets.
Step5: If error free acknowledgment from receiver and NextFrameExpected -> sequence
then sequence NextFrameExpected.
Step6: If time out then go to step3.
Step7: Stop.
Receiver
Step1: Start.
Step2: NextFrameExpectedß 0, repeat steps 3 forever.
Step3: If error-free frame received and sequence= NextFrameExpected, then pass packet to higher
layer and NextFrameExpectedß NextFrameExpected+1(modulo 2).
Step4: Stop.
Sender.java

import java.io.*;

import java.net.*;

public class Sender{

Socket sender;

ObjectOutputStream out;

ObjectInputStream in;

String packet,ack,str, msg;

DMI College Of Engineering 29


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

int n,i=0,sequence=0;

Sender(){}

public void run(){

try{

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Waiting for Connection....");

sender = new Socket("localhost",2005);

sequence=0;

out=new ObjectOutputStream(sender.getOutputStream());

out.flush();

in=new ObjectInputStream(sender.getInputStream());

str=(String)in.readObject();

System.out.println("reciver > "+str);

System.out.println("Enter the data to send....");

packet=br.readLine();

n=packet.length();

do{

try{

if(i<n){

msg=String.valueOf(sequence);

msg=msg.concat(packet.substring(i,i+1));

}else if(i==n){

msg="end";out.writeObject(msg);break;

}out.writeObject(msg);

sequence=(sequence==0)?1:0;

DMI College Of Engineering 30


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

out.flush();

System.out.println("data sent>"+msg);

ack=(String)in.readObject();

System.out.println("waiting for ack.....\n\n");

if(ack.equals(String.valueOf(sequence))){

i++;

System.out.println("receiver > "+" packet recieved\n\n");

}else{

System.out.println("Time out resending data....\n\n");

sequence=(sequence==0)?1:0;

}}catch(Exception e){}

}while(i<n+1);

System.out.println("All data sent. exiting.");

}catch(Exception e){}

finally{

try{

in.close();

out.close();

sender.close();

catch(Exception e){}

}}

public static void main(String args[]){

Sender s=new Sender();

s.run();

DMI College Of Engineering 31


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

}}

Receiver.java

import java.io.*;

import java.net.*;

public class Receiver{

ServerSocket reciever;

Socket connection=null;

ObjectOutputStream out;

ObjectInputStream in;

String packet,ack,data="";

int i=0,sequence=0;

Receiver(){}

public void run(){

try{

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

reciever = new ServerSocket(2005,10);

System.out.println("waiting for connection...");

connection=reciever.accept();

sequence=0;

System.out.println("Connection established :");

out=new ObjectOutputStream(connection.getOutputStream());

out.flush();

in=new ObjectInputStream(connection.getInputStream());

out.writeObject("connected .");

DMI College Of Engineering 32


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

do{

try{

packet=(String)in.readObject();

if(Integer.valueOf(packet.substring(0,1))==sequence){

data+=packet.substring(1);

sequence=(sequence==0)?1:0;

System.out.println("\n\nreceiver >"+packet);

else

System.out.println("\n\nreceiver >"+packet +" duplicate data");

}if(i<3){

out.writeObject(String.valueOf(sequence));i++;

}else{

out.writeObject(String.valueOf((sequence+1)%2));

i=0;

}}

catch(Exception e){}

}while(!packet.equals("end"));

System.out.println("Data recived="+data);

out.writeObject("connection ended .");

}catch(Exception e){}

finally{

try{in.close();

out.close();

DMI College Of Engineering 33


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

reciever.close();

catch(Exception e){}

}}

public static void main(String args[]){

Receiver s=new Receiver();

while(true){

s.run();

DMI College Of Engineering 34


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

DMI College Of Engineering 35


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

RESULT:

Thus the program is executed successfully and the output is verified.

DMI College Of Engineering 36


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

EX.NO:6 IMPLEMENTATION OF ENCRYPTION AND DECRYPTION OF


A DATA

AIM:

To write a ‘C’ program to implement Encryption and Decryption of a data.

ALGORITHM:

1.Initialize the variables.

2.Enter the data to be encrypted.

3.Using encrypt function,encrypt the data and print it.

4.Using decrypt the data and print it.

PROGRAM:

#include<stdio.h>
#include<string.h>
void encrypt(char password[],int key)
{
unsigned int i;
for(i=0;i<strlen(password);++i)
{
password[i]=password[i]-key;
}
}
void decrypt(char password[],int key)
{
unsigned int i;
for(i=0;i<strlen(password);++i)
{
password[i]=password[i]+key;
}

DMI College Of Engineering 37


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

}
int main()
{
char password[20];
printf("enter the password:\n");
scanf("%s",password);
printf("password=%s\n",password);
encrypt(password,0xFACA);
printf("encrypted value=%s\n",password);
decrypt(password,0xFACA);
printf("Decrypted value=%s\n",password);
return(0);
}

DMI College Of Engineering 38


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

OUTPUT:

RESULT:

Thus the encryption and decryption of a data was executed successfully using ‘C’.

DMI College Of Engineering 39


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

EX.NO:7 IMPLEMENTATION OF HIGH LEVEL DATA LINK CONTROL

AIM:

To write a ‘C’ program to implement High Level Data Link Control.

ALGORITHM:
1. Initialize the variables.
2. Enter the string of bits.
3. Insert a flag value.
4. Insert a zero at the beginning and end of each flag value
PROGRAM:
#include<stdio.h>
#include<string.h>
main()
{
int i,j,count=0,nl;
char str[100];
printf("enter the bit string:");
gets(str);
for(i=0;i<strlen(str);i++)
{
count=0;
for(j=i;j<=(i+5);j++)
{
if(str[j]=='1')
{
count++;
}
}
if(count==6)

DMI College Of Engineering 40


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

{
nl=strlen(str)+2;
for(;nl>=(i+5);nl--)
{
str[nl]=str[nl-1];
}
str[i+5]='0';
i=i+7;
}
}
puts(str);
}

DMI College Of Engineering 41


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

OUTPUT:

ENTER THE BIT STRING: 000111111001

000111110001

RESULT:

Thus the high level data link program was executed successfully.

DMI College Of Engineering 42


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

IMPLEMENTATION OF ERROR DETECTION AND


Ex. NO. 8
CORRECTION TECHNIQUE

AIM:

To write a ‘C’ program to implement Error Detection and Correction Techniques.

ALGORITHM:

1. Get four bit data


2. Generate the generator matrix
3. Encode the data
4. Create parity check matrix
5. Enter the error data
6. Calculate syndrome using e.HT
7. Decode the error data.

PROGRAM:
#include<stdio.h>
#include<stdlib.h>
char data[5];
int encoded[8],edata[7],syndrome[3];
int hmatrix[3][7] = {
1,0,0,0,1,1,1,
0,1,0,1,0,1,1,
0,0,1,1,1,0,1
};
char gmatrix[4][8]={"0111000","1010100","1100010","1110001"};

int main(){
int i,j;

printf("\nHamming code----- Encoding\n");


printf("Enter 4 bit data : ");
DMI College Of Engineering 43
EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

scanf("%s",data);
printf("\nGenerator matrix\n");
for(i=0;i<4;i++)
printf("%s\n",gmatrix[i]);
printf("\nEncoded data ");
for(i=0;i<7;i++)
{
for(j=0;j<4;j++)
encoded[i]+=((data[j]-'0')*(gmatrix[j][i]-'0'));
encoded[i]=encoded[i]%2;
printf("%d ",encoded[i]);
}
printf("\nHamming code----- Decoding\n");
printf("Enter encoded bits as recieved : ");
for(i=0;i<7;i++)
scanf("%d",&edata[i]);
for(i=0;i<3;i++)
{
for(j=0;j<7;j++)
syndrome[i]+=(edata[j]*hmatrix[i][j]);
syndrome[i]=syndrome[i]%2;
}
for(j=0;j<7;j++)
if((syndrome[0]==hmatrix[0][j]) && (syndrome[1]==hmatrix[1][j])&&
(syndrome[2]==hmatrix[2][j]))
break;
if(j==7)
printf("\nError free\n");
else
{
printf("\nError recieved at bit number %d of data\n",j+1);

DMI College Of Engineering 44


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

edata[j]=!edata[j];
printf("\nCorrect data should be : ");
for(i=0;i<7;i++)
printf("%d",edata[i]);

} getch();
return 0;

DMI College Of Engineering 45


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

OUTPUT:

DMI College Of Engineering 46


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

RESULT:

Thus the program for High Level Data Link was implemented successfully.

DMI College Of Engineering 47


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

EX. NO. 9 STUDY OF NETWORK SIMULATOR (NS2)

INTRODUCTION

The network simulator is discrete event packet level simulator.The network simulator covers a
very large number of applications of different kind of protocols of different network types consisting
of different network elements and traffic models. Network simulator is a package of tools that
simulates behavior of networks such as creating network topologies, log events that happen under any
load, analyze the events and understand the network. Well the main aim of our first experiment is to
learn how to use network simulator and to get acquainted with the simulated objects and understand
the operations of network simulation and we also need to analyze the behavior of the simulation object
using network simulation.

Platform required to run network simulator

 Unix and Unix like systems


 Linux (Use Fedora or Ubuntu versions)
 Free BSD
 SunOS/Solaris
 Windows 95/98/NT/2000/XP

Backend Environment of Network Simulator


Network Simulator is mainly based on two languages.They are C++ and OTcl. OTcl is the
object oriented version of Tool Command language.The network simulator is a bank of of different
network and protocol objects. C++ helps in the following way:

 It helps to increase the efficiency of simulation.


 Its is used to provide details of the protocols and their operation.
 It is used to reduce packet and event processing time.
OTcl helps in the following way:
 With the help of OTcl we can describe different network topologies
 It helps us to specify the protocols and their applications

DMI College Of Engineering 48


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

 It allows fast development


 Tcl is compatible with many platforms and it is flexible for integration
 Tcl is very easy to use and it is available in free

Basics of Tcl Programming (w.r.t. ns2)


Before we get into the program we should consider the following things:
1. Initialization and termination aspects of network simulator.
2. Defining the network nodes,links,queues and topology as well.
3. Defining the agents and their applications
4. Network Animator(NAM)
5. Tracing

Initialization
To start a new simulator we write
1. set ns [new Simulator]
From the above command we get that a variable ns is being initialized by using the set command. Here
the code [new Simulator] is a instantiation of the class Simulator which uses the reserved word 'new'.
So we can call all the methods present inside the class simulator by using the variable ns.

Creating the output files


1 #To create the trace files we write
2
3 set tracefile1 [open out.tr w]
4 $ns trace-all $tracefile1
5
6 #To create the nam files we write
7
8 set namfile1 [open out.nam w]
9 $ns namtrace-all $namfile

DMI College Of Engineering 49


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

In the above we create a output trace file out.tr and a nam visualization file out.nam. But in the Tcl
script they are not called by their names declared,while they are called by the pointers initialized for
them such as tracefile1 and namfile1 respectively.The line which starts with '#' are commented.The
next line opens the file 'out.tr' which is used for writing is declared 'w'.The next line uses a simulator
method trace-all by which we will trace all the events in a particular format.
The termination program is done by using a 'finish' procedure

01 # Defining the 'finish' procedure'


02
03 proc finish {} {
04 global ns tracefile1 namfile1
05 $ns flush-trace
06 close $tracefile
07 close $namfile
08 exec nam out.nam &
09 exit 0
10 }

In the above the word 'proc' is used to declare a procedure called 'finish'.The word 'global' is used to
tell what variables are being used outside the procedure.
'flush-trace' is a simulator method that dumps the traces on the respective files.the command 'close' is
used to close the trace files and the command 'exec' is used to execute the nam visualization.The
command 'exit' closes the application and returns 0 as zero(0) is default for clean exit.

In ns we end the program by calling the 'finish' procedure

1 #end the program


2 $ns at 125.0 "finish"

Thus the entire operation ends at 125 seconds.To begin the simulation we will use the command

DMI College Of Engineering 50


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

1 #start the the simulation process


2 $ns run
Defining nodes,links,queues and topology
Way to create a node:
view source
print?
1 set n0 [ns node]
In the above we created a node that is pointed by a variable n0.While referring the node in the script
we use $n0. Similarly we create another node n2.Now we will set a link between the two nodes.

1 $ns duplex-link $n0 $n2 10Mb 10ms DropTail

So we are creating a bi-directional link between n0 and n2 with a capacity of 10Mb/sec and a
propagation delay of 10ms.

In NS an output queue of a node is implemented as a part of a link whose input is that node to handle
the overflow at the queue.But if the buffer capacity of the output queue is exceeded then the last
packet arrived is dropped and here we will use a 'DropTail' option.Many other options such as
RED(Random Early Discard) mechanism, FQ(Fair Queuing), DRR(Deficit Round Robin),
SFQ(Stochastic Fair Queuing) are available.

So now we will define the buffer capacity of the queue related to the above link

1 #Set queue size of the link


2 $ns queue-limit $n0 $n2 20

so, if we summarize the above three things we get

01 #create nodes
02

DMI College Of Engineering 51


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

03 set n0 [$ns node]


04 set n1 [$ns node]
05 set n2 [$ns node]
06 set n3 [$ns node]
07 set n4 [$ns node]
08 set n5 [$ns node]
09
10 #create links between the nodes
11
12 $ns duplex-link $n0 $n2 10Mb 10ms DropTail
13 $ns duplex-link $n1 $n2 10Mb 10ms DropTail
14 $ns simplex-link $n2 $n3 0.3Mb 100ms DropTail
15 $ns simplex-link $n3 $n2 0.3Mb 100ms DropTail
16 $ns duplex-link $n0 $n2 0.5Mb 40ms DropTail
17 $ns duplex-link $n0 $n2 0.5Mb 40ms DropTail
18
19 #set queue-size of the link (n2-n3) to 20
20 $ns queue-limit $n2 $n3 20

Agents and applications

TCP
TCP is a dynamic reliable congestion protocol which is used to provide reliable transport of packets
from one host to another host by sending acknowledgements on proper transfer or loss of packets.Thus
TCP requires bi-directional links in order for acknowledgements to return to the source.

Now we will show how to set up tcp connection between two nodes

1 #setting a tcp connection


2
3 set tcp [new Agent/TCP]

DMI College Of Engineering 52


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

4 $ns attach-agent $n0 $tcp


5 set sink [new Agent/TCPSink]
6 $ns attach-agent $n4 $sink
7 $ns connect $tcp $sink
8 $tcp set fid_1
9 $tcp set packetSize_552

The command 'set tcp [new Agent/TCP]' gives a pointer called 'tcp' which indicates the tcp agent
which is a object of ns.Then the command '$ns attach-agent $n0 $tcp' defines the source node of tcp
connection. Next the command 'set sink [new Agent/TCPSink]' defines the destination of tcp by a
pointer called sink. The next command '$ns attach-agent $n4 $sink' defines the destination node as
n4.Next, the command '$ns connect $tcp $sink' makes the TCP connection between the source and the
destination.i.e n0 and n4.When we have several flows such as TCP, UDP etc in a network. So, to
identify these flows we mark these flows by using the command '$tcp set fid_1'. In the last line we set
the packet size of tcp as 552 while the default packet size of tcp is 1000.

FTP over TCP


File Transfer Protocol(FTP) is a standard mechanism provided by the Internet for transferring
files from one host to another. Well this is the most common task expected from a networking or a
inter networking . FTP differs from other client server applications in that it establishes between the
client and the server. One connection is used for data transfer and other one is used for providing
control information. FTP uses the services of the TCP. It needs two connections. The well Known port
21 is used for control connections and the other port 20 is used for data transfer.

Well here we will learn in how to run a FTP connection over a TCP

1 #Initiating FTP over TCP


2
3 set ftp [new Application/FTP]
4 $ftp attach-agent $tcp

DMI College Of Engineering 53


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

In above,the command 'set ftp [new Application/FTP]' gives a pointer called 'ftp' which indicates the
FTP application.Next, we attach the ftp application with tcp agent as FTP uses the services of TCP.

UDP
The User datagram Protocol is one of the main protocols of the Internet protocol suite.UDP
helps the host to send send messages in the form of datagrams to another host which is present in a
Internet protocol network without any kind of requirement for channel transmission setup. UDP
provides a unreliable service and the datagrams may arrive out of order,appear duplicated, or go
missing without notice. UDP assumes that error checking and correction is either not necessary or
performed in the application, avoiding the overhead of such processing at the network interface level.
Time-sensitive applications often use UDP because dropping packets is preferable to waiting for
delayed packets, which may not be an option in a real-time system.

Now we will learn how to create a UDP connection in network simulator.


1 # setup a UDP connection
2 set udp [new Agent/UDP]
3 $ns attach-agent $n1 $udp
4 $set null [new Agent/Null]
5 $ns attach-agent $n5 $null
6 $ns connect $udp $null
7 $udp set fid_2

Similarly,the command 'set udp [new Agent/UDP]' gives a pointer called 'udp' which indicates the udp
agent which is a object of ns.Then the command '$ns attach-agent $n1 $udp' defines the source node of
udp connection. Next the command 'set null [new Agent/Null]' defines the destination of udp by a
pointer called null. The next command '$ns attach-agent $n5 $null' defines the destination node as
n5.Next, the command '$ns connect $udp $null' makes the UDP connection between the source and
the destination.i.e n1 and n5.When we have several flows such as TCP,UDP etc in a network. So, to
identify these flows we mark these flows by using the command '$udp set fid_2

Constant Bit Rate(CBR)

DMI College Of Engineering 54


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

Constant Bit Rate (CBR) is a term used in telecommunications, relating to the quality of service.When
referring to codecs, constant bit rate encoding means that the rate at which a codec's output data should
be consumed is constant. CBR is useful for streaming multimedia content on limited capacity channels
since it is the maximum bit rate that matters, not the average, so CBR would be used to take advantage
of all of the capacity. CBR would not be the optimal choice for storage as it would not allocate enough
data for complex sections (resulting in degraded quality) while wasting data on simple sections.

CBR over UDP Connection

1 #setup cbr over udp


2
3 set cbr [new Application/Traffic/CBR]
4 $cbr attach-agent $udp
5 $cbr set packetSize_1000
6 $cbr set rate_0.01Mb
7 $cbr set random _false

In the above we define a CBR connection over a UDP one. Well we have already defined the UDP
source and UDP agent as same as TCP. Instead of defining the rate we define the time interval
between the transmission of packets in the command '$cbr set rate_0.01Mb'. Next, with the help of the
command '$cbr set random _false' we can set random noise in cbr traffic.we can keep the noise by
setting it to 'false' or we can set the noise on by the command '$cbr set random _1'. We can set by
packet size by using the command '$cbr set packetSize_(packetsize).We can set the packet size up to
sum value in bytes.

Scheduling Events

In ns the tcl script defines how to schedule the events or in other words at what time which event will
occur and stop. This can be done using the command
$ns at .

DMI College Of Engineering 55


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

So here in our program we will schedule the ftp and cbr.


1 # scheduling the events
2
3 $ns at 0.1 "cbr start"
4 $ns at 1.0 "ftp start"
5 $ns at 124.0 "ftp stop"
6 $ns at 124.5 "cbr stop"

Network Animator (NAM)

When we will run the above program in ns then we can can visualize the network in the NAM. But
instead of giving random positions to the nodes, we can give suitable initial positions to the nodes and
can form a suitable topology. So, in our program we can give positions to the nodes in NAM in the
following way

1 #Give position to the nodes in NAM


2
3 $ns duplex-link-op $n0 $n2 orient-right-down
4 $ns duplex-link-op $n1 $n2 orient-right-up
5 $ns simplex-link-op $n2 $n3 orient-right
6 $ns simplex-link-op $n3 $n2 orient-left
7 $ns duplex-link-op $n3 $n4 orient-right-up
8 $ns duplex-link-op $n3 $n5 orient-right-down

We can also define the color of cbr and tcp packets for identification in NAM.For this we use the
following command

1 #Marking the flows


2 $ns color1 Blue
3 $ns color2 Red

DMI College Of Engineering 56


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

To view the network animator we need to type the command: nam


Tracing
Tracing Objects
NS simulation can produce visualization trace as well as ASCII file corresponding to the
events that are registered at the network. While tracing ns inserts four objects: EnqT,DeqT,RecvT &
DrpT. EnqT registers information regarding the arrival of packet and is queued at the input queue of
the link. When overflow of a packet occurs, then the information of thye dropped packet is registered
in DrpT.DeqT holds the information abut the packet that is dequeued instantly.RecvT hold the
information about the packet that has been received instantly.

Structure of Trace files

1. The first field is event.It gives you four possible symbols '+' '-' 'r' 'd'.These four symbols correspond
respectively to enqueued, dequeued, received and dropped.
2. The second field gives the time at which the event occurs
3. The third field gives you the input node of the link at which the event occurs
4. The fourth field gives you the the output node at which the event occurs
5. The fifth field shows the information about the packet type.i.e whether the packet is UDP or TCP
6. The sixth field gives the packet size
7. The seventh field give information about some flags
8. The eight field is the flow id(fid) for IPv6 that a user can set for each flow in a tcl script.It is also used
for specifying the color of flow in NAM display
9. The ninth field is the source address
10. The tenth field is the destination address
11. The eleventh field is the network layer protocol's packet sequence number
12. The last field shows the unique id of packet

DMI College Of Engineering 57


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

Following are trace of two events:

r 1.84471 2 1 cbr 210 ------- 1 3.0 1.0 195 600


r 1.84566 2 0 ack 40 ------- 2 3.2 0.1 82 602

The trace file can be viewed with the cat command:

cat out.tr

RESULT:

Thus the introduction of Network Simulator was studied.

DMI College Of Engineering 58


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

EX NO. 10 SIMULATION OF CONGESTION CONTROL ALGORITHM

AIM:

To simulate a link failure and observe the congestion control algorithm using NS2.

ALGORITHM:

1. Create a simulation object


2. Set routing protocol to routing
3. Trace packets and all links onto NAM trace and to trace file
4. Create right nodes
5. Describe their layout topology as octagon
6. Add a sink agent to node
7. Connect source and sink.

PROGRAM:

set ns [new Simulator]

set nr [open thro_red.tr w]

$ns trace-all $nr

set nf [open thro.nam w]

$ns namtrace-all $nf

proc finish { } {

global ns nr nf

$ns flush-trace

close $nf

close $nr

exec nam thro.nam &

exit 0 }

DMI College Of Engineering 59


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

set n0 [$ns node]

set n1 [$ns node]

set n2 [$ns node]

set n3 [$ns node]

set n4 [$ns node]

set n5 [$ns node]

set n6 [$ns node]

set n7 [$ns node]

$ns duplex-link $n0 $n3 1Mb 10ms RED

$ns duplex-link $n1 $n3 1Mb 10ms RED

$ns duplex-link $n2 $n3 1Mb 10ms RED

$ns duplex-link $n3 $n4 1Mb 10ms RED

$ns duplex-link $n4 $n5 1Mb 10ms RED

$ns duplex-link $n4 $n6 1Mb 10ms RED

$ns duplex-link $n4 $n7 1Mb 10ms RED

$ns duplex-link-op $n0 $n3 orient right-up

$ns duplex-link-op $n3 $n4 orient middle

$ns duplex-link-op $n2 $n3 orient right-down

$ns duplex-link-op $n4 $n5 orient right-up

$ns duplex-link-op $n4 $n7 orient right-down

$ns duplex-link-op $n1 $n3 orient right

$ns duplex-link-op $n6 $n4 orient left

set udp0 [new Agent/UDP]

$ns attach-agent $n2 $udp0

set cbr0 [new Application/Traffic/CBR]

DMI College Of Engineering 60


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

$cbr0 set packetSize_ 500

$cbr0 set interval_ 0.005

$cbr0 attach-agent $udp0

set null0 [new Agent/Null]

$ns attach-agent $n5 $null0

$ns connect $udp0 $null0

set udp1 [new Agent/UDP]

$ns attach-agent $n1 $udp1

set cbr1 [new Application/Traffic/CBR]

$cbr1 set packetSize_ 500

$cbr1 set interval_ 0.005

$cbr1 attach-agent $udp1

set null0 [new Agent/Null]

$ns attach-agent $n6 $null0

$ns connect $udp1 $null0

set udp2 [new Agent/UDP]

$ns attach-agent $n0 $udp2

set cbr2 [new Application/Traffic/CBR]

$cbr2 set packet size_ 500

$cbr2 set interval_ 0.005

$cbr2 attach-agent $udp2

set null0 [new Agent/Null]

$ns attach-agent $n7 $null0

$ns connect $udp2 $null0

$udp0 set fid_ 1

DMI College Of Engineering 61


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

$udp1 set fid_ 2

$udp2 set fid_ 3

$ns color 1 Red

$ns color 2 Green

$ns color 2 Blue

$ns at 0.1 "$cbr0 start"

$ns at 0.2 "$cbr1 start"

$ns at 0.5 "$cbr2 start"

$ns at 4.0 "$cbr2 stop"

$ns at 4.2 "$cbr1 stop"

$ns at 4.5 "$cbr0 stop"

$ns at 5.0 "finish"

$ns run

DMI College Of Engineering 62


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

OUTPUT:

RESULT:

Thus the congestion control algorithm is simulated by using NS2.

DMI College Of Engineering 63


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

EX NO.11 IMPLEMENTATION OF DISTANCE VECTOR ROUTING


ALGORITHM

AIM:

To simulate and observe traffic route of a network using distance vector routing protocol.

ALGORITHM:

1. Create a simulator object


2. Set routing protocol to Distance vector routing
3. Trace packets on all links on to NAM trace and text trace file.
4. Define finish procedure to close files, flash tracing and run NAM
5. Create 5 nodes
6. Specify the link characteristics between the nodes
7. Describer their layout topology as a octagon
8. Add UDP agent for node n0
9. Create CBR traffic on the top of UDP and set traffic parameters
10. Add NULL agent to node n3
11. Connect source and sink
12. Schedule as follows
 Start traffic flow at 1.0
 Down the link n1 – n2 at 15.0
 Up the link n1 – n2 at 25.0
 Call finish procedure at 35.0
13. Start the scheduler
14. Observe the traffic route when the link is up and down
15. View the simulated events and trace file analyze it
16. Stop.

PROGRAM:

#Distance vector routing protocol – distvect.tcl

#Create a simulator object

set ns [new Simulator]

#Use distance vector routing

$ns rtproto DV

DMI College Of Engineering 64


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

#Open the nam trace file

set nf [open out.nam w]

$ns namtrace-all $nf

# Open tracefile

set nt [open trace.tr w]

$ns trace-all $nt

#Define 'finish' procedure

proc finish {} {

global ns nf

$ns flush-trace

#Close the trace file

close $nf

#Execute nam on the trace file

exec nam -a out.nam &

exit 0

# Create 8 nodes

set n1 [$ns node]

set n2 [$ns node]

set n3 [$ns node]

set n4 [$ns node]

set n5 [$ns node]

set n6 [$ns node]

set n7 [$ns node]

set n8 [$ns node]

DMI College Of Engineering 65


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

# Specify link characterestics

$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 $n6 1Mb 10ms DropTail

$ns duplex-link $n6 $n7 1Mb 10ms DropTail

$ns duplex-link $n7 $n8 1Mb 10ms DropTail

$ns duplex-link $n8 $n1 1Mb 10ms DropTail

# specify layout as a octagon

$ns duplex-link-op $n1 $n2 orient left-up

$ns duplex-link-op $n2 $n3 orient up

$ns duplex-link-op $n3 $n4 orient right-up

$ns duplex-link-op $n4 $n5 orient right

$ns duplex-link-op $n5 $n6 orient right-down

$ns duplex-link-op $n6 $n7 orient down

$ns duplex-link-op $n7 $n8 orient left-down

$ns duplex-link-op $n8 $n1 orient left

#Create a UDP agent and attach it to node n1

set udp0 [new Agent/UDP]

$ns attach-agent $n1 $udp0

#Create a CBR traffic source and attach it to udp0

set cbr0 [new Application/Traffic/CBR]

$cbr0 set packetSize_ 500

$cbr0 set interval_ 0.005

DMI College Of Engineering 66


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

$cbr0 attach-agent $udp0

#Create a Null agent (a traffic sink) and attach it to node n4

set null0 [new Agent/Null]

$ns attach-agent $n4 $null0

#Connect the traffic source with the traffic sink

$ns connect $udp0 $null0

#Schedule events for the CBR agent and the network dynamics

$ns at 0.0 "$n1 label Source"

$ns at 0.0 "$n4 label Destination"

$ns at 0.5 "$cbr0 start"

$ns rtmodel-at 1.0 down $n3 $n4

$ns rtmodel-at 2.0 up $n3 $n4

$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

DMI College Of Engineering 67


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

Output:

RESULT:

Thus the Distance Vector Routing algorithmwas simulated by using NS2

DMI College Of Engineering 68


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

EX. NO 12 IMPLEMENTATION OF LINK STATE ROUTING ALGORITHM

AIM:

To simulate and observe traffic route of a network using distance vector routing protocol.

ALGORITHM:

1. Create a simulator object


2. Set routing protocol to Distance vector routing
3. Trace packets on all links on to NAM trace and text trace file.
4. Define finish procedure to close files, flash tracing and run NAM
5. Create 5 nodes
6. Specify the link characteristics between the nodes
7. Describer their layout topology as a octagon
8. Add UDP agent for node n0
9. Create CBR traffic on the top of UDP and set traffic parameters
10. Add NULL agent to node n3
11. Connect source and sink
12. Schedule as follows
 Start traffic flow at 1.0
 Down the link n1 – n2 at 15.0
 Up the link n1 – n2 at 25.0
 Call finish procedure at 35.0
13. Start the scheduler
14. Observe the traffic route when the link is up and down
15. View the simulated events and trace file analyze it
16. Stop.

PROGRAM:

#Create a simulator object

set ns [new Simulator]

#Define different colors for data flows(for NAM)

$ns color 1 Blue

$ns color 2 Red

#Open the NAM trace file

DMI College Of Engineering 69


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

set nf [open out.nam w]

$ns namtrace-all $nf

#Define a 'finish' procedure

proc finish { } {

global ns nf

$ns flush-trace

#close the NAM trace file

close $nf

#Execute NAM on the trace file

exec nam out.nam &

exit 0

for {set i 0} {$i < 5} {incr i 1} {

set n($i) [$ns node]}

for {set i 0} {$i < 4} {incr i} {

$ns duplex-link $n($i) $n([expr $i+1]) 1Mb 10ms DropTail}

$ns duplex-link $n(0) $n(1) 1Mb 10ms DropTail

$ns duplex-link $n(1) $n(2) 1Mb 10ms DropTail

$ns duplex-link $n(2) $n(3) 1Mb 10ms DropTail

$ns duplex-link $n(3) $n(4) 1Mb 10ms DropTail

$ns duplex-link $n(4) $n(1) 1Mb 10ms DropTail

set udp0 [new Agent/UDP]

$ns attach-agent $n(0) $udp0

DMI College Of Engineering 70


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

set cbr0 [new Application/Traffic/CBR]

$cbr0 set packetSize_ 500

$cbr0 set interval_ 0.005

$cbr0 attach-agent $udp0

set null0 [new Agent/Null]

$ns attach-agent $n(3) $null0

$ns connect $udp0 $null0

$ns rtproto DV

$ns rtmodel-at 15.0 down $n(1) $n(2)

$ns rtmodel-at 25.0 up $n(1) $n(2)

$udp0 set fid_ 1

$ns color 1 Green

$ns at 1.0 "$cbr0 start"

$ns at 35 "finish"

#Run the simulation

$ns run

DMI College Of Engineering 71


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

OUTPUT:

RESULT:

Thus the Link State Routing algorithm was simulated by using NS2

DMI College Of Engineering 72


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

Content beyond syllabus

EX. NO 12 Applications using TCP and UDP Sockets (like SNMP)

AI M

To write a java program for SNMP 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

SOURCE CODE

import java.io.IOException;

import org.snmp4j.CommunityTarget;

import org.snmp4j.PDU;

import org.snmp4j.Snmp;

import org.snmp4j.Target;

import org.snmp4j.TransportMapping;

import org.snmp4j.event.ResponseEvent;

import org.snmp4j.mp.SnmpConstants;

import org.snmp4j.smi.Address;

import org.snmp4j.smi.GenericAddress;

import org.snmp4j.smi.OID; import org.snmp4j.smi.OctetString;

import org.snmp4j.smi.VariableBinding; import org.snmp4j.transport.DefaultUdpTransportMapping;

DMI College Of Engineering 73


EC6611 Computer Networks Lab Dept. of Electronics and communication Engg.

public class

SNMPManager { Snmp snmp = null; String address = null;

/** * Constructor * @param add */ public SNMPManager(String add)

SAMPLE INPUT& OUTPUT

Server

$ javac udpdnsserver.java $ java udpdnsserver Press Ctrl + C to Quit Request for host

yahoo.com Request for host cricinfo.com Request for host youtube.com

Client

$ javac udpdnsclient.java $ java udpdnsclient Enter the hostname : yahoo.com IP Address:

68.180.206.184 $ java udpdnsclient Enter the hostname : cricinfo.com IP Address:

80.168.92.140 $ java udpdnsclient Enter the hostname : youtube.com IP Address: Host Not

Found

RESULT

Thus the DNA application program was executed.

DMI College Of Engineering 74